Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Puzzled by filter response object

 
Srikanth Raghavan
Ranch Hand
Posts: 389
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I was reading about filters and wrappers chapter from HFSJ and I am totally confused on on thing, lemme explain.

The Filter.doFilter() method is called by the container before calling the Servlet.service() method which is called when FilterChain.doFilter(request, response) is called. This is what I understood, please correct me if I am wrong.

But they say that the response object cannot be wrapped after the FilterChain.doFilter() call because the response would have already been sent to the container. But how?
 
Gaurav Gambhir
Ranch Hand
Posts: 256
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Container call the Filter's doFilter() method untill it encounters chain.doFilter() call, the container then call the servlet service() method where it executes to completion and is popped off the stack, the container then return the control again to doFilter() method where it completes and popped off
Now When the original response is passed by the filter to the servlet, the servlet would write to the servlet's output stream. The moment the service() method completes, the container would flush the stream. (The container would call out.flush()). This would send the response to the client. This flushing always happens after the servlet's service() method is done. The container will not wait for any filter. Now, when the control goes back to the filter, the filter WILL have a reference to the actual response (It was having it even before). But if it tries to call any method on the response, an IllegalStateException will be thrown as output stream has already been flushed by the container. This explains why you need to send a custom response.

Next is How to get control of output before it goes to client?

Servlet gets the output stream or writer from response object so Instead of passing the real response object to the servlet, filter is swapped in response object, so in order to get the compression filter working, make custom implementation of HttpServletResponse interface and pass that to servlet via chain.doFilter(), this custom implementation also includes custom output stream
as well since the goal is to capture the output after the servlet writes to it, but before it goes back to client.
 
Srikanth Raghavan
Ranch Hand
Posts: 389
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Gaurav, I understood well...
[ October 13, 2006: Message edited by: Srikanth Raghavan ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic