Refresh Image in JSP/ Avoiding cache

爱⌒轻易说出口 提交于 2019-12-13 06:04:25

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/17479748/refresh-image-in-jsp-avoiding-cache

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!