如何删除 HTTP 响应标头? [英] How do delete a HTTP response header?

查看:201
本文介绍了如何删除 HTTP 响应标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一种情况,必须删除其中一个响应标头 Content-Disposition.所以我想写一个servlet过滤器来做到这一点.但我意识到 HttpServletResponse 只有一个 setHeader() 方法,但没有删除它的方法.我该怎么做?

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?

推荐答案

之后您无法通过标准 Servlet API 删除标头.最好的办法是防止设置标题.您可以通过创建一个 Filter 来替换 ServletResponsecode> 带有自定义 HttpServletResponseWrapper 跳过 setHeader() 的工作,只要标头名称是 Content-Disposition.

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.

基本上:

@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);
            }
        }
    });
}

只需将该过滤器映射到感兴趣的 URL 模式即可使其运行.

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

这篇关于如何删除 HTTP 响应标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆