Servlet Filter

Filter is a kind of interceptor which intercept the request and perform some pre and post processing.

It gets call as soon as request reaches out to server and just before returning the response.

Logging, security, compression, etc are common examples of Filter.

Filter interface is having three mail methods:

void init(FilterConfig paramFilterConfig):

Similar to Servlet, Filters also get initialized as soon as server gets start. At the time of initialization it calls init() method. Like ServletConfig we have FilterConfig to access parameters

doFilter(ServletRequest req, ServletResponse res, FilterChain Chain)

Below method will get call on every request or response.

chain.doFilter(request,response) method call is very important to call subsequent Filter or Servlet. Application will get stuck at this method if chain statement is not written.

void destroy()

This will get call as soon as container offloads Filter.

Filter can be define in two ways:

  1. Declare @WebFilter annotation with relative path and implements Filter interface.

2. Implement Filter interface and make an entry in web.xml file as shown below.

Example

  1. Open eclipse and Click on File as highlighted below.

File → New → Other

2. Select “Dynamic Web Project” and click on “next” button will help us to create project related to servlet.

3. Provide the project name and click on finish will help us to create project. On current example we have given as “ServletDemo”.

4. Don’t make any change and click on Next.

5. Check the checkbox to generate web.xml and click on Finish button will create project.

6. Right click on below highlighted folder and create a package having name com.javadoubts.servlet

7. Inside package com.javadoubts.servlet, create LoginServlet.java class and type below content.

8. Inside same package com.javadoubts.servlet parallel to LoginServlet.java class, create one more LoginFilter.java class implementing Filter interface.

9. Place below content in web.xml file

10. Now, its time to run application.

Right click on the project and select Run As and then Run on Server to run application on Apache Tomcat.

After hitting below URL checking logs will print below output.

http://localhost:8082/ServletDemo/login

OUTPUT
doFilter() method called
doGet() method called

Imran Khan, Adobe Community Advisor, AEM certified developer and Java Geek, is an experienced AEM developer with over 11 years of expertise in designing and implementing robust web applications. He leverages Adobe Experience Manager, Analytics, and Target to create dynamic digital experiences. Imran possesses extensive expertise in J2EE, Sightly, Struts 2.0, Spring, Hibernate, JPA, React, HTML, jQuery, and JavaScript.

0