How do delete a HTTP response header?

后端 未结 4 950
庸人自扰
庸人自扰 2020-11-29 01:52

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

4条回答
  •  死守一世寂寞
    2020-11-29 02:44

    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.

提交回复
热议问题