I am confused with one question in the Head First Book (Servlets and JSP) about Filters (chapter 13 page 728).
"A filter can act on only the request or response object, not both." This question is not true.
Technically the answer is correct, it will compile and "work", but I can not imagine any case where the request and the
response filter will be the same class or can you give me an example?
The main different between request and response filter are the method call chain.doFilter(request, response).
The request filter calls the chain at the beginning and the response at the end within the doFilter method. Furthermore
the response filter uses a wrapped response object, otherwise we will not get the response back. So it depends
on the kind of filter how I will implement the filter class.
There is no distinction between request and response filter actually. Where you call the filter.doChain method is totally up to you. You are not forced to call doChain at the beginning or end of doFilter method. You can implement a filter which does some processing before and after the call to doChain method...
so far I understand it does not matter where I put the method.
But can you give me an example where a filter can be used as request and response filter?
For me the question in the book suggest that I can write a filter and it can be used as request and
I made as an example a filter which outputs the http request and the response header (I know it is not
such a good example, because you have to differ between Request and Response Object, but I can only
imagine examples where I get always two different filter classes) . To output
both headers, I need two classes one for the request and one for the response header.
The request filter:
and the response filter:
Is it possible for this example (or a similar example) to have only one filter? If not I would answer for the question "A filter can act on only the request or response object, not both." yes and this would be wrong .
Thanks in advance
SCJP, Preparing for SCWCD
posted 10 years ago
ok I understand it. Code concerning the request has to be before chain.doFilter() and code for the response after the method.
The response must be wrapped in this case. The example would be the following: