Reputation: 1067
So I've been observing some answers about this topic and I understand that after the doFilter() call is completed it is now too late to modify a repsonse header, and to best handle this case I should use a response wrapper.
I want to know how to handle the case where I only want to set a header if the response that has bubbled back up to my filter has a specific status code. Should that logic be handled before doFilter? In the Request Wrapper class? I'm a bit confused.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest httpRequest;
HttpServletResponse servlettResponse = (HttpServletResponse)response;
CrossOriginResponseWrapper crossOriginResponseWrapper = new CrossOriginResponseWrapper(servlettResponse);
if (crossOriginResponseWrapper.getStatus() == 404) {
crossOriginResponseWrapper.addHeader("Access-Control-Allow-Origin", "*");
}
chain.doFilter(request, crossOriginResponseWrapper);
LOG.info(crossOriginResponseWrapper.getHeader("Access-Control-Allow-Origin"));
LOG.info(servlettResponse.getStatus());
}
UPDATE:
Is the only way to solve this overriding methods in the wrapper so that the response isn't written/flushed before it gets to my filter? Is there any simpler solution?
(Referencing this answer) Response is committing and doFilter chain is broken
Upvotes: 2
Views: 1801
Reputation: 590
Nop, that is the only way. Here you have a working example. https://github.com/sercasti/spring-httpserver-timings/blob/master/src/main/java/io/github/sercasti/tracing/filter/TracingFilter.java
I wrap the original Response with a Wrapper, thus avoiding other filters from calling the .write method, which instantly commits the response and locks you out from adding headers.
By using this wrapper, other filters write to my wrapper, and then when my filter gets the control back, I add my headers, and effectively write the original response.
Upvotes: 2