Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 678
Bozho Avatar asked Apr 01 '10 20:04

Bozho


People also ask

How do you set a response header?

Select the web site where you want to add the custom HTTP response header. In the web site pane, double-click HTTP Response Headers in the IIS section. In the actions pane, select Add. In the Name box, type the custom HTTP header name.

Can we set response header?

You can set response headers, you can add response headers And you can wonder what the difference is. But think about it for a second, then do this exercise. Draw a line from the HttpResponse method to the method's behavior.


1 Answers

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));
like image 65
BalusC Avatar answered Oct 11 '22 06:10

BalusC