Prevent browser from caching resources

Introduction

In this tutorial I am going to tell you how you can prevent cache in browser. Sometimes we need to clear the browser cache or prevent the browser from caching resources so that we always get the latest output from the server. Disabling caching of your web pages ensures your resources are coming every time from the server.

In every browser, you’ll find an option to disable caching or even you can clear the cached resources but this type of caching is client side caching and we do not rely on whether users will disable cache or clear cache. Therefore we want to ensure that every time a page is requested will bring the updated content from the server.

I assume that you have Java, JSP and Servlet based application where you want to get updated or recent content on your web pages.

Here is an example on how to prevent browser from caching resources.

Prerequisites

Java, JSP, Servlet

HTTP Header Constants

We need to define some constants which are mainly found in HTTP headers of the request.

public enum HTTPCacheHeader {
    CACHE_CONTROL("Cache-Control"),
    EXPIRES("Expires"),
    PRAGMA("Pragma"),
    private String name;
    private HTTPCacheHeader(String name) {
        this.name = name;
    }
    public String getName() {
        return this.name;
    }
}

The above enum constants are used for http headers. For more information on enum please read how to create enum in Java

Servlet Filter

We need to create a Servlet filter that will actually prevent browser caching for each request coming from the client.

This servlet filter actually sets some cache control headers so that browser will not cache resources.

public class NoCacheFilter implements Filter {
    public NoCacheFilter() {
    }
    public void destroy() {
    }
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResp response
        // set cache directives        httpServletResponse.setHeader(HTTPCacheHeader.CACHE_CONTROL.getName(),
                "no-cache, no-store, must-revalidate"); // HTTP 1.1
        httpServletResponse.setHeader(HTTPCacheHeader.PRAGMA.getName(),
                "no-cache"); // HTTP 1.0
        httpServletResponse
                .setDateHeader(HTTPCacheHeader.EXPIRES.getName(), 0L); // Proxies
        // pass the request along the filter chain
        chain.doFilter(request, response);
    }
    public void init(FilterConfig fConfig) throws ServletException {
    }
}

So the above filter adds http header directives for each web page and prevents caching. You are not actually clearing the cache rather preventing browser from caching resources.

Update web.xml

Now in order to let web application work with the servlet we need to make corresponding entry of servlet filter into deployment descriptor – web.xml file.

<?xml versi encoding "UTF-8"?>
<web-app versi
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocati>
    <filter>
        <display-name>NoCacheFilter</display-name>
        <filter-name>NoCacheFilter</filter-name>
        <filter-class><fully qualified package name>.NoCacheFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>NoCacheFilter</filter-name>
        <url-pattern>*.jsp</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>
    <session-config>
        <session-timeout>20</session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>/index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

We put entry of the servlet filter into web.xml file for each requested or forwarded jsp page.

That’s all. Thanks for reading.

Related posts

Leave a Comment