5

i have searched and seen couple of post for this problem, but did not find the answer how it is possible.

what i want to do is add the header after the filter chain,

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletResponse httpResp = (HttpServletResponse) response;

try {
HttpServletResponseWrapper bufferedResponse = new     HttpServletResponseWrapper (httpResp); 

chain.doFilter(request, bufferedResponse);

} finally {   
// header added at this line is not actually being added.        
bufferedResponse.setHeader("ADD A HEADER: ", "HEADER");
}                                     
}

multiple posts are talking it is possible by using HttpServletResponseWrapper but it is not working for me, can anyone help me on this.

mc110
  • 2,825
  • 5
  • 20
  • 21
Kishore
  • 73
  • 1
  • 6
  • You can refer to this answer, it worked for me - https://stackoverflow.com/questions/32829124/adding-header-in-response-in-filter/32830377#32830377 – Harshad Vyawahare Oct 16 '18 at 14:58

2 Answers2

5

You can't add a header (well, you can but it won't have any effect) after the response has been committed since at that point the HTTP headers have all been written to the client.

You have three options.

  1. Write your header before you call doFilter()
  2. Make sure (large buffer, small response, no calls to flush() etc) that the response is not committed before you try and add you header.
  3. Wrap the response before the do filter method and buffer then entire response body in the wrapper, add your header afterwards and then write out the response body from your buffer.
Mark Thomas
  • 16,339
  • 1
  • 39
  • 60
  • Yes, I am trying to implement option 2 or 3 you have suggested. but not yet successful. do you have any sample code for this. [link]http://www.wetfeetblog.com/servlet-filer-to-log-request-and-response-details-and-payload/431[link] using following approach to buffer the response. i am using response header but struggling on how to add the header – Kishore Jun 10 '14 at 21:16
  • Approach 3 works only when there is no response body. If there is a response body, it does not work – manuka_m Jan 30 '20 at 11:59
0

you can add headers after do filter, but that does not guarantee that it will always work. One case in which it will not works is, When any servlet/filter has called response.sendRedirect.

`Filter A - pre work 
           doFilter ------> Servlet A - do some work
                                       invoke response.sendRedirect
           post work - add/Set Headers (These will get ignored).`

Note: There can be other scenarios also.