Warm tip: This article is reproduced from serverfault.com, please click

How do I prevent browser caching with Play?

发布于 2011-09-25 18:11:56

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
}
Questioner
andronikus
Viewed
0
Tommi 2011-09-26 13:28:37

Play framework response object has a setHeader method. You can add the headers you want like this, for example:

response.setHeader("Cache-Control", "no-cache");