How do delete a HTTP response header?

后端 未结 4 952
庸人自扰
庸人自扰 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:45

    This does not work for me using Spring 4. I'm trying to strip out the Expires response header. For every page. Like so:

    public class CachingFilter implements Filter {
        private final Log logger = LogFactory.getLog(getClass());
    
        public CachingFilter() {}
        public void destroy() {}
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
            logger.debug("doFilter()");
            chain.doFilter(request, new HttpServletResponseWrapper((HttpServletResponse) response) {
                public void setHeader(String name, String value) {
                    logger.debug("setHeader(" + name + ","+value+")");
    
                    if (!name.equalsIgnoreCase("Expires")) {
                        super.setHeader(name, value);
                    }
                }
            });
        }
    
        public void init(FilterConfig fConfig) throws ServletException {}
    }
    

    And here is how I add the filter:

    public class AppConfig implements WebApplicationInitializer {
        private static final String DISPATCHER_SERVLET_NAME = "dispatcher";
        private static final String DISPATCHER_SERVLET_MAPPING = "/";
    
        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
            rootContext.register(AppContext.class);
    
            ServletRegistration.Dynamic dispatcher = servletContext.addServlet(DISPATCHER_SERVLET_NAME, new DispatcherServlet(rootContext));
            dispatcher.setLoadOnStartup(1);
            dispatcher.addMapping(DISPATCHER_SERVLET_MAPPING);
    
            EnumSet dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD);
    
            FilterRegistration.Dynamic noCache = servletContext.addFilter("noCacheFilter", new CachingFilter());
            noCache.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
    
            servletContext.addListener(new ContextLoaderListener(rootContext));
        }
    }
    

    setHeader() being called for Expires and Cache-Control, but I can't override the Expires filter value, or the Cache-Control value. I can add to the Cache-Control value. It turns into an array of values if I call setHeader on Cache-Control. But I need to delete the header.

提交回复
热议问题