开发者

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 be开发者_JS百科ing 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
}


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");


I haven't tested it, but it looks like the http.cacheControl configuration setting might work.

http.cacheControl

HTTP Response headers control for static files: sets the default max-age in seconds, telling the user’s browser how long it should cache the page. This is only read in prod mode, in dev mode the cache is disabled. For example, to send no-cache:

http.cacheControl=0

Default: 3600 – set cache expiry to one hour.


It is actually this:

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


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");


response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, pre-check=0, post-check=0, max-age=0, s-maxage=0"); // HTTP 1.1.


On play currently 2.5.x to 2.8.x you can set cache life of both assets folder or assets file in configuration.

For folder-

play.assets.cache."/public/stylesheets/"="max-age=100"
play.assets.cache."/public/javascripts/"="max-age=200"

for specific file -

play.assets.cache."/public/stylesheets/bootstrap.min.css"="max-age=3600"

--- documentation https://www.playframework.com/documentation/2.8.x/AssetsOverview

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜