Spring MVC, REST, and HATEOAS Spring MVC, REST, and HATEOAS spring spring

Spring MVC, REST, and HATEOAS


There is a useful project called Spring HATEOAS on GitHub which has the following description:

"This project provides some APIs to ease creating REST representations that follow the HATEOAS principle when working with Spring and especially Spring MVC"

If the resource class you are returning extends 'ResourceSupport' you can easily add links to it, and you can build links using 'ControllerLinkBuilder', for example to add a self link:

import static org.sfw.hateoas.mvc.ControllerLinkBuilder.*;Link link = linkTo(YourController.class).slash(resource.getName()).withSelfRel();resource.add(link);

It is quite a new project but it is available from the public Maven repo if required:

<dependency>    <groupId>org.springframework.hateoas</groupId>    <artifactId>spring-hateoas</artifactId>    <version>0.3.0.RELEASE</version></dependency>

If you use the maven artifact:

org.sfw.hateoas.mvc.ControllerLinkBuilder

becomes:

org.springframework.hateoas.mvc.ControllerLinkBuilder


My Thoughts:

  • using some kind of naming convention so that for example the self reference url can be constructed out of the class name of the object.
  • I do not think that adding the links stuff should be added by the controller (btw you self wrote "I don't want my controllers polluted with view constructs". I would try to search for an way to extend the JSON serialization so that it automatically add the extra stuff. May you need to add some annotations to your entities, even if this would pollute them a bit.


Just stumbled across this while looking for something else and thought you should be considering using the Link header instead of content in the JSON body which is really just polluting the representations of your resources.

Check out the IETFs memo on web linking and also the IANA registry of link relations.