Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTTP response caching

Tags:

I want to ensure that my servet's response is never cached by the broswer, such that even if two identical requests are made (a nanosecond apart), the server is always contacted. Is this the correct way to achieve this:

class MyServlet extends HttpServlet {      protected void doGet(HttpServletRequest request, HttpServletResponse response) {         response.setHeader("Cache-Control", "no-cache");     } } 

Thanks, Don

like image 585
Dónal Avatar asked Aug 05 '10 08:08

Dónal


People also ask

Which HTTP requests can be cached?

The POST response body can only be cached for subsequent GET requests to the same resource. Set the Location or Content-Location header in the POST response to communicate which resource the body represents. So the only technically valid way to cache a POST request, is for subsequent GETs to the same resource.

What is HTTP response cache?

android.net.http.HttpResponseCache. Caches HTTP and HTTPS responses to the filesystem so they may be reused, saving time and bandwidth. This class supports HttpURLConnection and HttpsURLConnection ; there is no platform-provided cache for DefaultHttpClient or AndroidHttpClient .

Does HTTP use caching?

HTTP is designed to cache as much as possible, so even if no Cache-Control is given, responses will get stored and reused if certain conditions are met. This is called heuristic caching. For example, take the following response. This response was last updated 1 year ago.

How does HTTP support caching?

HTTP caching occurs when the browser stores local copies of web resources for faster retrieval the next time the resource is required. As your application serves resources it can attach cache headers to the response specifying the desired cache behavior.


1 Answers

No, that's not the correct way. Here is the correct way:

response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. response.setHeader("Pragma", "no-cache"); // HTTP 1.0. response.setDateHeader("Expires", 0); // Proxies. 

You'll probably see someone else suggesting other entries/attributes, but those are completely irrelevant when at least the above are mentioned.

Don't forget to clear your browser cache before testing after the change.

See also:

  • Caching tutorial for webmasters
  • Making sure a page is not cached across all browsers
like image 83
BalusC Avatar answered Oct 20 '22 00:10

BalusC