Nearby lessons

15 of 34

Servlet - Filters

📌 What You Will Learn
  • Understand FilterConfig
  • Understand FilterChain
  • Understand Demo Program for <dispatcher> tag
  • See complete working code examples

Filters is an essential part of the Java Servlet technology. This lesson explains FilterConfig, FilterChain and DemoFilter.java with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid.

FilterConfig(I)

For every Filter web container creates a FilterConfig object and handover to the filter as argument

to init() method.

By using FilterConfig object,Filter can get its configuration information.

FilterConfig defines the following methods...

FilterConfig(I)

returns the logical name of the filter which is configured in web.xml by using <filter-name> tag.

Example02
JCode Cell
1 
2public String getFilterName()
3

FilterConfig(I)

Example03
JCode Cell
1 
2public String getInitParameter(String name)
3public Enumeration getInitParameterNames()
4public ServletContext getServletContext()
5

FilterChain

We can use FilterChain object to forward request to the next level. (It may be another Filter or

Servlet)

FilterChain interface contains the following method.

public void doFilter(SR req,SR resp) throws SE,IOE

DemoFilter.java

;

Example05
JCode Cell
1 
2import javax.servlet.*;
3import java.io.*;
4public class DemoFilter implements Filter
5{
6public void init(FilterConfig conf) throws ServletException
7{
8}
9public void doFilter(ServletRequest req,ServletResponse resp,FilterChain fc) throws ServletException,IOException
10{
11PrintWriter out = resp.getWriter();
12out.println("<h1>This line added by Demo Filter before processing the request</h1>")
13
Output

<h1>This line added by Demo Filter before processing the request</h1>
      

DemoFilter.java

Example06
JCode Cell
1 
2fc.doFilter(req,resp);
3out.println("<h1>This line added by Demo Filter after processing the request</h1>");
4}
5public void destroy()
6{
7}
8}
9
Output

<h1>This line added by Demo Filter after processing the request</h1>
      

TargetServlet.java

web.xml:

Example07
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5public class TargetServlet extends HttpServlet
6{
7public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8{
9PrintWriter out = resp.getWriter();
10out.println("<h1>This is the Target Servlet</h1>");
11}
12}
13
Output

<h1>This is the Target Servlet</h1>
      

TargetServlet.java

Analysis:RequestRequest
BrowserTarget

Servlet

ResponseResponse

Demo Filter

  • Whenever we are sending the request to TargetServlet,web container checks is there any filter

configured for this servlet or not.

If any Filter configured,web container forwards the request to the Filter instead of Servlet.

After completing Filtering logic,Filter forwards the request to the TargetServlet.

After processing that request by TargetServlet , the response will be forwarded to the Filter

instead of browser.

After executing Filtering logic , Filter forwards total response to the browser.

http://localhost:7777/filter1/test

Example08
JCode Cell
1 
2<web-app>
3 
4<servlet>
5<servlet-name>TargetServlet</servlet-name>
6<servlet-class>TargetServlet</servlet-class>
7</servlet>
8 
9<servlet-mapping>
10<servlet-name>TargetServlet</servlet-name>
11<url-pattern>/test1</url-pattern>
12</servlet-mapping>
13 
14<filter>
15<filter-name>DemoFilter</filter-name>
16<filter-class>DemoFilter</filter-class>
17</filter>
18 
19<filter-mapping>
20<filter-name>DemoFilter</filter-name>
21<url-pattern>/test1</url-pattern>
22</filter-mapping>
23 
24</web-app>
25

Configuring Filter in web.xml

We can configure Filter by using <filter> tag.

Configuring Filter in web.xml

We can map Filter either for a Particular url-pattern or to a particular Servlet or to the total web

application.

Filter-Mapping to a Particular url-pattern:

Example10
JCode Cell
1 
2<web-app>
3<filter>
4<filter-name>
5<filter-class>
6<init-param>
7<param-name>
8<param-value>
9</init-param>
10</filter>
11..
12</web-app>
13

Configuring Filter in web.xml

If the request is coming with the specified url-pattern then automatically this filter will be

executed.

Filter-mapping to a Particular Servlet:

Example11
JCode Cell
1 
2<filter-mapping>
3<filter-name>DemoFilter</filter-name>
4<url-pattern>/test1</url-pattern>
5</filter-mapping>
6

Configuring Filter in web.xml

Filter-Mapping for Total web application:

Example12
JCode Cell
1 
2<filter-mapping>
3<filter-name>DemoFilter</filter-name>
4<servlet-name>TargetServlet</servlet-name>
5</filter-mapping>
6

Configuring Filter in web.xml

For any request to the web application whether it is for servlet or jsp, this Filter will be executed.

Note:

Mapping Filter to the total web application is possible from Servlet 2.5V onwards.

<dispatcher> tag:

A servlet can get the request in one of the following 4 ways

FORWARD

Intermediate INCLUDE

Servlet

Target

REQUESTServlet

Intermediate ERROR

Servlet

Example13
JCode Cell
1 
2<filter-mapping>
3<filter-name>DemoFilter</filter-name>
4<url-pattern>*</url-pattern>
5</filter-mapping>
6

Configuring Filter in web.xml

By default Filter concept is applicable only for direct end user REQUEST and not applicable for RD's

forward,include calls and error page calls.

If we want to extend for remaining cases also then we should go for <dispatcher> tag.

<dispatcher> tag introduced in Servlet 2.4V.

The allowed values for <dispatcher> tag are:

  • REQUEST:

Filter will be executed for direct end user request.

This is default value

  • FORWARD:

Filter will be executed for RD's forward() call.

  • INCLUDE:

Filter will be executed for RD's include() call

  • ERROR:

Filter will be executed for Error page call

Example14
JCode Cell
1 
2A Request Directly from Browser(REQUEST)
3By RequestDispatcher's forward() call(FORWARD)
4By RequestDispatcher's include() call(INCLUDE)
5By Error Page Call(ERROR)
6

Configuring Filter in web.xml

If we want to execute Filter for direct end user's request and RD's forward() call, then we have to

configured filter as follows...

Example15
JCode Cell
1 
2<error-page>
3<exception-type>java.lang.AE</exception-type>
4<location>/test</location>
5</error-page>case-1:
6

Configuring Filter in web.xml

In this case Filter won't be executed for RD's include call and error page calls.

Case-2:

Example16
JCode Cell
1 
2<filter-mapping>
3<filter-name>DemoFilter</filter-name>
4<url-pattern>/test1</url-pattern>
5<dispatcher>REQUEST</dispatcher>
6<dispatcher>FORWARD</dispatcher>
7</filter-mapping>
8

Configuring Filter in web.xml

In this case Filter will be executed only for RD's include call and in the remaining 3 cases filter wont

be executed.

Example17
JCode Cell
1 
2<filter-mapping>
3....
4<dispatcher>INCLUDE</dispatcher>
5</filter-mapping>
6

Demo Program for <dispatcher> tag

web.xml:

Demo Program for <dispatcher> tag

Example19
JCode Cell
1 
2<web-app>
3 
4<servlet>
5<servlet-name>FirstServlet</servlet-name>
6<servlet-class>FirstServlet</servlet-class>
7</servlet>
8 
9<servlet>
10<servlet-name>TargetServlet</servlet-name>
11<servlet-class>TargetServlet</servlet-class>
12</servlet>
13<servlet>
14<servlet-name>TargetServlet1</servlet-name>
15<servlet-class>TargetServlet1</servlet-class>
16</servlet>
17 
18<servlet-mapping>
19<servlet-name>FirstServlet</servlet-name>
20<url-pattern>/test1</url-pattern>
21</servlet-mapping>
22 
23<servlet-mapping>
24<servlet-name>TargetServlet</servlet-name>
25<url-pattern>/test2</url-pattern>
26</servlet-mapping>
27<servlet-mapping>
28<servlet-name>TargetServlet1</servlet-name>
29<url-pattern>/test3</url-pattern>
30</servlet-mapping>
31<filter>
32<filter-name>DemoFilter</filter-name>
33<filter-class>DemoFilter</filter-class>
34</filter>
35 
36<filter-mapping>
37<filter-name>DemoFilter</filter-name>
38<servlet-name>TargetServlet</servlet-name>
39<dispatcher>REQUEST</dispatcher>
40<dispatcher>FORWARD</dispatcher>
41<dispatcher>INCLUDE</dispatcher>
42<dispatcher>ERROR</dispatcher>
43</filter-mapping>
44 
45<error-page>
46<exception-type>java.lang.ArithmeticException</exception-type>
47<location>/test2</location>
48</error-page>
49</web-app>
50

TargetServlet.java

Example20
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5public class TargetServlet extends HttpServlet
6{
7public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8{
9PrintWriter out = resp.getWriter();
10out.println("<h1>This is the Target Servlet</h1>");
11}
12}
13
Output

<h1>This is the Target Servlet</h1>
      

TargetServlet1.java

Example21
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5public class TargetServlet1 extends HttpServlet
6{
7public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8{
9PrintWriter out = resp.getWriter();
10out.println(10/0);
11}
12}
13

FirstServlet.java

Example22
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5public class FirstServlet extends HttpServlet
6{
7public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8{
9RequestDispatcher rd = req.getRequestDispatcher("/test2");
10rd.include(req,resp);
11//rd.forward(req,resp);
12}
13}
14

DemoFilter.java

;

Example23
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5public class DemoFilter implements Filter
6{
7public void init(FilterConfig conf) throws ServletException
8{
9}
10public void doFilter(ServletRequest req,ServletResponse resp,FilterChain fc) throws ServletException,IOException
11{
12PrintWriter out = resp.getWriter();
13out.println("<h1>This line added by Demo Filter before processing the request</h1>")
14
Output

<h1>This line added by Demo Filter before processing the request</h1>
      

Filter Chain

We can configure more than one Filter for a Target Resource and all these filters will be executed

one by one and forms Filter Chain.

Target

LogAuthentication RequestResponse

Filter

Filter DataEncryption

Convert Filter

Filter Chain

Demo Program for FilterChain

First

Servlet

Browser Log Demo

Filter Filter

web.xml:

Demo Program for FilterChain

Example26
JCode Cell
1 
2<web-app>
3 
4<filter>
5<filter-name>LogFilter</filter-name>
6<filter-class>LogFilter</filter-class>
7</filter>
8 
9<filter>
10<filter-name>DemoFilter</filter-name>
11<filter-class>DemoFilter</filter-class>
12</filter>
13 
14<filter-mapping>
15<filter-name>LogFilter</filter-name>
16<url-pattern>/test1</url-pattern>
17</filter-mapping>
18 
19<filter-mapping>
20<filter-name>DemoFilter</filter-name>
21<url-pattern>/test1</url-pattern>
22</filter-mapping>
23 
24<servlet>
25<servlet-name>FirstServlet</servlet-name>
26<servlet-class>FirstServlet</servlet-class>
27</servlet>
28 
29<servlet-mapping>
30<servlet-name>FirstServlet</servlet-name>
31<url-pattern>/test1</url-pattern>
32</servlet-mapping>
33 
34</web-app>
35

FirstServlet.java

Example27
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.io.*;
5public class FirstServlet extends HttpServlet
6{
7public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8{
9PrintWriter out = resp.getWriter();
10out.println("<h1>This is Target Servlet</h1>");
11}
12}
13
Output

<h1>This is Target Servlet</h1>
      

DemoFilter.java

Example28
JCode Cell
1 
2import javax.servlet.*;
3import java.io.*;
4public class DemoFilter implements Filter
5{
6public void init(FilterConfig conf) throws ServletException
7{
8}
9public void doFilter(ServletRequest req,ServletResponse resp,FilterChain fc) throws ServletException,IOException
10{
11PrintWriter out = resp.getWriter();
12out.println("<h1> This Line added by DemoFilter before processing of the request</h1>");
13fc.doFilter(req,resp);
14out.println("<h1> This Line added by DemoFilter After processing of the request</h1>");
15}
16public void destroy()
17{
18}
19}
20
Output

<h1> This Line added by DemoFilter before processing of the request</h1>
<h1> This Line added by DemoFilter After processing of the request</h1>
      

LogFilter.java

RequestURL()+" at "+ new Date());

Example29
JCode Cell
1 
2import javax.servlet.*;
3import javax.servlet.http.*;
4import java.util.*;
5import java.io.*;
6public class LogFilter implements Filter
7{
8private FilterConfig config;
9public void init(FilterConfig config) throws ServletException
10{
11this.config= config;
12}
13public void doFilter(ServletRequest req,ServletResponse resp,FilterChain fc) throws ServletException,IOException
14{
15PrintWriter out = resp.getWriter();
16out.println("<h1> This Line added by log Filter before processing of the request</h1>");
17ServletContext context = config.getServletContext();
18HttpServletRequest req1 = (HttpServletRequest)req;
19context.log("A request is coming from "+req1.getRemoteHost()+" for URL :"+req1.get
20
Output

<h1> This Line added by log Filter before processing of the request</h1>
      

LogFilter.java

Note:

In filter3 demo program, the log file is available in the following location:

Tomcat/logs/localhost.2017-02-26.txt

Example30
JCode Cell
1 
2fc.doFilter(req,resp);
3out.println("<h1> This Line added by Log Filter After processing of the request</h1>");
4}
5public void destroy()
6{
7config= null;
8}
9}
10
Output

<h1> This Line added by Log Filter After processing of the request</h1>
      

Web Container's Rule for ordering of Filters in FilterChain

  • Identify all filters which are configured according to url-pattern & execute all these filters from

top to bottom.

  • Identify all filters which are configured according to <servlet-name> & execute all these filters

from top to bottom.

Note:

<filter> and <filter-mapping> tags are direct child tags of <web-app> and hence we can take these

tags anywhere within <web-app>.

Difference b/w Filter's doFilter() Method and FilterChain's doFilter() Method:

Filter's doFilter() MethodFilterChain's doFilter() Method
1) public void doFilter (SR req, SR resp, FC fc)1) public void doFilter (SR req, SR resp)
throws SE, IOEthrows SE, IOE

Web Container's Rule for ordering of Filters in FilterChain

Method only.be another Filter OR Servlet)
3) It is call back method because Web Container3) It is not call back method because we have to
calls this Method automatically.call explicitly this Method.

Wrappers

Sometimes it is required to alter request and response information in the filters. We can

implement this by using wrapper classes.

i.e we can use wrappers inside filters to alter request and response information.

Eg1:

Within the filter,we have to convert end user's resume from word format to pdf format.

Eg 2:

Within the filter,we have to compress the response and that compressed response we can send to

the browser,so that we can reduce download time.

There are 2 types of wrappers

  • Request wrappers
  • Response wrappers
  • Request wrappers:

To alter request information

There are two request wrapper classes...

ServletRequest (I)

ServletRequestWrapper (C) HttpServletRequest (I)

HttpServletRequestWrapper (C)

  • ServletRequestWrapper
  • HttpServletRequestWrapper
  • Response wrappers:

To alter response information

ServletResponse (I)

ServletResponseWrapper (C)HttpServletResponse (I)

HttpServletResponseWrapper (C)

There are two response wrapper classes

  • ServletResponseWrapper
  • HttpServletResponseWrapper
Example32
JCode Cell
1 
2Total Filtering Logic, we have to define in this 2) To forward Request to the next Level (It may
3
📝 Key Takeaways
  • Key ideas of Servlet - Filters explained simply
  • Ready-to-use code examples
  • Exam-style questions at the end

🧠 Test Your Knowledge

4 Questions
Progress: 0 / 4