简体   繁体   中英

Refresh Image in JSP/ Avoiding cache

I am working on web project where I have to generate image and display it on JSP page when it gets load. Now the problem is that I am have to use same image name and hence browser is using cached image always and not the new one.

Display.jsp

<html>
  <head>  
   <script type="text/javascript">
      updateImage(){
          var img1 = document.getElementById("text");
          img1.src="sun.png?time=".new Date().getTime();
      }   
   </script>
  </head> 
  <body onload="updateImage()">
          <form action="com.CheckName" method="get">
              <input type="button" value="submit" name="submit" /> 
              <img src="sun.png" id="text">
          </form>
  </body>
</html>

By clicking on button same jsp page gets loaded again. I am using above code but still I am getting cached(old) image only on next page load. Where I am going wrong.

Please help.

Thanks

Since you're using JSP, you could append the current time using System.currentTimeMillis() .

Replace this:

<img src="sun.png" id="text">

with this:

<img src="sun.png?time=<%=System.currentTimeMillis()%>" id="text">

I wouldn't suggest you to avoid caching it all the times. Instead of appending the current time, you could append the current version number (or the last time it has changed), so users won't have to download it again everytime they open this page.


You could also do that with javascript, but yours didn't work cause it had an error. Use + instead of . to concatenate strings.

img1.src="sun.png?time=".new Date().getTime(); //wrong

img1.src="sun.png?time=" + new Date().getTime(); //ok!

Just pay attention because onload is only executed when all content (including images) has been loaded. That means you'll get the cached version when you open the page (but the non-cached version will load after a while).


There are also other approaches, like setting no-cache headers to the HTTP response, but I guess that is not the point of this question.

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