如何根据Content-type添加响应头;在提交响应之前获取内容类型 [英] How to add response headers based on Content-type; getting Content-type before the response is committed
本文介绍了如何根据Content-type添加响应头;在提交响应之前获取内容类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想为所有 image/*
和 text/css
设置 Expires
标头.我在 Filter
中执行此操作.然而:
I want to set the Expires
header for all image/*
and text/css
. I'm doing this in a Filter
. However:
- 在调用
chain.doFilter(..)
之前,Content-type 还没有实现" - 在调用
chain.doFilter(..)
之后,Content-type 被设置,但 content-length 也是如此,它禁止添加新的 headers(至少在 Tomcat 实现中)
- before calling
chain.doFilter(..)
the Content-type is not yet "realized" - after calling
chain.doFilter(..)
the Content-type is set, but so is content-length, which forbids adding new headers (at least in Tomcat implementation)
我可以使用请求资源的扩展名,但是由于一些 css 文件是由 Richfaces 通过从 jar 文件中获取它们生成的,因此文件名不是 x.css
,但是是/xx/yy/zz.xcss/DATB/...
.
I can use the extensions of the requested resource, but since some of the css files are generated by richfaces by taking them from inside jar-files, the name of the file isn't x.css
, but is /xx/yy/zz.xcss/DATB/...
.
那么,有没有办法在提交响应之前获取 Content-type.
So, is there a way to get the Content-type before the response is committed.
推荐答案
是的,实现 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));
这篇关于如何根据Content-type添加响应头;在提交响应之前获取内容类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文