Nearby lessons

31 of 34

Servlet - Examples: Filters & Wrappers

📌 What You Will Learn
  • See complete runnable servlet programs
  • Understand the output of each program
  • Copy and deploy programs in Tomcat

Filter programs including FilterChain, dispatcher tags, Request Wrappers, and BadWordFilter.

FAQs

Every Filter in Java has to implement Filter interface either directly or indirectly.

Filter interface defines the following 3 methods

1.init():

public void init(FilterConfig config)throws ServletException

This method will be executed only once to perform initialization activities.

Example01
JCode Cell
1 
2 Filter
3 FilterConfig
4 FilterChain
5 Filter(I):
6

FAQs

public void destroy()

This method will be executed only once to perform clean up activities just before taking the filter

from out of service.

Example02
JCode Cell
1 
2 destroy()
3

FAQs

public void doFilter(ServletRequest req,ServletResponse resp,FilterChain fc)throws SE,IOE

Total filtering logic we have to define in this method only.

This method will be executed for every request.

By using FilterChain object we can forward the request to the next level.(it may be Servlet or

another Filter)

Example03
JCode Cell
1 
2 doFilter()
3

FilterConfig(I)

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

Example04
JCode Cell
1 
2 public String getFilterName()
3

FilterConfig(I)

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

DemoFilter.java

;

Example06
JCode Cell
1 
2 import javax.servlet.*;
3 import java.io.*;
4 public class DemoFilter implements Filter
5 {
6 public void init(FilterConfig conf) throws ServletException
7 {
8 }
9 public void doFilter(ServletRequest req,ServletResponse resp,FilterChain fc) throws ServletException,IOException
10 {
11 PrintWriter out = resp.getWriter();
12 out.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

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

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

TargetServlet.java

web.xml:

Example08
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class TargetServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
8 {
9 PrintWriter out = resp.getWriter();
10 out.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

Example09
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 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 
2 A Request Directly from Browser(REQUEST)
3 By RequestDispatcher's forward() call(FORWARD)
4 By RequestDispatcher's include() call(INCLUDE)
5 By 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

Example18
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

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

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

TargetServlet1.java

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

FirstServlet.java

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

DemoFilter.java

;

Example22
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class DemoFilter implements Filter
6 {
7 public void init(FilterConfig conf) throws ServletException
8 {
9 }
10 public void doFilter(ServletRequest req,ServletResponse resp,FilterChain fc) throws ServletException,IOException
11 {
12 PrintWriter out = resp.getWriter();
13 out.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>
          

DemoFilter.java

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

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

Demo Program for FilterChain

Example24
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

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

    <h1>This is Target Servlet</h1>
          

DemoFilter.java

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

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

Example28
JCode Cell
1 
2 fc.doFilter(req,resp);
3 out.println("<h1> This Line added by Log Filter After processing of the request</h1>");
4 }
5 public void destroy()
6 {
7 config= 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

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
Example29
JCode Cell
1 
2 Total Filtering Logic, we have to define in this 2) To forward Request to the next Level (It may
3

Demo Program for Request Wrapper

Example30
JCode Cell
1 
2 <html>
3 <body bgcolor=green text=white><center><h1>Durga Software Solutions</h1></center>
4 <form action = "/wrapper/test1" >
5 <h1>Enter Any Word :<input type=text name=word></h1>
6 <input type=submit>
7 </form>
8 </body>
9 </html>
10

CustomizedRequest.java

Example31
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 public class CustomizedRequest extends HttpServletRequestWrapper
5 {
6 public CustomizedRequest(HttpServletRequest req)
7 {
8 super(req);// to make original request information available to the Parent class
9 }
10 public String getParameter(String word)
11 {
12 String word1 = super.getParameter(word);
13 if(word1.equals("JAVA") | word1.equals("SCJP") | word1.equals("SCWCD") | word1.equals("SAT"))
14 return "SLEEP";
15 else
16 return word1;
17 }
18 }
19

BadWordFilter.java

Example32
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class BadWordFilter implements Filter
6 {
7 public void init(FilterConfig conf) throws ServletException
8 {
9 }
10 public void doFilter(ServletRequest req,ServletResponse resp,FilterChain fc) throws ServletException,IOException
11 {
12 CustomizedRequest req1 = new CustomizedRequest((HttpServletRequest)req);
13 fc.doFilter(req1,resp);
14 }
15 public void destroy()
16 {
17 }
18 }
19

TargetServlet.java

web.xml:

Example33
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 public class TargetServlet extends HttpServlet
6 {
7
8 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
9 {
10 PrintWriter out = resp.getWriter();
11 String word = req.getParameter("word");
12 out.println("<h1>Hi your typed word is :"+word+"</h1>");
13 }
14 }
15

TargetServlet.java

Flow of Program-Execution:

Enter Any Word: 1 23

Submit

Login.htmlTarget Servlet

5 4

Backward Filter

End user entered the word and click the submit button.

Filter creates a CustomizedRequest object by using wrapper class.

Filter forwards that customized request object to the TargetServlet instead of original request.

Within the servlet if we are performing any operation o the request object,our own customized

behaviour will be reflected.

TargetServlet prepares the response and forwards to Filter.

Filter forwards that response inturn to the end user.

Note:

We are not required to configure anything related to wrapper in web.xml.

Conclusions:

  • Filter object will be created by web container automatically. For this web container always calls

public no-arg constructor.Hence every Filter class should compulsary contains public no-arg

constructor. It may be explicitly provided by programmer or default constructor generated by

compiler.

  • Filter object will be created automatically by the web container at the time of application

deployment or at the time of server startup. Hence <load-on-startup> is not required for the

filters.

  • Usage of filter is nothing but following

Intercepting Filter Design Pattern.Hence it is recommended to use Filters concept in our

application.

  • Usage of Wrappers is nothing but following Decorator design pattern. Hence it is

recommended to use Wrappers in our application.

@WebFilter Annotation in Servlet 3.0V:

It is the replacement for filter configurations in web.xml

import javax.servlet.annotation.*;

@WebFilter(filterName="DemoFilter", urlPatterns="/test")

public class DemoFilter implements Filter

{

....

}

Example34
JCode Cell
1 
2 <web-app>
3 <filter>
4 <filter-name>BadWordFilter</filter-name>
5 <filter-class>BadWordFilter</filter-class>
6 </filter>
7 <filter-mapping>
8 <filter-name>BadWordFilter</filter-name>
9 <servlet-name>TargetServlet</servlet-name>
10 </filter-mapping>
11
12 <servlet>
13 <servlet-name>TargetServlet</servlet-name>
14 <servlet-class>TargetServlet</servlet-class>
15 </servlet>
16
17 <servlet-mapping>
18 <servlet-name>TargetServlet</servlet-name>
19 <url-pattern>/test1</url-pattern>
20 </servlet-mapping>
21 </web-app>
22
📝 Key Takeaways
  • Every example is complete and compiles as-is
  • Examples are grouped by topic
  • Typing programs is the fastest way to learn servlets