Saturday, 4 February 2012

what is a filter and how it works ?

A filter is used to dynamically intercept request and response objects and change or use the data present in them. Filters should be configured in the web deployment descriptor (web.xml). Filters can perform essential functions like authentication blocking, logging, content display style conversion, etc.
Filters can also be used to transform the response from servlet to jsp before sending it back to client.
A good way to think of servlet filters is as a chain of steps that a request and response must go through before reaching a servlet, jsp or static resources such as HTML.
Servlet filter is an object which provides the implementation of filter interface

Example program for Servlet filter
Scenario: wikipedia have wiki pages. We can see and also modify the wiki pages.
Requirement: We have to track the users who ever modify the wiki pages..

import javax.servlet.ServletException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;


public class FilterEx implements Filter {
private FilterConfig fc;
@Override
public void init(FilterConfig config) throws ServletException {
this.fc = config;
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
String name = httpReq.getRemoteUser();
if(name != null)
{
fc.getServletContext().log("User" +name+ "is updating");
}
}
@Override
public void destroy() {
// TODO Auto-generated method stub
}
}
web.xml

<filter>
<filter-name>ApplicationExample</filter-name>
<filter-class>com.files.FilterEx</filter-class>
</filter>
<filter-mapping>
<filter-name>ApplicationExample</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>


To develop the servlet filter you need to follow the steps.

  • First we need to implement the filter Interface.
  • The filter implementation class contains doFilter(). Our action to coded in the doFilter().
  • Then the last step is to configure this Servlet filter in the deployment descriptor(web.xml).
How it works:
When we deploy the jar into server, first it reads the init() of our Servlet filter. Then with respective to the request Servlet filter doFilter() will be executed.

No comments:

Post a Comment