Search code examples
jsphttp-headersjboss7.xbrowser-cachedeveloper-tools

Enable browser caching in JSP


How can I define my content of a page cacheable? I am using Google Chromes Audit function and it tells me:

The following resources are explicitly non-cacheable. Consider making them cacheable if possible.

I created a new Filter that is called with every request:

public class CachingFilter implements Filter {

    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

    HttpServletResponse httpResponse = (HttpServletResponse) response;

        httpResponse.setHeader("Cache-Control", "private");
        httpResponse.setDateHeader("Expires", System.currentTimeMillis() + 604800000L); // one week
        httpResponse.setDateHeader("Max-Age", System.currentTimeMillis() + 604800000L);

        chain.doFilter(request, response);
    }
}

This Filter works for all JavaScript files, because they don't appear in the Google Audit tool anymore. But I still get a list of images and the main JSP file. What other headers do I have to set to also enable caching for them?

This is the Request-Header of an image:

Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Cookie:entries=20; JSESSIONID=fSSOjMOknqW4yk0bH1Nxy2Ea.undefined
Host:localhost:8080
If-Modified-Since:Mon, 13 Aug 2012 12:52:32 GMT
If-None-Match:W/"1685-1344862352945"
Referer:http://localhost:8080/SSIS2_JBoss7/View/PackageManagement/Packages.jsp
User-Agent:Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1

And the Response-Header of the image:

Cache-Control:private
Date:Thu, 16 Aug 2012 08:33:05 GMT
ETag:W/"1685-1344862352945"
Expires:Thu, 23 Aug 2012 08:33:05 GMT
Max-Age:Thu, 23 Aug 2012 08:33:05 GMT
Pragma:No-cache

Solution

  • I had to add this line in order to cache all images and the main JSP file:

    httpResponse.setHeader("Pragma", "private");