比 -6ren">
gpt4 book ai didi

java - 强制浏览器缓存 Spring MVC 的 JS 响应

转载 作者:行者123 更新时间:2023-12-01 15:15:37 27 4
gpt4 key购买 nike

每当我需要在 Spring MVC 上处理自定义响应数据类型时,这似乎都有些尴尬。

就我而言,我需要返回 JavaScript 内容。但是,我希望它被缓存。

澄清一下,这不是静态文件情况( <mvc:resources... ),而是在服务器上生成的动态文件,我确实想缓存它(即 HttpResponse 200 和 HttpResponse 302)。

就代码而言,在客户端我只需:

<script src="<spring:url value='/some-file.js'/>"></script>

比 SpringMVC Controller :

@RequestMapping(value = "/some-file.js")
public ResponseEntity<String> resourceBundles(HttpServletRequest request, HttpServletResponse response, Locale locale) throws IOException {

responseHeaders.add("Cache-Control", "public, max-age");
responseHeaders.add("Content-Type", "text/javascript; charset=UTF-8");
responseHeaders.add("Expires", "max-age");

// Turn this into JSON response:
String someJson = "{ a:a, b;b};";
return new ResponseEntity<String>("var data = " + someJson, responseHeaders, HttpStatus.OK);
}

但是,浏览器似乎总是试图访问这个动态JS文件。

由于该文件依赖于 session ,因此我无法生成它并将其视为静态文件。

有什么建议吗?

最佳答案

这是正确的行为。大多数浏览器会向您发送带有 If-Modified-Since + 时间戳的 GET 请求,以检查文件是否已更改。

在通常情况下,您可以使用时间戳来确定文件是否已更改。但由于您的情况永远不会改变,您可以回复 304 / HttpStatus.NOT_MODIFIED response without a response body (而不是 200/OK)。

这告诉浏览器该文件没有更改。

这应该有效:

@RequestMapping(value = "/some-file.js")
public ResponseEntity<String> resourceBundles(
HttpServletRequest request,
HttpServletResponse response, Locale locale) throws IOException {

Date lmod = session.getAttribute("lmod");
if( null == lmod ) {
lmod = new Date();
session.setAttribute("lmod", lmod);
}

responseHeaders.add("Last-Modified", lmod);

String ifModifiedSince = request.getHeader("If-Modified-Since");
if( null != ifModifiedSince ) { // You may want to compare lmod and ifModifiedSince here, too
return new ResponseEntity( responseHeaders, HttpStatus.NOT_MODIFIED );
}

... create first time response ...
}

告诉浏览器Last-Modified将使它能够向您发送If-Modified-Since

关于java - 强制浏览器缓存 Spring MVC 的 JS 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11646876/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com