Servlet Filters

 

A Servlet filter is an object that can intercept HTTP requests targeted at your web application. We can intercept the request, modify it before the request accesses the back-end resources.

 

Using Filters, we can as well manipulate the response from the server before it reaches to the Client.

servlets14

What is a Servlet Filter ?

Servlet Filter is a small amount of code that execute before or after serving up a web resource. A Servlet Filter does not create it’s own response, but it can manipulate a Servlet request or a Servlet response.

Any logic that we want to execute before the servlet request is processed by the servlet can be put into the filter. Similary, for the response.

Pre-processing and post-processing logic can be put into filter.

Filters follow the decorator design pattern. It dynamically extends the Servlet behavior without adding the Servlet code or necessarily extending the Servlet source code.

A Servlet filter can intercept requests both for Servlets, JSP’s, HTML files or other static content, as illustrated in the diagram below:

A Servlet Filter in a Java Web Application

Use of Servlet Filters allow us to replace something called as Servlet chaining or chaining Servlets.

Filter chaining :

Filter chaining is the concept of applying more than one filter to a servlet or a JSP. Example, like one filter doing encryption/decryption stuff and another filter doing zipping/unzipping kind of stuff.

We can map multiple filters to a single web resource. As well, we can map a filter to multiple web resources.

servlets16

Depends on business requirement, we can have multiple filters handling multiple responsibilities.

  • Filters have initialization parameters, so behavior can be parameterized and controlled through the deployment descriptor.
  • Filters have access to the Servlet Request Headers, so they can manipulate the headers, they can add objects to the request attributes, they can add objects to the session.
  • Filters also have access to the ServletContext, and all the resources which are accessed by the Servlet.

Use of Servlet Filters :

  • Record all the incoming requests
  • Log the IP addresses of the computers from which the request originates
  • Conversions
  • Data compressions
  • Encryption and Decryption
  • Input validation
  • Authentication and Authorization
  • Audit access to sensitive resources
  • Email to system administrators on every application error
  • Compress the response to reduce our bandwidth to make application perform better.

 

Servlet Filter Life cycle :

servlets17

In order to create a servlet filter you must implement the javax.servlet.Filter interface. Here is an example servlet filter implementation:

import javax.servlet.*;
import java.io.IOException;

/**

 */
public class SimpleServletFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
                       throws IOException, ServletException {
    }

    public void destroy() {
    }
}

When the servlet filter is loaded the first time, its init() method is called, just like with servlets.

When a HTTP request arrives at your web application which the filter intercepts, the filter can inspect the request URI, the request parameters and the request headers, and based on that decide if it wants to block or forward the request to the target servlet, JSP etc.

It is the doFilter() method that does the interception.

How ServletFilter works ??

servlets18

Example :

servlets19

Mapping filter with a Servlet :

We need to add an entry in the deployment descriptor file.

servlets20

Example :

 <filter>
    <filter-name>Authenticate</filter-name>
    <filter-class>demo.pluralsight.com.AuthenticationFilter</filter-class>
 </filter>
 <filter-mapping>
    <filter-name>Authenticate</filter-name>
    <url-pattern>/SecuredServlet</url-pattern>
 </filter-mapping>