What is java Filter ? With examples.

What is java Filter ? With examples ...

A filter is nothing but java class; A filter offers a useful way of performing filtered functionality in a java web application. Typically, filters do not generate content themselves, although in this example, the filter will generate some minimal content to show how it is called. A filter implements the javax.servlet.Filter interface. The primary filter functionality is implemented by the doFilter() method of the filter.
Method Summary
 voiddestroy()
          Called by the web container to indicate to a filter that it is being taken out of service.
 voiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)
          The doFilter method of the Filter is called by the container each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain.
 voidinit(FilterConfig filterConfig)
          Called by the web container to indicate to a filter that it is being placed into service.
A filter is typically used to perform a particular piece of functionality either before or after the primary functionality of a web application is performed. As an example, if a request is made for a particular resource such as a servlet and a filter is used, the filter code may execute and then pass the user on to the servlet. As a further example, the filter might determine that the user does not have permissions to access a particular servlet, and it might send the user to an error page rather than to the requested resource.

Here is some  code of simple java that is basic servlet that willl access, the TestServlet class.

  • TestServlet
package com.cakes;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TestServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

 private static final long serialVersionUID = 1L;

 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  performTask(request, response);
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
   IOException {
  performTask(request, response);
 }

 private void performTask(HttpServletRequest request, HttpServletResponse response) throws ServletException,
   IOException {
  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("TestServlet says hi");
 }

}

Here is some code for filter , it content java code for  request and response handling..

  • This filter will display the value of the my-param init parameter, and it will also display the values of any request parameters. 
  • MyFilter.java

package com.cakes;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class MyFilter implements Filter {

 FilterConfig filterConfig = null;

 public void init(FilterConfig filterConfig) throws ServletException {
  this.filterConfig = filterConfig;
 }

 public void destroy() {
 }

 public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
   throws IOException, ServletException {
  servletResponse.setContentType("text/html");
  
  PrintWriter out = servletResponse.getWriter();
  out.println("my-param (InitParameter): " + filterConfig.getInitParameter("my-param"));
  out.println("<br/><br/>Parameters:<br/>");
  Enumeration<String> parameterNames = servletRequest.getParameterNames();
  if (parameterNames.hasMoreElements()) {
   while (parameterNames.hasMoreElements()) {
    String name = parameterNames.nextElement();
    String value = servletRequest.getParameter(name);
    out.println("name:" + name + ", value: " + value + "<br/>");
   }
  } else {
   out.println("---None---<br/>");
  }
  out.println("<br/>Start Regular Content:<br/><hr/>");
  filterChain.doFilter(servletRequest, servletResponse);
  out.println("<br/><hr/>End Regular Content:<br/>");

 }

}
Here we can see an example of a filter declared in web.xml. Notice that init parameters can be passed to a filter, just like they can be passed to a servlet. Notice that the filter-mapping has the url-pattern of /*. This routes all requests to the web application through the MyFilter filter.

  • web.xml 
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <filter>
  <filter-name>MyFilter</filter-name>
  <filter-class>com.cakes.MyFilter</filter-class>
  <init-param>
   <param-name>my-param</param-name>
   <param-value>my-param-value</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>MyFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

 <servlet>
  <servlet-name>TestServlet</servlet-name>
  <servlet-class>com.cakes.TestServlet</servlet-class>
 </servlet>
 <servlet-mapping>
  <servlet-name>TestServlet</servlet-name>
  <url-pattern>/test</url-pattern>
 </servlet-mapping>

 <welcome-file-list>
  <welcome-file>index.jsp</welcome-file>
 </welcome-file-list>

</web-app>
Fired up the application in Tomcat and made a request for the TestServlet via the /test mapping in web.xml. As you can see, the MyFilter class is executed, and in the 'Regular Content' section we can see the regular content served up by the servlet. Now Ready for run just check first Tomcat is start and then  goto your web browser and type  following URL   http://localhost:8080/filter-test/test
Anther way is you can just use Eclipse for easy development of java filter ... 

Comments

Popular posts from this blog

Java Access Specifiers and Modifiers

Java Chat Application or Java Messenger