Java Servlet Filter Introduction

Java Servlet Filter is the most important web component in java web application. It can intercept both request and response in the HTTP web communication. It can extract and manipulate the data exchanged between client and web server. So you can write code to pre-process the request and post-process the response with it. You can do actions such as logging, authentication, manipulate session attributes before the request pass to the called resources. You can also do actions such as encoding, formatting before the response data send back to the client.

What You Can Learn In This Article

  1. Servlet Filter’s advantage.
  2. Servlet Filter’s implementation.
  3. Create your first Servlet Filter use Eclipse.

Java Servlet Filter’s Advantage

  1. Make web application common tasks easy:
    java servlet filter component structure
    For example, when you want to validate a session object to make sure the user is logged in for every jsp page or servlet call. You can call the user authentication code in every called web resources. But it is not easy for maintenance. If you add new servlet or jsp pages. You have to add the authentication code to them also.Use java servlet filter, you can resolve the issue easily. You just need to write the user authentication code in the filter’s doFilter() method. And configure which web resources that this java servlet filter apply to in web.xml.Then all the request to the resources that filtered by this java servlet filter class will be processed by it first.If you add new web resources, you just need to add xml configuration in web.xml, do not need to change the source code.
  2.  Java Servlet Filter is pluggable:
    java servlet filter is pluggable
    You can create multiple java servlet filters and apply them to different resources. Each one can has it’s own purpose such as logging request data, authentication, change request charset, compress the response data and add cookie or header to the http response.You can also configure the java servlet filter order, so that the request will be processed by all of them one by one. This is also called java servlet filter chain.
  3. Dynamic : Java Servlet Filter is loaded on web container startup. When a request come in, it will be invoked by the container at runtime. And intercept the request and response automatically.
  4. Declarative : Java Servlet Filter is declared in web.xml (java web application descriptor). If you want to configure a new one, you just need to declare it in web.xml, do not need to change java and jsp pages code.
  5. Modular : Because each Filter is usually used to encapsulate one common logic function. So one filter class is just a modular function unit. You can easily add or remove any filter ( modular function ) to web application resources.
  6. Portable : Based on java, so it is portable in may java platform and web containers.
  7. Reusable : Because it is portable and configured in a declarative way, so it is easy to be reused in different web applications.
  8. Transparent : Because it process the request or response between the client and server without any influence to the core processing provided by the web resources. So to the target resources, Filter is transparent, it can be added or removed to the resource when necessary. But it will not break the web resources down.
  9. Conclusion : In one word, Java Servlet Filter is modular, portable and reusable web components declared through web.xml flexibly. It can dynamically pre-process request or post-process response transparently.
READ :   Servlet Overview

Servlet Filter Implementation

  1. Implement servlet filter interface to crate it.
  2. Configure the created class in web.xml.
  3. Package the web application and deploy it to tomcat.

Implement Servlet Filer Interface

The javax.servlet.Filter interface is used to crate a filter class. It contains all the Filter’s life cycle methods. It is managed by web container.

  1. void init(FilterConfig fConfig) : This method is called when the container load and initialize the Filter class. It is called only once in it’s life cycle. You should initialize resources such as get database connection, open file handler in it.
    FilterConfig input parameter is used to get this Filter’s init parameters from web application configuration file(web.xml). It can also return the ServletContext object to get container related information.
  2. doFilter(ServletRequest request, ServletResponse response, FilterChain chain) : Every time web container invoke this class, the java code in this method will be performed. You can use web container provided request and response object to extract and manipulate the request or response data. You can invoke the next filter in the filter chain or pass request data to target resource use the FilterChain object.
  3. void destroy() : This method is called when the container remove the Filter object. You should close any resources ( such as database connection, file handler) that opened in init() mehtod. This method is called only once.

Configure Filter In Configuration File

There are two way to configure a Filter object.

  1. Declare In web.xml

      <!-- This is declaration. -->
      <filter>
        <display-name>Authenticate login credential.</display-name>
        <!-- This is the name. -->
        <filter-name>LoginAuthFilter</filter-name>
        <!-- This is the implementation class.  -->
        <filter-class>com.dev2qa.example.servlet.filter.LoginAuthFilter</filter-class>
      </filter>
      
      <!-- When request url match the url-pattern, the mapping filter will be invoked. -->
      <filter-mapping>
        <!-- This is just the filter name decalred above. -->
        <filter-name>LoginAuthFilter</filter-name>
        <!-- This is the request url such as http://localhost:8080/Dev2qaWebAppExample/HelloWorld -->
        <url-pattern>/HelloWorld</url-pattern>
      </filter-mapping>
  2. Use WebFilter Annotation
    In Servlet 3.0, javax.servlet.annotation.WebFilter can be used to declare it. This annotation also has other parameters that can define it’s name, init parameters, url patterns etc. But if you change the configuration often, you had better use web.xml. Because it do not need to recompile the java class. 
READ :   Servlet RequestDispatcher And SendRedirect

Create Java Servlet Filter Class Use Eclipse

  1. Open Eclipse and create a java web project. You can read article Debug Java EE Web Application In Tomcat Use Eclipse to learn how to do this.
  2. Right click the java project name, click ” New —> Others ” in the popup menu. Input the keyword in the search text box. Choose the icon in below dialog. Click Next.
    create servlet filter class popup dialog
  3. Input package name, class name in below wizard dialog. Then click Next.
    java servlet filter package and class name wizard
  4. In this dialog, you can either edit initialization parameters or Filter Mappings. Because we do not have any init parameters, so we just choose the default Filter mapping item, and click Edit button.
    edit java servlet filter mapping eclipse wizard dialog
  5. In this dialog, you can choose either Servlet or URL pattern radio button in the top of the wizard. Now select URL pattern. Input /HelloWorld in url pattern input text box. Click Ok. Click Next.
    java servlet filter mapping url-pattern
  6. Click Finish button.
  7. Now you can see the newly created Filter is added in WEB-INF/web.xml file.
  8. You can also see the java file in left panel.
    java servlet filter class in left panel
  9. Edit LoginAuthFilter.java with below java code. Below java code will print out one line text to console in init(), doFilter() and destroy() method.
    	/**
    	 * @see Filter#destroy()
    	 */
    	public void destroy() {
    		System.out.println("LoginAuthFilter destroy method. ");
    	}
    
    	/**
    	 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
    	 */
    	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    		
    		System.out.println("LoginAuthFilter doFilter method. ");
    
    		chain.doFilter(request, response);
    	}
    
    	/**
    	 * @see Filter#init(FilterConfig)
    	 */
    	public void init(FilterConfig fConfig) throws ServletException {
    		System.out.println("LoginAuthFilter init method. ");
    	}
  10. Now, start the Tomcat server. Input url in your favorite web browser: http://localhost:8080/Dev2qaWebAppExample/HelloWorld. And then stop the Tomcat server. You can see below output in the web console.
    LoginAuthFilter init method. 
    LoginAuthFilter doFilter method. 
    LoginAuthFilter destroy method.

Download “JavaServletFilterIntroductionExampleCode.zip” JavaServletFilterIntroductionExampleCode.zip – Downloaded 48 times – 62 KB

(Visited 381 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.