How to use a filter in JSP?

JSPJava 8Object Oriented ProgrammingProgramming

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 java.io.*;
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 java.io.IOException, 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
      chain.doFilter(request,response);
   }
   public void destroy( ) {
      /* Called before the Filter instance is removed
      from service by the web container*/
   }
}

Compile LogFilter.java 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

<filter>
   <filter-name>LogFilter</filter-name>
   <filter-class>LogFilter</filter-class>
   <init-param>
      <param-name>test-param</param-name>
      <param-value>Initialization Paramter</param-value>
      </init-param>
</filter>
<filter-mapping>
   <filter-name>LogFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>

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.

raja
Published on 20-Mar-2019 09:59:53
Advertisements