JSP Filter Methods

Following are the filter methods:

Public void doFilter(ServletRequest,ServletResponse, FilterChain)

This is called everytime when a request/response is passed from every client when it is requested from a resource.

Public void init(FilterConfig)

This is to indicate that filter in JSP is placed into service

Public void destroy()

This to indicate the filter has been taken out from service.

Example:

In this example, we have created filter and mapped in Java web.xml filter Gurufilter.java Web.xml

Explanation of the code:

Gurufilter.java Code Line 17-32: Here we are using “doFilter” method where we are getting request object(in our example the request object is req(HttpServletRequest object)) and get the remote address of the client and printing on the console and also printing date and time on the console. Code Line 33-37: Here we are using init method where we are taking the init parameter and printing init parameter in the console. Web.xml Code Line 10-11 – Filter mapping in web.xml for GuruFilter with the class name GuruFilter.java where we have filter-name as GuruFilter and filter class which is directory path of GuruFilter class Code Line 13-15 – Mapping the init parameter named guru-param and getting the value of it which is placed under filter tag so this init-param has been defined for gurufilter

Output:

When you execute the above code, you get the following output:

The output is Test Param from the init parameter And fetching IP address, date and time of it.