Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I prevent browser caching with Play?

Part of my app provides a file to be downloaded using the redirect() method. I have found that Chrome (and not Firefox or IE, weirdly) is caching this file so that the same version gets downloaded even if it has changed server-side. I gather that there is a way to tell a browser not to cache a file, e.g. like this in the HTML, or by adding something to the HTTP header. I could probably figure those out in a lower-level web framework, but I don't know how to get at the header in Play!, and the HTML option won't work because it's not an HTML file.

It seems like there's always a clever and simple way to do common tasks in Play!, so is there a clever and simple way to prevent caching in a controller?

Thanks!

Edit:

Matt points me to the http.cacheControl setting, which controls caching for the entire site. While this would work, I have no problem with most of the site being cached, especially the CSS etc. If possible I'd like to control caching for one URL at a time (the one pointing to the downloading file in this case). It's not exactly going to be a high-traffic site, so this is just academic interest talking.

Ideally, I'd like to do something like:

public static void downloadFile(String url) {
  response.setCaching(false);  // This is the method I'm looking for
  redirect(url);  // Send the response
}
like image 507
andronikus Avatar asked Sep 25 '11 18:09

andronikus


People also ask

How do I stop my browser from caching?

Here's how... When you're in Google Chrome, click on View, then select Developer, then Developer Tools. Alternatively, you can right click on a page in Chrome, then click Inspect. Click on the Network tab, then check the box to Disable cache.

What does disable caching mean?

Along the top of the network panel, there's a checkbox that says “Disable Caching.” This disables browser-level caching, but only as long as the DevTools are open. So it won't affect your normal browsing, but while working with the developer tools you won't have to worry about stale content.

Do browsers automatically cache?

Browser handles automatically cache of resources. What you seem to be asking about is the actuall response from the server. You will need to set that up yourself in your application. You can do so both on front-end and backend.


1 Answers

Tommi's answer is ok, but to make sure it works in every browser, use:

response().setHeader("Cache-Control", "no-cache, max-age=0, must-revalidate, no-store");
like image 70
Gus Avatar answered Sep 28 '22 13:09

Gus