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?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…