reate a <filter> entry in your web.xml file. code example
Example 1: filters in xml
package demotest; import java.io.IOException;import java.util.Date; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import Javax.servlet.http.HttpServletRequest; public class GuruFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, Filterchain chain) throws IOException, ServletException { // TODO Auto-generated method stub HttpServletRequest req = (HttpServletRequest) request; String ipAddress = req.getRemoteAddr(); System.out.println("IP Address "+ipAddress + ", Time is" + new Date().toString()); // pass the request along the filter chain chain.doFilter(request, response); } /** * @see Filter#init(FilterConfig) */ public void init(FilterConfig fConfig) throws ServletException { String guruparam = fConfig.getInitParameter("guru-param"); //Print the init parameter System.out.println("Test Param: " + guruparam); }}
Example 2: filters in xml
<?xml version="1.0" encoding="UTF-8"?><web-app id="WebApp_ID" 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"> <display-name> test</display-name> <filter> <description> </description> <display-name> GuruFilter</display-name> <filter-name>GuruFilter</filter-name> <filter-class>demotest.GuruFilter</filter-class> <init-param> <param-name>guru-param</param-name> <param-value>This is guru paramter</param-value> </init-param> </filter> <filter-mapping> <filter-name>GuruFilter</filter-name> <url-pattern>/GuruFilter</url-pattern> </filter-mapping>