Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ETag support in Spring for versioned entity

I am planning to support ETag for my RESTfull Spring application. Most of the resources I expose are versioned in DB.

I am aware of ShallowEtagHeaderFilter, which is not exactly, what I need, since it only saves bandwidth.

Is there a production ready solution for Spring MVC that associates ETag header with exposed entity version?

like image 791
mavarazy Avatar asked Sep 03 '13 04:09

mavarazy


People also ask

How is ETag implemented in REST API?

First, you retrieve the current entity data by using a GET request that includes the If-Match request header. The ETag information is returned along with the entity content. Then, you send a PUT update request that includes the If-Match request header with the ETag information from the previous GET request.

What is spring boot ETag?

An ETag (entity tag) is an HTTP response header returned by an HTTP/1.1 compliant web server used to determine change in content at a given URL. It can be considered to be the more sophisticated successor to the Last-Modified header.

How do I get an ETag value?

Generating ETag Value It can be created and updated manually or can be auto-generated. Common methods of its auto-generation include using a hash of the resource's content or just a hash of the last modification timestamp. The generated hash should be collision-free.

Where is ETag stored?

Approach C: caching the ETag. This is like approach B but ETag is stored in some cache middleware.


1 Answers

spring-data-rest supports this out-of-the-box, see the conditional request part of the reference documentation.

You can also use Spring Framework 4.2.0+ which supports conditional requests for ResponseEntity types returned by Controller methods - see reference documentation.

Something like:

@RequestMapping("/book/{id}")
public ResponseEntity<Book> showBook(@PathVariable Long id) {

    Book book = findBook(id);
    String version = book.getVersion();

    return ResponseEntity
                .ok()
                .cacheControl(CacheControl.maxAge(30, TimeUnit.DAYS))
                .eTag(version) // lastModified is also available
                .body(book);
}
like image 144
Brian Clozel Avatar answered Sep 18 '22 13:09

Brian Clozel