Servlet Filter

Filter is an object that transforms the information of request or response from one format to another. The filter class is declared in the deployment class.

The other types that can be implemented in a web application using filters is:

  • Security verification.
  • Session validation.
  • Internationalization.
  • Triggering resource access events.
  • Data compression.
  • MIME type changing.
  • Caching.
  • XSL transformation of XML response from a servlet

Methods Of Filter Interface

init (FilterConfig)It is used during the initialization.
doFilter(ServletRequest, ServletResponse, FilterChain)It used when more than one filter is implemented in web application.
destroy( )Destroy the instance of the filter class.

Example of Servlet Filter

Listing 1:FilterServ



import javax.servlet.*;

public class FilterServ implements Filter {
	public void  init(FilterConfig FilCon)

	      String test = FilCon.getInitParameter("Javabeat");

	      System.out.println("Javabeat: " + test);

 	 public void doFilter(ServletRequest req,
                       ServletResponse res,
                       FilterChain fc)
       		throws IOException, ServletExpection

	  	PrintWriter out= res.getWriter();



  	public void destroy( )


Details of the above code

The filter has initialization parameter, these can be read in the init method using the FilterConfig.

Listing 2:Web.xml



	 	 <param-value>Hello World !!!!!!!!</param-value>


   		<filter-name> FilterServ </filter-name>
 	 	 <url-pattern>/ FilterServ </url-pattern>


Details of the program

  • In the above web.xml file the filter named is specified as FilterServ which is implemented in the filter class.
  • The <init-param> tag is used to initialize the parameter. It contains two tags namely <param-name> and <param-value> which is used to initialize the attributes of the filter.
  • Filter mapping is used to map the servlets and resources in the web application. It contains two tags namely <filter-name> and <url-pattern>. The <filter-name> tag is used to map the filter to a servlet or URL and the <url-pattern> tag associates the filter with a set of url’s.

The output of these program can be seen in console as:

Javabeat : Hello World!!!!!!!!!

Previous Tutorial : Session Tracking Using Servlet || Next Tutorial : How To Get Client IP Address In Servlet

Leave a Reply

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

Pin It on Pinterest

Share This

Share this post with your friends!