java 如何防止Servlets的结果被缓存?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5139785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to prevent the result of Servlets from being cached?
提问by Prashant
How can I stop caching of pages in browser using Servlets?
如何使用 Servlet 在浏览器中停止缓存页面?
I want that session should expire if I press back button of browser when i am logged in.
如果我在登录时按浏览器的后退按钮,我希望该会话应该过期。
回答by Dead Programmer
To permanently disable cache.
永久禁用缓存。
// Set to expire far in the past.
response.setHeader("Expires", "Sat, 6 May 1995 12:00:00 GMT");
// Set standard HTTP/1.1 no-cache headers.
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
// Set IE extended HTTP/1.1 no-cache headers (use addHeader).
response.addHeader("Cache-Control", "post-check=0, pre-check=0");
// Set standard HTTP/1.0 no-cache header.
response.setHeader("Pragma", "no-cache");
Clearing the client cache would not expire session immediately,but clears session cookies in the browser. To make the session expire immediately, you need to explicitly specify in server side jsp or servlet.
清除客户端缓存不会立即使会话过期,而是清除浏览器中的会话 cookie。要使会话立即过期,需要在服务器端jsp 或servlet 中显式指定。
// use session invalidate
session.invalidate();
回答by A. R. Younce
If you get a HttpServletResponse(implementation) object for the request you can send HTTP headers that will encourage browsers not to cache the content you send them.
如果您获得请求的HttpServletResponse(实现)对象,您可以发送 HTTP 标头,鼓励浏览器不要缓存您发送给它们的内容。
HttpServletResponse response; // You'll need to initialize this properly
response.setHeader("Cache-control", "no-cache, no-store");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
See the documentation for HttpServletResponseand HttpServletResponseWrapper. In case you need to read up on cache control headers in HTTP, check this out.
请参阅HttpServletResponse和HttpServletResponseWrapper的文档。如果您需要阅读 HTTP 中的缓存控制标头,请查看此内容。