Servlet based image protection

Over the weekend I implemented a system on my photo sites to exert some control over the viewing and or downloading of my photos.

This essentially involved running image requests through some custom code to check for correct permission to view the image.

In general terms, here’s how to add the same to your site (should you want it).

Image Servlet.

You will need to write a servlet or whatever takes its place in your MVC architecture of choice.

This servlet will be handling image requests so needs to perform the necessary checks that the user is allowed to view this image (check for a cookie, look at referrer etc).

If the user fails these checks then you can set the response status code to a 403 (or 404 if you prefer), then reset the response.

If however a user is allowed to view the image then you can forward this request to the image (using RequestDispatcher.forward with the uri of the image), which lets your servlet engine serve the image instead of Apache/IIS. Therefore valid requests to this servlet will serve the image to the browser.

Request Mapping.

To have requests for images call your code instead of just displaying the image, you need to map any requests for images to your servlet.

To do this I used Apache’s mod rewrite to forward requests for .jpg files in my photo directory to the uri for the code described above.

As an alternative you could rename all your image links to be calls to your servlet, and pass the image filename as a parameter.

The important thing is that you don’t lose the name of the image file, as you need it to do the forwarding (obvious really).

The other important thing to watch for is that the final forward to the image does not forward back to your servlet and end up in a loop.

To get around this I ensure that the image files are in a different directory to the directory mapping in the URL, then switch that part of the URL so the image forward is not picked up by my mod rewrite rule.


  • You may need to set up your servlet engine to serve images. I use resin, which doesn’t need any extra configuration for that.

  • You may wish to implement some sort of last modified scheme to save bandwidth. On the other hand you may not want to do this to prevent images being cached.

    I chose to implement it. I simply checked the timestamp of the file against the various headers.

    That’s about it.

    Let me know how you get on if you decide to do it or if you have any questions.

  • One thought on “Servlet based image protection”

    Comments are closed.