How do delete a HTTP response header?

response-headers, servlet-filters, servlets

Solution

You can't delete headers afterwards by the standard Servlet API. Your best bet is to just prevent the header from being set. You can do this by creating a `Filter` which replaces the `ServletResponse` with a custom `HttpServletResponseWrapper` implementation which skips the `setHeader()`'s job whenever the header name is `Content-Disposition`.

Basically:

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
        public void setHeader(String name, String value) {
            if (!name.equalsIgnoreCase("Content-Disposition")) {
                super.setHeader(name, value);
            }
        }
    });
}

Just map that filter on the URL-pattern of interest to get it to run.

Problem

I have a situation where one of the response headers `Content-Disposition` has to be removed. So I thought of writing a servlet filter to do this. But I realized that the `HttpServletResponse` has only a `setHeader()` method but no method to remove it. How can I do this?

Original source