1

In my project we use some img tags like that

<img src="url to java servlet?parameters">

while the servlet responds the bytesteam right away, something like

response.getOutputStream().write(imageBytes);

That all works fine, but is there any way of caching that image in the browser, because it wont cache it automatically like regular url images.

kan
  • 28,279
  • 7
  • 71
  • 101
alianos-
  • 886
  • 10
  • 21

3 Answers3

2

See the Caching Tutorial for Web Authors and Webmasters.

You want to output suitable Cache-Control headers and/or handle If-Modified-Since and/or ETag requests.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

Your servlet should provide logic for if-modified-since, expired logic. See getLastModified method.

kan
  • 28,279
  • 7
  • 71
  • 101
1

You need to set at least the ETag, Last-Modified and Expires headers on the response. The ETag header should represent the unique identifier of the file based on a combination of filename, filesize and lastmodified timestamp). The Last-Modified header should represent the last modified timestamp of the file. The Expires header should inform the client how long it is allowed to keep the file in cache.

If the cache has been expired in the client side and the ETag or Last-Modified are available, then the client will send a HEAD request to check if the file needs to be renewed. If not, then the Expires will just be postponed again accordingly.

You can find here a servlet example which handles this all (and download resumes and automatic GZIP): FileServlet supporting resume and GZIP.

However, if your files are available on the disk file system already (and not in a database), then you should consider just delegating the job to the servletcontainer's builtin default servlet. See also Reliable data serving.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555