Nearby lessons
31 of 34Servlet - Examples: Filters & Wrappers
- 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.
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.
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)
FilterConfig(I)
returns the logical name of the filter which is configured in web.xml by using <filter-name> tag.
FilterConfig(I)
DemoFilter.java
;
DemoFilter.java
TargetServlet.java
web.xml:
TargetServlet.java
| Analysis: | Request | Request |
|---|---|---|
| Browser | Target |
Servlet
| Response | Response |
|---|
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
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:
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:
Configuring Filter in web.xml
Filter-Mapping for Total web application:
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
| REQUEST | Servlet |
|---|
Intermediate ERROR
Servlet
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
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...
Configuring Filter in web.xml
In this case Filter won't be executed for RD's include call and error page calls.
Case-2:
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.
Demo Program for <dispatcher> tag
TargetServlet.java
TargetServlet1.java
FirstServlet.java
DemoFilter.java
;
DemoFilter.java
Demo Program for FilterChain
FirstServlet.java
DemoFilter.java
LogFilter.java
RequestURL()+" at "+ new Date());
LogFilter.java
Note:
In filter3 demo program, the log file is available in the following location:
Tomcat/logs/localhost.2017-02-26.txt
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 Container | 3) 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
Demo Program for Request Wrapper
CustomizedRequest.java
BadWordFilter.java
TargetServlet.java
web.xml:
TargetServlet.java
Flow of Program-Execution:
Enter Any Word: 1 23
Submit
| Login.html | Target 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
{
....
}
- Every example is complete and compiles as-is
- Examples are grouped by topic
- Typing programs is the fastest way to learn servlets