I'm trying to write a servlet filter that will add headers to the response depending on the status of the request. I know I have to wrap the response with a HttpServletResponseWrapper before passing to the chain.doFilter
but the headers never get sent, so I'm obviously missing something very obvious.
Code looks something like:
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
{
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
HttpServletResponseWrapper responseWrapper = new HttpServletResponseWrapper(httpServletResponse);
chain.doFilter(request, responseWrapper);
if(responseWrapper.getStatus() < 400)
{
responseWrapper.addHeader("X-Custom-Foobar", "abc");
}
}
Is there something I have to capture in the wrapper to prevent the response from going out to the client until the check is complete?
So the frustrating part about this spec is that you have to completely intercept the ServletOutputStream
and buffer it. I ended up following the example here :: https://stackoverflow.com/a/11027170/76343
The base class HttpServletResponseWrapper
is a complete passthrough and as soon as the output stream is closed, all further modifications to the response are mute.
Unfortunately there doesn't seem to be a more elegant way to accomplish this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With