Prevent browser from caching resources

You may also like to read:

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 webpages ensures your resources come from the server each and every time. In every browser, you’ll find the 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.

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

Write Enum for declaring constants

public enum HTTPCacheHeader {




    private String name;

    private HTTPCacheHeader(String name) { = name;
    public String getName() {


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

Write the servlet filter

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
                "no-cache"); // HTTP 1.0
                .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. We are not clearing rather preventing browser from caching resources.

Make corresponding entry to the web.xml file

<?xml versi encoding "UTF-8"?>
<web-app versi
 xmlns:xsi="" xsi:schemaLocati>



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

That’s all. Thanks for your patience. Please leave a comment.

Prevent browser from caching resources

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top