What is Servlet Filter?

Servlet filter is an object which is invoked at the preprocessing and postprocessing of a http request.
Servlet Filters are pluggable and configured in deployment descriptor (web.xml) file. Servlets and filters both are unaware of each other and we can add or remove a servlet filter just by editing web.xml.
A servlet filter can intercept requests both for servlets, JSP's, HTML files or other static content, as shown in diagram below:

pic

Why Servlet Filter?


We know that how we can manage session in web application and if we want to make sure that a resource is accessible only when user session is valid, we can achieve this using servlet session attributes. This approach is simple but if we have a lot of servlets and jsps, then it will become hard to maintain due to redundant code. If we want to modify someattribute name in future, we have to change all the places where we have session authentication.
That’s why we have servlet filter. Servlet Filters are pluggable java components that we use to intercept and process requests before they are sent to servlets and response after servlet code is finished and before container sends the response back to the client.

Filter API

Filter have its own API like Servlet. There are 3 interfaces of Filter API present in javax.servlet package like:

  1. Filter
  2. FilterChain
  3. FilterConfig

To create a servlet filter we have to implement the javax.servlet.Filter interface. Let’s see an example servlet filter implementation:

Required Files:

  1. Index.html
  2. FilterDemo.java
  3. HiServlet.java
  4. web.xml
index.html
<a href="MyServlet1">click</a>
FilterDemo.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class FilterDemo implements Filter{
    public void init(FilterConfig arg0) throws ServletException {};
    public void doFilter(ServletRequest request, ServletResponse response,
    FilterChain chain) throws IOException, ServletException {
        PrintWriter out=response.getWriter();
        out.print("filter is invoking before);
        chain.doFilter(request, response);            //sends request to resource

        out.print("filter is invoking after");
    }
    public void destroy() {}
}
HiServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
importjavax.servlet.http.*;

public class HiServlet extends HttpServlet { 
    public void doGet(HttpServletRequest request, HttpServletResponse esponse)
    throws ServletException, IOException{

        response.setContentType("text/html");
        PrintWriter out=response.getWriter();

        out.print("<br>welcome to JavaRace<br>");
    }

}
web.xml

For defining the filter, filter element of web-app must be defined just like servlet.

<web-app>
    <servlet>
        <servlet-name>HiServlet</servlet-name>
        <servlet-class>HiServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>HiServlet</servlet-name>
        <url-pattern>/s1</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>MyFilter</filter-name>
        <filter-class>FilterDemo</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>MyFilter</filter-name>
        <url-pattern>/s1</url-pattern>
    </filter-mapping>
</web-app>

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 resources(servlet, jsp, etc).


About the Author



Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





 PreviousNext