Our Twitter results are neatly cached, so a user refreshing the result page will not trigger an additional search on the Twitter API. However, the response will be sent to this user multiple times even if the results do not change, which will waste bandwidth.
An ETag is a hash of the data of a web response and is sent as a header. The client can memorize the ETag of a resource and send the last known version to the server with the If-None-Match
header. This allows the server to answer 304 Not Modified
if the request does not change in the meantime.
Spring has a special Servlet filter, called ShallowEtagHeaderFilter
, to handle ETags. Simply add it as a bean in the MasterSpringMvc4Application
configuration class:
@Bean public Filter etagFilter() { return new ShallowEtagHeaderFilter(); }
This will automatically generate ETags for your responses as long as the response has no cache control headers.
Now if we interrogate our RESTful API, we can see that an ETag is sent along with the server...