Servlet Filters are java components that can be used to intercept and process requests before they are sent to servlets and response after servlet code is finished and before container sends the response back to the client.
Authentication Filter
Data Compression
Logging and Auditing
Encryption Filter
Filters are configured in web.xml and we can have multiple filter for one resource.It is created by implementeing javax.servlet.Filter interface.
1) void init(FilterConfig fg) It is 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.
FilterConfig is used by container to provide init parameters and servlet context object to the Filter.
2) doFilter(ServletRequest req, ServletResponse res, FilterChain fc) It is called every time by container when it has to apply filter to a resource.
Container provides request and response object references to filter as argument. FilterChain is used to invoke the next filter in the chain.
3) void destroy() It is called by the web container to indicate to a filter that it is being taken out of service.
<filter> <filter-name>LogFilter</filter-name> <filter-class>LogFilter</filter-class> <init-param> <param-name>name</param-name> <param-value>values</param-value> </init-param> </filter> <filter> <filter-name>AuthenFilter</filter-name> <filter-class>AuthenFilter</filter-class> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter-mapping> <filter-name>AuthenticationFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
With above configuration ist LogFilter will be applied and then AuthenticationFilter.
Example:
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class LogFilter implements Filter { public void init(FilterConfig config) throws ServletException{ } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws java.io.IOException, ServletException { System.out.println("In Filter before servlet call"); //Pass request back down the filter chain or execute servlet chain.doFilter(request,response); System.out.println("In Filter after servlet call"); } public void destroy( ){ } }