How to use a filter in JSP?

Following example shows how to print the client's IP address and the current date time, each time it would access any JSP file. This example will give you a basic understanding of the JSP Filter, but you can write more sophisticated filter applications using the same concept −

// Import required java libraries
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Implements Filter class
public class LogFilter implements Filter {
   public void init(FilterConfig config) throws ServletException {
      // Get init parameter
      String testParam = config.getInitParameter("test-param");
      //Print the init parameter
      System.out.println("Test Param: " + testParam);
   public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
   throws, ServletException {

      // Get the IP address of client machine.
      String ipAddress = request.getRemoteAddr();
      // Log the IP address and current timestamp.
      System.out.println("IP "+ ipAddress + ", Time "+ new Date().toString());
      // Pass request back down the filter chain
   public void destroy( ) {
      /* Called before the Filter instance is removed
      from service by the web container*/

Compile in the usual way and put your LogFilter.class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes.

JSP Filter Mapping in Web.xml

Filters are defined and then mapped to a URL or JSP file name, in much the same way as Servlet is defined and then mapped to a URL pattern in web.xml file. Create the following entry for filter tag in the deployment descriptor file web.xml

      <param-value>Initialization Paramter</param-value>

The above filter will apply to all the servlets and JSP because we specified /* in our configuration. You can specify a particular servlet or the JSP path if you want to apply the filter on a few servlets or JSP only.

Now try to call any servlet or JSP and you will see generated log in your web server log. You can use Log4J logger to log above log in a separate file.