Reputation: 83
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
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
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.
Upvotes: 6