Some Unknown Facts About Java Servlet Filter

JAVA SERVLET FILTER

Java Servlet Filter

Java Servlet filter is used to intercept the request and do some pre-processing and can be used to intercept response and do post-processing before sending to a client in a web application. In this article, we will learn about the Servlet Filter in Java. We will look into various usage of servlet filter and its processing process. It mainly does two tasks, namely:

  1. Pre-Processing Task
  2. Post-processing Task

Filters:

  • A filter is a web component like Servlet.
  • Web Container is responsible for managing the complete lifecycle of Filter.

Java Servlet Filter

For creating any filter, you must implement the Filter interface. Filter interface provides the life cycle methods for a filter.

Methods

  Description 

 public void init(FilterConfig config) 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 a 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 a filter is taken out of the service.

Filter processing Diagram:

  • Servlet is responsible for core request processing. Before sending the request to a servlet. You may want to perform some tasks which are called as pre-processing tasks.
  • After request processing is completed by Servlet, you may want to perform some tasks which are called as post-processing tasks.
  • If you write the code for the pre-processing tasks and post-processing tasks across all the servlets code gets duplicated and gives the maintenance problem when you try to change that code.
  • To avoid the code duplication problem and maintenance problem, you need to write the pre-processing tasks and post-processing tasks code in a centralized place called Filter.
  • Following are various pre-processing tasks which you can perform on incoming request before core request processing.
    • Logging
    • Security checks include Authentication and Authorization.
    • Verifying Session Validity etc.
  • Following are various post-processing tasks which you can perform on outgoing response after core request processing.
    • Data Compression
    • Data Encryption/ Encoding etc.

Steps to develop the Filter:

  1. Write your own filter class by implementing Filter interface which is in Javax.servlet package.
  2. Your filter class has to override the following 3 lifecycle methods
    • init(FilterConfig fC): This method will be called at the time of creating the filter object.
    • doFilter(Servlet.req, Servlet.res, FilterChain fC): This method will be called when the client will send the request, a container will verify to invoke the filter for the current request.
    • Destroy(): Call to destroy the filter.

3. Configure the filter in the web.xml as follows:

<filter>
<filter-name>hello</filter-name>
<filter-class>com.xadminFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hello</filter-name>
<url-pattern>/hello.xadmin</url-pattern>
</filter-mapping

All the filters configured will be initialized by the container at the container startup. After submitting the request, the first web container will see any servlet is available with hello.xadmin. If available then it will keep in a stack, next it will check any filter is available with URL-hello.jtc, if available it will put in a stack and last it will process the first filter and inside filter we have servlet code that will execute the servlet.

Simple Example of  java servlet filter:

Index.html

<a href="servlet">click here to invoke Servlet</a>

CustFilter.java

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

public class CustFilter 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 invoked before");  
  chain.doFilter(req, resp);//sends request to next resource  
  out.print("filterinvoked after");  
  }  
  public void destroy() {}  
 }

HiServlet.java

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

Web.xml

<web-app>  
      
 <servlet>  
 <servlet-name>s1</servlet-name>  
 <servlet-class>HiServlet</servlet-class>  
 </servlet>  
   
 <servlet-mapping>  
 <servlet-name>s1</servlet-name>  
 <url-pattern>/servlet</url-pattern>  
 </servlet-mapping>  
    
 <filter>  
 <filter-name>f1</filter-name>  
  <filter-class>CustFilter</filter-class>  
  </filter>  
       
  <filter-mapping>  
  <filter-name>f1</filter-name>  
  <url-pattern>/servlet</url-pattern>  
  </filter-mapping>  
     
     
  </web-app>

An advantage of java servlet filter:

  1. A filter is pluggable.
  2. One filter doesn’t have a dependency on another resource.
  3. Less Maintenance

Filter Chaining:
Invoking Multiple Filters one by one as a chain is called as Filter Chaining. Filter chain will be managed by web-container automatically based on the order of filters configured in web.xml.You can add or remove the filters from the filter chain by changing web.xml. You can change the order of filters in the filter chain just by changing the filter configuration in web.xml.

Servlet Chaining:
Invoking multiple servlets (invoking service()) one by one as a chain is called as Servlet chaining. Servlet chain will be managed by the developer by writing the code in the servlet class by using request dispatcher (programming approach) You can add or remove the servlets from servlet chain by changing the code of Servlet. You can change the order of Servlets in servlets in servlet chain just by changing the code inside a servlet.

Conclusion:
By now you should have an idea of the kinds of things filters can do, and how to write your own java servlet filter. For more information, see the Servlet specifications available at Java.sun.com. In this article, we learned regarding the servlet filter with a simple example. and learned how to implement our own custom filter. Please, feel free to drop a comment in the below comment box if you find any doubt regarding the topic or you want to share more information about the topic. Happy Learning!

READ NOW:- session management in java

Leave a Reply

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