Spring MVC Framework Using Hateoas

Share:
Spring MVC Rest is the framework to develop the services using Json, it provides only plain response, and it will not point to the other rest links. Spring Rest framework clients will tightly depends on provider as they it need to by provider if any modifications to rest endpoints.

Spring Hateoas(Hypertext as the Engine of Application State) is the framework it resolves most of the dependent issues, by providing hyperlinks to inner/linked resource.
Spring MVC Framework Using Hateoas
If we know the initial/staring URI of the service, all different application endpoints can easily understood the client by parsing the initial response.

Some of the Classes used in Hateoas: 

1.Link: it is the classes used to create hyperlinks, it has two fields, rel and href. Href property points to hyperlink and rel contains hyperlink type like self, next etc.

Link link = new Link("http://localhost:8080/test");

assertThat(link.getHref(), is("http://localhost:8080/test"));

assertThat(link.getRel(), is(Link.SELF));

2.Resource Support: It is the base class containing all hyperlinks for a data transfer objects.

Example:

public class StudentResource extends ResourceSupport {
              long id;
              String firstname;
              String lastname;
              // setters and getters
            }
            StudentResource resource = new StudentResource();
            resource.id=1L;
            resource.firstname = "Dave";
            resource.lastname = "Matthews";
            resource.add(new Link("http://myhost/student"));
            The output will be 
            {
              "id":1,
              "firstname": "Sravan",
              "lastname": "K",
              "links": [
                {
                  "rel": "self",
                  "href": "http://myhost/student"
                }
              ]
            }
            

3.LinkBuilder: It is the interface is used for creating links at different application layers.LinkBuilderSupport is the abstract class provides the abstract implementations of interface.

ControllerLinkBuilder is the class used to link using spring rest controller methods.

Example:

Suppose if the controller contains below methods:

@Controller
            @RequestMapping("/students")
            class StudentController {
            
              @RequestMapping(method = RequestMethod.GET)
              public HttpEntity<StudentResource> showAll() {}
            
              @RequestMapping(value = "/{studentId}", method = RequestMethod.GET)
              public HttpEntity<StudentResource> show(@PathVariable Long studentId) {}
            }
            
Link link = linkTo (StudentController.class).withRel("students"); is the link points to first method and

Link link = linkTo (StudentController.class).slash(student.getId()).withSelfRel(); is the link to points second method, to show the student id url.

ControllerLinkBuilder internally depends up on ServletUricomponentBuilder an extension of UricomponentBuilder which is used to prepare the absolute uri of the link.

The slash method will accept either object or any object which implements the org.springframework.hateoas.Identifiable interface, then we can pass the object instead of object property, by default it will call getId() method instead of toString() method.

 Student student = new Student(1L, "Dave", "Matthews");
                    

Link link = linkTo(StudentController.class).slash(student.getId()).withSelfRel();

If the Student class implements Identifiable interface then

 Student student = new Student(1L, "Dave", "Matthews");
        

Link link = linkTo(StudentController.class).slash(student).withSelfRel();

AnnotationMappingDiscoverer is the class is used to discover the @requestMapping annotation method and also @RequestParam, @PathVariable and @MatrixVariable etc… While creating links.

methodOn() method present in ControllerLinkBuilder class which will return proxy for dummy method implementation.

The framework passed into the methods are typicallyignored, exclude the ones mention to through @PathVariable as they create up the URI.

EntityLinks: EntityLinks is the easier way to create hyperlinks, it will not depends on controller methods, it will only depends on entities.

EntityLinks is available for dependency injection by activating @EnableEntityLinks in Spring MVC configuration.

Activating this functionality will cause all Spring MVC controllers and JAX-RS resource implementations available in the current ApplicationContext being inspected for the @ExposesResourceFor(…) annotation. 

The annotation exposes which model type the controller manages. The annotation exposes which model type the controller manages. 

Beyond that we assume you follow the URI mapping convention of a class level base mapping and assuming you have controller methods handling an appended /{id}.

Sample Controller look like below:

@Controller
            @ExposesResourceFor(Order.class)
            @RequestMapping("/orders")
            class OrderController {
            
              @RequestMapping
              ResponseEntity orders() {  }
            
              @RequestMapping("/{id}")
              ResponseEntity order (@PathVariable ("id") ){}
            }
            
            And the entityLinks in other controller:
            
            @Controller
            class PaymentController {
            
              @Autowired EntityLinks entityLinks;
            
              @RequestMapping(, method = HttpMethod.PUT)
              ResponseEntity payment(@PathVariable Long orderId) {
            
                Link link = entityLinks.linkToSingleResource(Order.class, orderId);
                
              }
            }
            

ResourceAssemblerSupport is the class to create resource links, for single and all resources.

StudentResourceAssembler:

class StudentResourceAssembler extends ResourceAssemblerSupport<Student, StudentResource> {
            
              public StudentResourceAssembler() {
                super(StudentController.class, StudentResource.class);
              }
            
              @Override
              public StudentResource toResource(Student student) {
            
                StudentResource resource = createResource(student);
                // … do further mapping
                return resource;
              }
            }
            

And the link creation will be:

Student student = new Student();
            Iterable<Student> people = Collections.singletonList(student);
            StudentResourceAssembler assembler = new StudentResourceAssembler();
            StudentResource resource = assembler.toResource(student);
            List<StudentResource> resources = assembler.toResources(people);
            

Conclusion:

Spring Hateoas is the frameworks for providing the hypermedia link in response, client need the single point of the entry point of the provider, and inner/linked resource will get the previous response,

so that if the provider endpoints are modified then also client cannot modify their code, Also, the application can advertise new capabilities by putting new links or URIs in the representation.

Author Bio: Chirag thumar is working as a web programmers at Nex, Nex is leading Java J2ee development company India and USA. He runs his own company main focus Java based web application using JQuery, Struts, JSF, node.Js, spring, Ext Js, etc.

He Writes about Emergency technology, Java based frameworks & tools, Innovative quotes, Social Media News and online marketing.

Get OUR Direct UPDATE
in your inbox

Subscribe to our mailing list and get interesting stuff and updates to your email inbox.