Preventing image caching

The first time a browser loads an image it saves it into a local cache, to prevent reading the same image from the remote source if a URL is reloaded, and consequently speeding up loading time, since the image is loaded from the local cache.
This is not convenient, however, when working with servlets to dynamically generate images as described so far. An image is processed and delivered by a servlet upon submission of a client request from a browser, and the processing usually happens based on parameters.
Although parameters values might change over time, in certain circumstances the same servlet URL must return different images, e.g. a line chart that is plotted against time displaying daily website hits. In this situation, even if a servlet is resubmitted several times, a browser might insist on displaying an outdated image loaded from the local cache.

There are two workarounds for this problem:

  1. Each time a request is submitted, pass a unique id as a servlet parameter, so that there will never be identical URLs, and the browser is forced to get a fresh image from the server. For example, if the servlet request is submitted from a JSP page, the unique id can be set as the current time in milliseconds, using the method System.currentTimeMillis() to embed the id in the servlet URL string.

  2. Set the http response headers as follows:

    • response.setHeader("Cache-Control","no-cache");
    • response.setHeader("Pragma","no-cache");
    • response.setDateHeader("Expires",0);

    Setting the response headers might not work properly with some browsers.

The example below is a JSP page that loads a JPEG image from a servlet. The request is submitted using the <image> HTML tag, passing the servlet URL to the src attribute.
The method System.currentTimeMillis() is used to embed a unique id into the servlet URL. The JSP page is submitting a request to the servlet Example3.java, listed in the previous topic about the usage of the Java Advanced Imaging API.


<html>

  <body bgcolor=white>

    <center>
    
      <image src=http://localhost:8080/examples/servlet/Example3?id=<%=System.currentTimeMillis()%>>
      
    </center>

  </body>

</html>