How to add response headers based on Content-type; getting Content-type before the response is committed

前端 未结 2 1271
一生所求
一生所求 2020-12-01 15:07

I want to set the Expires header for all image/* and text/css. I\'m doing this in a Filter. However:

  • before
相关标签:
2条回答
  • 2020-12-01 15:55

    You should subclass HttpServletResponseWrapper and override addHeader and setHeader to add the newly desired header when "Content-Type" is passed in as the header name. Make sure to not forget to call super in those overridden methods too. Wrap the Response sent in the doFilter method argument with this new Wrapper and pass the Wrapper to the call to doFilter.

    0 讨论(0)
  • 2020-12-01 16:03

    Yes, implement HttpServletResponseWrapper and override setContentType().

    class AddExpiresHeader extends HttpServletResponseWrapper {
        private static final long ONE_WEEK_IN_MILLIS = 604800000L;
    
        public AddExpiresHeader(HttpServletResponse response) {
            super(response);
        }
    
        public void setContentType(String type) {
            if (type.startsWith("text") || type.startsWith("image")) {
                super.setDateHeader("Expires", System.currentTimeMillis() + ONE_WEEK_IN_MILLIS);
            }
            super.setContentType(type);
        }
    }
    

    and use it as follows:

    chain.doFilter(request, new AddExpiresHeader((HttpServletResponse) response));
    
    0 讨论(0)
提交回复
热议问题