Home > java > Caching Images that are dished out with a Servlet

Caching Images that are dished out with a Servlet

February 18th, 2004 kikkoman

   You can find examples of how to dish out an image via a servlet online, but they don’t go into the caching of the image. Basically, you ‘name’ the servlet in the “src” of your img tag and in your web.xml file.

<img src=”imageServlet.imageServ?imageId=xxxx”>

and in the web.xml:
<servlet-mapping>
   <servlet-name>ImageServlet</servlet-name>
   <url-pattern>*.imageServ</url-pattern>
</servlet-mapping>

Caching: My coverage is an extension of a post here.

To get the browser to cache the image you need to set some headers.
response.setDateHeader( “Last-Modified”, image.getModifiedDate() );

On the next access of the image, the browser will/should respond with a “If-Modifed-Since” header. Compare the image’s timestamp on the server with the timestamp from the browser. If the browser has an old copy or didn’t set the header, send out the image. If the browser has the image, you set a HTTP response of 304 “Not-Modified”.

So in the end it looks something like this:

long browserTime = request.getDateHeader( “If-Modified-Since” );
long imageTime = image.getModifedDate();
if ( browserTime == -1 || imageTime > browserTime )
{
   // send the image
   response.setDateHeader( “Last-Modified”, imageTime );
}
else
   response.setStatus( 304 );

and you’re done.

Categories: java Tags:
Comments are closed.