Servlet Filter

Filters are compontents that you can utilize and design to perform some separating assignments.

Filter is used for pre-processing of requests and post-processing of responses. You can have any number of filters for pre-processing of a request and post-processing of a response. Filters are configured in the deployment descriptor of a web application.

So maintenance cost will be less.

Servlet-Filter

How Filters Works?

When a request reaches the Web Container, it checks if any filter has URL patterns that matches the requested URL.

The Web Container finds the first channel with a coordinating URL design and filter's code is executed.

On the off chance that another channel has a coordinating URL design, its code is then executed. This proceeds until there are no channels with coordinating URL designs left.

On the off chance that no mistake happens, the solicitation goes to the objective servlet. Henceforth we know, that the solicitation will be gone to the objective servlet just when all the related Filters are effectively executed.

The servlet gives back the reaction back to its guest. The last channel that was connected to the solicitation is the first channel connected to the reaction.

Finally the reaction will be gone to the Web Container which passes it to the customer.

Usage of Filter

  1. recording all incoming requests
  2. logs the IP addresses of the computers from which the requests originate
  3. conversion
  4. data compression
  5. encryption and decryption
  6. input validation etc.

Advantage of Filter

  1. Filter is pluggable.
  2. One filter don't have dependency onto another resource.
  3. Less Maintenance

Filter API

The javax.servlet package contains the three interfaces of Filter API.

  1. Filter
  2. FilterChain
  3. FilterConfig

Filter interface

You must implement the Filter interface. Filter interface provides the life cycle methods for a filter.

Method Description
public void init(FilterConfig config)/td> init() method is invoked only once. It is used to initialize the filter.
public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain) doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks.
public void destroy() This is invoked only once when filter is taken out of the service.

What is FilterChain Interface?

FilterChain object is utilized to conjure the following channel in the chain, or if the calling channel is the last channel in the chain then the rosource toward the end of the chain summoned. The assets toward the end of Filter chain can either be an objective Servlet(in instance of solicitation stream) or the Client(in instance of reaction stream) as portrayed in the chart above.

Example Filter usage

Index.html

<a href="servlet1">click here</a> 

MyFilter.java

import java.io.IOException;   
import java.io.PrintWriter;   
  
import javax.servlet.*;   
  
public class MyFilter implements Filter{   
  
public void init(FilterConfig arg0) throws ServletException {}   
       
public void doFilter(ServletRequest req, ServletResponse resp,   
    FilterChain chain) throws IOException, ServletException {   
           
    PrintWriter out=resp.getWriter();   
    out.print("filter is invoked before");   
           
chain.doFilter(req, resp);//sends request to next resource   
           
    out.print("filter is invoked after");   
    }   
    public void destroy() {}   
}
  

HelloServlet.java

import java.io.IOException;   
import java.io.PrintWriter;   
  
import javax.servlet.ServletException;   
import javax.servlet.http.*;   
  
public class HelloServlet extends HttpServlet {   
    public void doGet(HttpServletRequest request, HttpServletResponse response)   
            throws ServletException, IOException {   
  
        response.setContentType("text/html");   
        PrintWriter out = response.getWriter();   
       
        out.print("
welcome to servlet
");                    }       }  

web.xml

<web-app>   
  
<servlet>   
<servlet-name>s1</servlet-name>   
<servlet-class>HelloServlet</servlet-class>   
</servlet>   
  
<servlet-mapping>   
<servlet-name>s1</servlet-name>   
<url-pattern>/servlet1</url-pattern>   
</servlet-mapping>   
  
<filter>   
<filter-name>f1</filter-name>   
<filter-class>MyFilter</filter-class>   
</filter>   
    
<filter-mapping>   
<filter-name>f1</filter-name>   
<url-pattern>/servlet1</url-pattern>   
</filter-mapping>   
  
  
</web-app>