Issue
What I want to do is, adding a new header to the response after the request is processed. I need to check the processed HttpStatus
code (401 unauthorized in my case) and add a new header. I know Spring has interceptors, but the response cannot be modified as stated in the document:
Note that the postHandle method of HandlerInterceptor is not always ideally suited for use with @ResponseBody and ResponseEntity methods. In such cases an HttpMessageConverter writes to and commits the response before postHandle is called which makes it impossible to change the response, for example to add a header. Instead an application can implement ResponseBodyAdvice and either declare it as an @ControllerAdvice bean or configure it directly on RequestMappingHandlerAdapter.
Well, I implemented the ResponseBodyAdvice
. Yes, it allows body modification, but I couldn't manage to modify the headers, event couldn't find the status code returned from the controller.
The other option, using servlet filters is not also successful. I need to add the header after filterChain.doFilter(servletRequest, servletResponse);
call. But it again doesn't modify the header value. Is there a way to accomplish this easy task?
Solution
It sounds like you're on the right track with a servlet filter, what you probably need to do is wrap the servlet response object with one that detects when a 401 status code has been set and adds your custom header at that time:
HttpServletResponse wrappedResponse = new HttpServletResponseWrapper(response) {
public void setStatus(int code) {
super.setStatus(code);
if(code == 401) handle401();
}
// three similar methods for the other setStatus and the two
// versions of sendError
private void handle401() {
this.addHeader(...);
}
};
filterChain.doFilter(request, wrappedResponse);
Answered By - Ian Roberts