Kishore
Kishore

Reputation: 83

Adding response header after doFilter

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.

Upvotes: 6

Views: 4358

Answers (2)

Abhinav Nimesh
Abhinav Nimesh

Reputation: 1

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.

Upvotes: 0

Mark Thomas
Mark Thomas

Reputation: 16660

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.

Upvotes: 6

Related Questions