Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Servlet Filter - Modify response headers based on status

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?

like image 854
Mark Avatar asked Sep 14 '25 13:09

Mark


1 Answers

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.

like image 100
Mark Avatar answered Sep 16 '25 03:09

Mark