[ACCEPTED]-What is the use of filter and chain in servlet?-chain
Servlet filters are implementation of the 8 chain of responsibility pattern
The point is that each filter stays "in 7 front" and "behind" each 6 servlet it is mapped to. So if you have 5 a filter around a servlet, you'll have:
void doFilter(..) {
// do stuff before servlet gets called
// invoke the servlet, or any other filters mapped to the target servlet
chain.doFilter(..);
// do stuff after the servlet finishes
}
You 4 also have the option not to call chain.doFilter(..)
in which 3 case the servlet will never be called. This 2 is useful for security purposes - for example 1 you can check whether there's a user logged-in.
What are Filters ?
Filters
are used to intercept and process requests
before they are sent to servlets(in 9 case of request) .
OR
Filters
are used to intercept and process a response
before they 8 are sent back to client by a servlet.
Why they are used ?
-Filters 7 can perform security checks.
-Compress the 6 response stream.
-Create a different response.
What does doFilter() do ?
The 5
doFilter()
is calledevery time
the container determines that the 4 filter should be applied to a page.
It takes 3 three arguments
->ServletRequest
->ServlerResponse
->FilterChain
All the functionality that your filter supposed to do
is implemented inside 2 doFilter()
method.
What is FilterChain ?
Your
filters do not know anything about the other filters and servlet
. FilterChain knows theorder of the invocation of filters
anddriven
by the 1filter elements
you defined in theDD
.
Filters are there to complement Servlets. For 2 the usage, you should read this, The Essentials of Filters. Filters 1 are implemented using Chain of Responsibility GoF pattern.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.