Thursday, June 30, 2011

What is a Servlet Filter java

What is a Servlet Filter java

Explain the Servlet Filter?

what purpose used the Servlet Filter?


Filters are not servlets. They do not implement and override HttpServlet methods such as doGet() or doPost(). Rather, a filter implements the methods of the javax.servlet.Filter interface. The methods are:

init()


destroy()


doFilter()


* Intercept a servlet's invocation before the servlet is called
* Examine a request before a servlet is called
* Modify the request headers and request data by providing a customized version of the request object that wraps the real request
* Modify the response headers and response data by providing a customized version of the response object that wraps the real response
* Intercept a servlet's invocation after the servlet is called

A filter implements javax.servlet.Filter and defines its three methods:

1. void init(FilterConfig config) throws ServletException: Called before the filter goes into service, and sets the filter's configuration object
2. void destroy(): Called after the filter has been taken out of service
3. void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException: Performs the actual filtering work


Example

import javax.servlet.*;

public class MyFilter implements javax.servlet.Filter {
public FilterConfig filterConfig; //1

public void doFilter(final ServletRequest request, //2
final ServletResponse response,
FilterChain chain)
throws java.io.IOException, javax.servlet.ServletException {
chain.doFilter(request,response); //3
}

public void init(final FilterConfig filterConfig) { //4
this.filterConfig = filterConfig;
}

public void destroy() { //5
}
}

No comments:

Post a Comment