How to disable caching of static assets like .css and .js in JSF2?

后端 未结 1 1497
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-30 17:49

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

相关标签:
1条回答
  • 2020-12-30 18:26

    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("/*")
    public class NoCacheFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (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:

    • How to control web page caching, across all browsers?

    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.

    <script src="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.

    0 讨论(0)
提交回复
热议问题