1) Lets first understand how Request
and Request Filter
work:
When, lets say client, makes a request to servlet, it goes through container. Container decides what servlet Request
needs to be forwarded to. Which means, container is in total control.
Container control makes implementing request filter easy because we can just let container know that the Request
should go to filter first and then to servlet. Because container is in total control. So implementing request filter is easy.
2) Now lets understand how Response
and Response Filter
work:
When container invokes Servlet service methods, it passes 2 objects to the methods, Request
and Response
.
This simply means that Servlet is in total control to send the response back to client. How ?
Because Response
object has the pointer to Output Stream Writer
object. Which means, once Servlet finishes processing the request, it will straight write the Response
back to the client using pointer to Output Writer Stream
object. So, Servlet won't wait for anyone (middle men like filter) and straight serve the client. By the time, it will be too late to intervene.
So, what's the solutions ?
Wrapper
is our solution.
How Wrapper works ?
So, before container passes the real Request
and Response
objects to Servlet, we will wrap our Response
object and then send the Real Request
and Wrapped Response
objects to the Servlet service methods.
So now, Servlet has pointer to our Wrapped Output Stream Writer
object and not the Real Response Output Stream Writer
object. So, when Servlet finishes the request, it will write the response to our Wrapped Stream
and then Our Wrapped Response Object
will write back to Real Response Writer Stream
.
Moral of the story: Use wrapper
when dealing with Response
. Request
doesn't need wrapper concept.