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

我想为所有image/*text/css设置Expires标头。 我在Filter这样做。 然而:

  • 在调用chain.doFilter(..) ,Content-type尚未“实现”
  • 在调用chain.doFilter(..) ,设置了Content-type,但是content-length也是如此,它禁止添加新的头文件(至少在Tomcat实现中)

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

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

是的,实现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); } } 

并按如下方式使用:

 chain.doFilter(request, new AddExpiresHeader((HttpServletResponse) response)); 

您应该子类化HttpServletResponseWrapper并覆盖addHeader和setHeader,以便在将“Content-Type”作为标题名称传入时添加新需要的标题。 确保不要忘记在那些被覆盖的方法中调用super。 用这个新的Wrapper包装doFilter方法参数中发送的Response,并将Wrapper传递给对doFilter的调用。