HATEOAS (hypertext as the engine of application state)

 HATEOAS (HyperMedia as the engine of application state)

in any web application you see

  1. See Data
  2. Perform Action (using Links)
How to Implement this Action Links (Options)
  • Custom format and Implementation
    • Difficult to maintain (need to create structure in pojo)
  • Use Standard Implementation
    • HAL (JSON Hypertext Application Language) : This is simple format that gives a consistent and easy way to hyperlink between resources in your API This will define how to Link other resources in the REST API
STEP 1: add given below dependancy in pom.xml

<dependency>

    <groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-hateoas</artifactId>

</dependency>


Step 2:


import org.springframework.hateoas.EntityModel;

@RestController

public class UserResourceController {

private UserDaoService userDaoService;

//http://localhost:8080/users

//EntityModel

//WebMvcLinkBuilder

@GetMapping("/users/{id}")

public EntityModel<User> retrieveUser(@PathVariable int id) {

User user = userDaoService.findOne(id);

if(user == null) {

throw new UserNotFoundException("id:"+id);

}

EntityModel<User> entityModel = EntityModel.of(user);

WebMvcLinkBuilder link = linkTo(methodOn(this.getClass()).retrieveAllUser());

entityModel.add(link.withRel("all-users"));

return entityModel;

}

}


Step 3: Given above example is create link by given below 3 line of code only


EntityModel<User> entityModel = EntityModel.of(user);

WebMvcLinkBuilder link = linkTo(methodOn(this.getClass()).retrieveAllUser());

entityModel.add(link.withRel("all-users"));





Comments

Popular posts from this blog

Introduction of RESTful Web Service

Learn JPA and Hibernate

Implementing Dynamic Filtering for Rest API