28

chain.doFilter(req,res);
We used this in a servlet program. I want to know what is the use of the method doFilter() in a servlet? Also what is the use of filter and chain concept in Java servlets?

informatik01
  • 16,038
  • 10
  • 74
  • 104
Vinoth Kumar
  • 3,243
  • 7
  • 24
  • 13

3 Answers3

39

Servlet filters are implementation of the chain of responsibility pattern

The point is that each filter stays "in front" and "behind" each servlet it is mapped to. So if you have 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 also have the option not to call chain.doFilter(..) in which case the servlet will never be called. This is useful for security purposes - for example you can check whether there's a user logged-in.

Bozho
  • 588,226
  • 146
  • 1,060
  • 1,140
  • 5
    While writing my answer, I got a message that somebody already provided one. But I still kept working on my take, thinking that the provider must have missed mentioning the pattern and the link to it. But after submitting mine, I found out that I was completely wrong. +1 – Adeel Ansari Nov 08 '10 at 10:24
  • 1
    @Adeel Ansari anyway, you provided a link that I didn't - the one to "essentials of filters", so +1 there as well. – Bozho Nov 08 '10 at 10:30
30

What are Filters ?

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

OR

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

enter image description here

Why they are used ?

-Filters can perform security checks.

-Compress the response stream.

-Create a different response.

What does doFilter() do ?

The doFilter() is called every time the container determines that the filter should be applied to a page.

It takes three arguments

->ServletRequest

->ServlerResponse

->FilterChain

All the functionality that your filter supposed to do is implemented inside 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 filter elements you defined in the DD.

Prateek Joshi
  • 3,929
  • 3
  • 41
  • 51
13

Filters are there to complement Servlets. For the usage, you should read this, The Essentials of Filters. Filters are implemented using Chain of Responsibility GoF pattern.

bluish
  • 26,356
  • 27
  • 122
  • 180
Adeel Ansari
  • 39,541
  • 12
  • 93
  • 133