0

I came across a portion of code that zips the servlet output before returning it to the user, it uses a custom ServletResponseWrapper -it's so famous if u know what I am talking about-, my questions are :

1 - now the function of intercepting the response is totally the responsibility of the response wrapper -through overriding the output stream it returns- and the filter has no effect in such behaviour ? Am I correct ?

2- what happens if any of the servlets that the filters intercept its requests closed the output stream, will the code after chain.doFilter() be able to use this stream again ? and will the filter work ?

3 why does the wrapped response solve the problem of the "output returns directly to the container before being intercepted by the filter" ... I mean why the control over the response is then returned to the filter ?

osama yaccoub
  • 1,884
  • 2
  • 17
  • 47

1 Answers1

1

I've recently used the example code from this book for my project: Professional Java for Web Applications. There is a good example for a compression filter in chapter 9.

I'm not involved with the company behind the book.

These are the answers to your question:

  1. Yes, you're correct. The filter wraps the original HttpServletResponse with a wrapper, and from this moment on the wrapper is responsible for managing the output stream (but not for closing the stream).
  2. It's not a good idea at all to close the output stream in your own code, whether you use a wrapped HttpServletResponse or not.
  3. The control over the output stream isn't returned to the filter. The execution of your web app is continued in the line after chain.doFilter(), and you can write some data to the wrapped response, if it's necessary. But don't close the stream, neither in your filter, nor in your servlet(s).
JimHawkins
  • 4,843
  • 8
  • 35
  • 55
  • why not to close the stream? – osama yaccoub Feb 23 '16 at 11:12
  • because closing belongs to the responsibility of the container. Don't be afraid the container forgets to close the stream ;-) – JimHawkins Feb 23 '16 at 11:15
  • I mean, does it really affect filter behavior y any mean? I read n stackoverflow that It won't allow filter to work , but have no idea if this is true or not http://stackoverflow.com/questions/1159168/should-one-call-close-on-httpservletresponse-getoutputstream-getwriter – osama yaccoub Feb 23 '16 at 14:29
  • The answer of skaffman and its comments in the topic you've linked are perfect. I still say "don't close the output stream. Closing is the job of the container." – JimHawkins Feb 23 '16 at 14:46
  • let me know if you have trouble with the code examples in the book that I recommended. There are some minor issues. – JimHawkins Feb 23 '16 at 15:31