It seems somewhat awkward whenever I need to deal with custom responses data type on Spring MVC.
In my case, I need to return a JavaScript content. However, I want it to be cache.
So to clarify, this is not a static file case (<mvc:resources...), Instead it’s a dynamic file generated on the server, that I do want to cache (i.e. HttpResponse 200 and HttpResponse 302).
In terms of code, on the client side I simply have:
<script src="<spring:url value='/some-file.js'/>"></script>
Than a 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);
}
However, it seems that the browser is always trying to access this dynamic JS file.
Since this file is Session depended, I can not generate it and treat it as a static file.
Any suggestions?
This is the correct behavior. Most browsers will send you a
GETrequest with aIf-Modified-Since+ time stamp to check whether a file has changed.In the usual case, you’d use the time stamp to figure out whether the file has changed. But since it never changes in your case, you can reply with a
304/HttpStatus.NOT_MODIFIEDresponse without a response body (instead of200/ OK).That tells the browser that the file hasn’t changed.
This should work:
Telling the browser
Last-Modifiedwill enable it to send youIf-Modified-Since