简体   繁体   中英

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 logged out?

using JSP or javascript

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.

HttpServletResponse hsr = (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}" />

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+"'/>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM