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

标签 java json spring spring-mvc

每当我需要在 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/

相关文章:

java - retorfit2 如何让这个 json 正确?

java - 在Android中实现数据缓存

c# - 在没有 Json.Net 的情况下反序列化 Json 字符串(在 C# 中)

spring - 使用 SQL 查询的动态 Spring Security

java - 我可以使用 <http :auto-config=true> and <UsernamePasswordAuthenticationFilter> at the same time in spring security

Java Applet 和浏览器卡住

java - 如何运行 java -cp 命令

java - 使用 restTemplate 发送带有身份验证 header 的 GET 请求

java - Song类,使用抽象类和接口(interface)

java - 如何检查一年中的月份是否为一月