Skip to content Skip to sidebar Skip to footer

Clear Image From Browser Cache In Jsp Or Javascript

I'm developing a JSP Web application for a university, and there is a personnel picture displayed in user page. How can i clear this picture from web-browser cache once the user lo

Solution 1:

That's not possible. Your best bet is to just entirely disable the caching of the resource in question. Create a filter which does the following job in the doFilter() method.

HttpServletResponsehsr= (HttpServletResponse) response;
hsr.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
hsr.setHeader("Pragma", "no-cache");
hsr.setDateHeader("Expires", 0);
chain.doFilter(request, response);

and map it on an URL pattern covering the image(s) of interest.


Edit: if you actually don't care about the image being present in the browser cache, but your concrete problem is that different logged-in users basically use the same image URL because it's been served dynamically by some servlet, then you can also solve it by giving every unique user an unique image URL. You can do this by appending for example the user ID as request parameter to the image URL, or including it in the image's path.

<img src="profileimage?id=${user.id}" />

or

<img src="profileimage/${user.id}" />

Solution 2:

The question clearly doesn't distinguish between client-side and server-side code.

For one thing, when a user closes the web browser, you just can't clear the cache, because the browser's gone.

That said, you can keep track of image changes and append a number to the image URL - this will force the web browser to ignore the cache and load the new image.

Example:

File filename = new File("/path/to/profile.png");
long t = filename.lastModified();
System.out.print("<img src='profile.png?"+t+"'/>");

Post a Comment for "Clear Image From Browser Cache In Jsp Or Javascript"