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

Solution 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));

Solution 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.