Java Servlet Filter is the most important web component in java web application. It can intercept both requests and responses in the HTTP web communication. It can extract and manipulate the data exchanged between the client and the 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.
1. What You Can Learn In This Article?
- Servlet Filter’s advantage.
- Servlet Filter’s implementation.
- Create your first Servlet Filter use Eclipse.
2. Java Servlet Filter’s Advantage.
- Make web application common tasks easy: 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 resource. 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 applies to in web.xml. Then all the requests to the resources 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.
- Java Servlet Filter is pluggable: You can create multiple java servlet filters and apply them to different resources. Each one can have 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 the java servlet filter chain.
- Dynamic: Java Servlet Filter is loaded on web container startup. When a request comes in, it will be invoked by the container at runtime. And intercept the request and response automatically.
- 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.
- 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.
- Portable: Based on java, so it is portable in many java platforms and web containers.
- Reusable: Because it is portable and configured in a declarative way, so it is easy to be reused in different web applications.
- Transparent: Because it processes the request or response between the client and server without any influence on the core processing provided by the web resources. So to the target resources, the Filter is transparent, it can be added or removed to the resource when necessary. But it will not break the web resources down.
- Conclusion: In one word, Java Servlet Filter is modular, portable, and reusable web components declared through web.xml flexibly. It can dynamically pre-process requests or post-process responses transparently.
3. Servlet Filter Implementation.
- Implement a servlet filter interface to create it.
- Configure the created class in web.xml.
- Package the web application and deploy it to tomcat.
3.1 Implement Servlet Filer Interface.
The javax.servlet.Filter interface is used to create a filter class. It contains all the Filter’s life cycle methods. It is managed by a web container.
- 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 the web application configuration file(web.xml). It can also return the ServletContext object to get container-related information.
- doFilter(ServletRequest request, ServletResponse response, FilterChain chain): Every time a web container invokes this class, the java code in this method will be performed. You can use web container-provided request and response objects to extract and manipulate the request or response data. You can invoke the next filter in the filter chain or pass request data to the target resource using the FilterChain object.
- void destroy(): This method is called when the container removes the Filter object. You should close any resources ( such as database connection, file handler ) that opened in init() method. This method is called only once.
3.2 Configure Filter In Configuration File.
There are two ways to configure a Filter object.
- 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>
- 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 does not need to recompile the java class.
3.3 Create Java Servlet Filter Class Use Eclipse.
- Open Eclipse and create a java web project. You can read the article Debug Java EE Web Application In Tomcat Use Eclipse to learn how to do this.
- Right-click the java project name, click ” New —> Others ” in the popup menu to open the Select a wizard window. Input the keyword Filter in the search text box. Choose the icon Web / Filter in the Wizard panel below it, click the Next button.
- Input Java package name ( com.dev2qa.example.servlet.filter ), Class name ( LoginAuthFilter ) in the Create Filter wizard dialog. Then click Next.
- In this dialog, you can either edit Initialization parameters or Filter Mappings ( like servlet mappings ). Because we do not have any init parameters, so we just choose the default Filter mapping item and click the Edit button.
- In the Edit Filter Mapping dialog, you can choose either the Servlet or URL pattern radio button at the top of the wizard. In this example, I select the URL pattern radio. Input /HelloWorld in url Pattern input text box. Click Ok. Click Next.
- Click the Finish button.
- Now you can see the newly created Filter is added in the WEB-INF/web.xml file.
<filter> <display-name>LoginAuthFilter</display-name> <filter-name>LoginAuthFilter</filter-name> <filter-class>com.dev2qa.example.servlet.filter.LoginAuthFilter</filter-class> </filter> <filter-mapping> <filter-name>LoginAuthFilter</filter-name> <url-pattern>/HelloWorld</url-pattern> </filter-mapping>
- You can also see the java file com.dev2qa.example.servlet.filter.LoginAuthFilter.java in the eclipse IDE left panel java project.
- Edit LoginAuthFilter.java with the 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. "); }
- 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 the below output in the web console.
LoginAuthFilter init method. LoginAuthFilter doFilter method. LoginAuthFilter destroy method.