2

I have an implementation similar to this one that allows the caller to ask for a specific file from the filesystem. The file is one that doesn't change frequently and is being downloaded by a mobile application. Is there a way I can change this to use the 304 - Not Modified HTTP status code so the client wouldn't have to download the file when it hasn't changed? If so, would the interface to this method have to change in some way to accept a date? Is there some standard way to implement this?

@RequestMapping(value = "/files/datafile", method = RequestMethod.GET)
public void getDataFile(HttpServletResponse response) {
    try {
      // get your file as InputStream
      InputStream is = ...;
      // copy it to response's OutputStream
      org.apache.commons.io.IOUtils.copy(is, response.getOutputStream());
      response.flushBuffer();
    } catch (IOException ex) {
      log.info("Error writing file to output stream. Filename was '{}'", fileName, ex);
      throw new RuntimeException("IOError writing file to output stream");
    }

}
Community
  • 1
  • 1
Chris Williams
  • 11,647
  • 15
  • 60
  • 97

1 Answers1

0

Use Springs ETag Header support.

You just need to add this filter to your web.xml

<filter>
    <filter-name>etagFilter</filter-name>
    <filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>etagFilter</filter-name>
    <servlet-name>petclinic</servlet-name>
</filter-mapping>

Or you do it more sophisticated in your controller:

Ralph
  • 118,862
  • 56
  • 287
  • 383
  • Wouldn't the client code need to change as well? How would the server know that the value hasn't changed if the client doesn't provide a hash of the old value? – Chris Williams Dec 08 '15 at 19:17
  • If your client is an not to old webbrowser, then it should work. The key is that the client send the etag header to the browser back if it request the same url, than the server can decide if it must send back the content or just the statuscode that nothing has changed. – Ralph Dec 08 '15 at 19:28
  • The client is a mobile app. – Chris Williams Dec 08 '15 at 19:29
  • Then maybe, the client needs to modified too. to send the etag header back to the server. – Ralph Dec 08 '15 at 19:31