HATEOAS (hypertext as the engine of application state)
HATEOAS (HyperMedia as the engine of application state)
in any web application you see
- See Data
- Perform Action (using Links)
- 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
<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
Post a Comment