Master java skills

Filter in Servlet

In web applications, sometimes, we need some kind of pre and postprocessing of requests and responses, such as encryption and decription of data, conversion, compression of data.

This can be achieved by the use of filter classes in servlets. These are pluggable components, meaning they will be applied to only those filters which we want to. We just need to make filters entries in the web.xml file.

How to define filter in web.xml

<web-app>  
  
    <filter> 
        <filter-class>...</filter-class>  
        <filter-name></filter-name>  
    </filter>  
   
    <filter-mapping>  
        <filter-name>...</filter-name>  
        <url-pattern>...</url-pattern>  
    </filter-mapping>  
  
</web-app>  

What is the need of filters

Let’s consider a scenario where we want to store some data in the database. To validate that the valid data should be stored, we can validate using javascript also at the client side. But if the javascript is disabled, then what? There comes the use of filters at the server side.

Advantage of using filters

  • Filters can be used for authentication and authorization of requests for resources.
  • Filters can also be used for formatting of request body or header before sending it to the servlet.
  • For compression of the response data sent to the client.
  • Filters can be used for adding cookies and header information to the response etc.
  • Filters can be used for input validation.

Important points about filters

  1. Filters are used for pre and post processing of requests.
  2. Filters are java classes which are created by extending javax.servlet.Filter interface.
  3. They have to be defined in web.xml
  4. Filters can be applied to a single servlet, multiple servlets or all the servlets of the application

How to implement filter

Write a class by extending javax.servlet.Filter interface. There are three methods in this interface – init(), doFilter(), destroy(). We have to override these methods. They are the lifecycle methods of a Filter.

doFilter will be executed in both preprocessing + postprocessing.

doFilter() method takes three arguments – ServletRequest, ServletResponse, FilterChain. With the help of FilterChain, we can forward the request after successful authentication.

Filter Example

package com.sks.filter;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ExampleFilter implements Filter {

	public void init(FilterConfig config) throws ServletException {
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
			throws IOException, ServletException {

		PrintWriter out = resp.getWriter();
		out.print("filter is invoked before servlet<br><br>");

		chain.doFilter(req, resp);// sends request to intended servlet

		out.print("<br><br> filter is invoked after servlet");
	}

	public void destroy() {
	}
}

ExampleServlet.java

package com.sks;

import java.io.IOException;
import java.io.PrintWriter;

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

public class ExampleServlet 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 example servlet<br>");

	}

}

On the below mapping, we can see that <url-pattern> for filter1 is /*. This means this filter will apply to all the servlets.

<web-app>  

    <filter>
	<filter-class>com.sks.filter.ExampleFilter</filter-class>
	<filter-name>filter1</filter-name>
    </filter>

    <filter-mapping>
	<filter-name>filter1</filter-name>
	<url-pattern>/*</url-pattern>
    </filter-mapping>
  
    <servlet>  
        <servlet-class>com.sks.ExampleServlet</servlet-class>  
        <servlet-name>exampleServlet</servlet-name>  
    </servlet>  
  
    <servlet-mapping>  
        <servlet-name>exampleServlet</servlet-name>  
        <url-pattern>/exampleServlet</url-pattern>  
    </servlet-mapping>  
  
    <servlet>  
        <servlet-class>com.javatrainingschool.HttpSessionExampleServlet</servlet-class> 
        <servlet-name>httpSessionServlet</servlet-name>  
    </servlet>  
  
    <servlet-mapping>  
        <servlet-name>httpSessionServlet</servlet-name>  
        <url-pattern>/httpSessionServlet</url-pattern>  
    </servlet-mapping>  
  
</web-app> 

Run the application and test

url – http://localhost:8080/my-first-servlet-app/exampleServlet