如何根据Content-type添加响应头; 在提交响应之前获取Content-type

Boz*_*zho 8 java tomcat servlets

我想Expires为所有image/*和设置标题text/css.我正在这样做Filter.然而:

  • 在调用chain.doFilter(..)Content-type 之前还没有"实现"
  • 调用chain.doFilter(..)Content-type 后,内容长度也是如此,禁止添加新标题(至少在Tomcat实现中)

我可以使用所请求资源的扩展,但由于某些css文件是由richfaces通过从jar文件中获取而生成的,因此文件的名称不是x.css,但是/xx/yy/zz.xcss/DATB/....

那么,有没有办法在提交响应之前获取Content-type.

Bal*_*usC 13

是的,实施HttpServletResponseWrapper和覆盖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);
    }
}
Run Code Online (Sandbox Code Playgroud)

并按如下方式使用:

chain.doFilter(request, new AddExpiresHeader((HttpServletResponse) response));
Run Code Online (Sandbox Code Playgroud)