在JSP /避免缓存中刷新图像 [英] Refresh Image in JSP/ Avoiding cache

查看:171
本文介绍了在JSP /避免缓存中刷新图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发web项目,我必须生成图像并在加载时在JSP页面上显示它。现在的问题是我必须使用相同的图像名称,因此浏览器总是使用缓存图像而不是新图像。

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>

点击按钮,jsp页面再次加载。
我正在使用上面的代码,但我仍然只在下一页加载时得到缓存(旧)图像。哪里出错了。

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.

请帮忙。

谢谢

推荐答案

既然你正在使用JSP,你可以使用 System.currentTimeMillis()附加当前时间。

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

替换为:

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

这个:

<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.

你也可以用javascript做到这一点,但你的工作不起作用,因为它有错误。使用 + 而不是来连接字符串。

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(); //错误

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

请注意,因为 onload 仅在所有内容时执行(包括图像)已加载。这意味着当您打开页面时,您将获得缓存版本(但非缓存版本将在一段时间后加载)。

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).

还有其他方法,比如在HTTP响应中设置no-cache标头,但我想这不是这个问题的重点。

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.

这篇关于在JSP /避免缓存中刷新图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆