BalusC's answer is good, but can be a bit overwhelming if you are just starting out.
Simply put: SerlvetResponse and its HttpServletResponse extension are interfaces that tell you what methods to call to do what you need. In the ordinary course of working with filters, servlets, etc., you often use HttpServletResponse to tell your application how to respond to requests.
HttpServletResponseWrapper is one specific implementation of HttpServletResponse, which gives you a convenient way to wrap an existing response with some logic without having to write a completely new interface implementation. He has many methods, so itโs really nice. As a trivial example, suppose you wanted to block calls to response.flushBuffer () . This code using HttpServletResponseWrapper will do the following:
class DisallowFlushResponseWrapper extends HttpServletResponseWrapper { public DisallowFlushResponseWrapper(HttpServletResponse response) { super(response); } @Override public void flushBuffer() { throw new UnsupportedOperationException("Don't call this!"); } }
A typical way to use such a shell would be to create such a filter:
class DisallowFlushFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) { if (response instanceof HttpServletResponse) { HttpServletResponse newResponse = new DisallowFlushResponseWrapper((HttpServletResponse) response); chain.doFilter(request, newResponse); } ... } ... }
Note that we complete the response included in the filter with an instance of our own shell. Then we pass the wrapper to the next element in the filter chain. Thus, everything that comes after this filter will get an exception if it calls flushBuffer (), because it will call it on our wrapper. The wrapper, due to the default behavior, will delegate any other call to the wrapped answer that is real, so everything except calls to this method will work fine.
Ryan Stewart Aug 12 '11 at 23:15 2011-08-12 23:15
source share