Skip to content Skip to sidebar Skip to footer

How To Disable Caching Of Static Assets Like .css And .js In Jsf2?

I'm trying to set up a project to not cache static assets .css and .js. We seem to be having some internal caching issues for some people and I'm hoping this clears it up. I have

Solution 1:

With the setHeader() you're overridding any previously set header. Rather use addHeader() instead, or just put all values commaseparated as the header value. Here's the complete set:

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
response.setDateHeader("Expires", 0); // Proxies.

Your another mistake is that a PhaseListener isn't the best place for this. It's only invoked on JSF page requests, not on static resource requests which are independently invoked by the webbrowser. In other words, only the JSF page itself has caching disabled, but all <script>, <link>, <img>, etc will generate new requests which doesn't invoke that PhaseListener because those are not JSF pages.

Rather use a Filter.

@WebFilter("/*")publicclassNoCacheFilterimplementsFilter {

    @OverridepublicvoiddoFilter(ServletRequest req, ServletResponse res, FilterChain chain)throws IOException, ServletException {
        HttpServletResponseresponse= (HttpServletResponse) res;
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1.
        response.setHeader("Pragma", "no-cache"); // HTTP 1.0.
        response.setDateHeader("Expires", 0); // Proxies.
        chain.doFilter(req, res);
    }

    // ... (just keep init() and destroy() NO-OP)
}

If you target a Servlet 3.0 container (Tomcat 7, Glassfish 3, etc), then web.xml (or faces-config.xml) registration is not necessary. The @WebFilter("/*") will autoregister it and map it on an URL pattern of /* which thus covers all requests.

See also:


Unrelated to the concrete problem, disabling the static asset caching altogether isn't the best idea. It unnecessarily costs network bandwidth. Rather look for a different solution, for example including the server startup timestamp in the query string.

E.g.

<scriptsrc="foo.js?#{startup.time}"></script>

with in faces-config.xml

<managed-bean><managed-bean-name>startup</managed-bean-name><managed-bean-class>java.util.Date</managed-bean-class><managed-bean-scope>application</managed-bean-scope></managed-bean>

This example would force the browser to reload the assets whenever the server has restarted.

Post a Comment for "How To Disable Caching Of Static Assets Like .css And .js In Jsf2?"