javascriptjavahtmltomcatcaching

Update from Tomcat 8.5 to 9: different caching behaviour


I have a web-application, which displays some 3D objects. The 3D objects are static files in a TomCat subdirectory. The app is based on Java 8 and JavaScript. If it runs under TomCat 8.5 everything works well for every web-browser. Using TomCat 9.0 it does not display the objects. I figured out so far, that it seems to be a caching problem: when I switch off caching in the developer modes of Edge or Chrome everything loads perfectly again.

My question is, how can I switch off caching in TomCat 9?

I have already tried some ideas which I found in the forum, like:

  1. adding the Cache-Control, Pragma and Expires meta tags to the head-section in html
  2. adding a TOMCATROUTE/conf/context.xml file with < Context>< Resources antiResourceLocking="false" cachingAllowed="false"/>< /Context>
  3. use the context.xml file below in conf/Catalina/localhost (the files not to be cached are situated in c:\xxx\service and are invoked by TOMCATINVOKE/service/... )

but neither worked. Any ideas?

Thank you.

<Context>
  <Resources>
    <PreResources className="org.apache.catalina.webresources.DirResourceSet"
                  base="C:\xxx\service"
                  webAppMount="/service" />
  </Resources>
</Context>

PS: The most weired thing is, that is works fine with FireFox, but not in Edge or Chrome (except I change to developer mode and switch off caching).


Solution

  • You can use a simple servlet filter to disable caching for app resources, below is a simple servlet filter

    package com.yourapp.filters;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    public class NoCacheFilter implements Filter {
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
    
            HttpServletResponse httpRes = (HttpServletResponse) response;
    
            httpRes.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, proxy-revalidate");
            httpRes.setHeader("Pragma", "no-cache");
            httpRes.setDateHeader("Expires", 0);
    
            chain.doFilter(request, response);
        }
    }
    

    Register in web.xml

    <filter>
        <filter-name>NoCacheFilter</filter-name>
        <filter-class>com.yourapp.filters.NoCacheFilter</filter-class>
    </filter>
    
    <filter-mapping>
        <filter-name>NoCacheFilter</filter-name>
        <url-pattern>/service/*</url-pattern>
    </filter-mapping>
    

    Place your 3D files under:

    <your-webapp-root>/webapp/service/