[ACCEPTED]-What is the use of filter and chain in servlet?-chain

Accepted answer
Score: 37

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

    // 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.

Score: 30

What are Filters ?

Filters are used to intercept and process requests before they are sent to servlets(in 9 case of request) .


Filters are used to intercept and process a response before they 8 are sent back to client by a servlet.

enter image description here

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 called every time the container determines that the 4 filter should be applied to a page.

It takes 3 three arguments




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 the order of the invocation of filters and driven by the 1 filter elements you defined in the DD.

Score: 12

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