问题
I want to set the Expires header for all image/* and text/css. I'm doing this in a Filter. However:
- 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)
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/....
So, is there a way to get the Content-type before the response is committed.
回答1:
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));
回答2:
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.
来源:https://stackoverflow.com/questions/2563344/how-to-add-response-headers-based-on-content-type-getting-content-type-before-t