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
Loading editor…

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
Loading editor…

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
Loading editor…

FilterConfig(I)

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

Example04
Loading editor…

FilterConfig(I)

Example05
Loading editor…

DemoFilter.java

;

Example06
Loading editor…

DemoFilter.java

Example07
Loading editor…

TargetServlet.java

web.xml:

Example08
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

Configuring Filter in web.xml

Filter-Mapping for Total web application:

Example12
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

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
Loading editor…

Demo Program for <dispatcher> tag

Example18
Loading editor…

TargetServlet.java

Example19
Loading editor…

TargetServlet1.java

Example20
Loading editor…

FirstServlet.java

Example21
Loading editor…

DemoFilter.java

;

Example22
Loading editor…

DemoFilter.java

Example23
Loading editor…

Demo Program for FilterChain

Example24
Loading editor…

FirstServlet.java

Example25
Loading editor…

DemoFilter.java

Example26
Loading editor…

LogFilter.java

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

Example27
Loading editor…

LogFilter.java

Note:

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

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

Example28
Loading editor…

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
Loading editor…

Demo Program for Request Wrapper

Example30
Loading editor…

CustomizedRequest.java

Example31
Loading editor…

BadWordFilter.java

Example32
Loading editor…

TargetServlet.java

web.xml:

Example33
Loading editor…

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
Loading editor…
📝 Key Takeaways
  • Every example is complete and compiles as-is
  • Examples are grouped by topic
  • Typing programs is the fastest way to learn servlets

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.