在我的带有HATEOAS应用程序的Spring Boot 2 REST中,我的/users
端点生成application/hal+json
,而我的/users2
端点生成application/json
。我希望有一个端点/users
,它根据客户端定义的Accept
标头生成两个不同的表示:
# Produce JSON+HAL
curl http://localhost:8080/api/users
# Produce JSON+HAL
curl -H "Accept: application/hal+json" http://localhost:8080/api/users
# Produce JSON
curl -H "Accept: application/json" http://localhost:8080/api/users
Spring REST是否有一种优雅的方式?
两个端点当前定义为:
@GetMapping("/users")
public @ResponseBody PagedResources<PersistentEntityResource> pagedUsers(Pageable pageable, PersistentEntityResourceAssembler assembler) {
return pagedAssembler.toResource(personHandler.users(pageable), assembler);
}
@GetMapping("/users2")
public List<Person> allUsers() {
return personHandler.allUsers();
}
由于(当前)lack of reactive support in Spring HATEOAS,我需要普通的JSON(即非HALed)API。
答案 0 :(得分:-1)
我认为这可以解决您的问题:
@GetMapping("/users")
public ResponseEntity pagedUsers(Pageable pageable, PersistentEntityResourceAssembler assembler) {
if(null != pageable && null != assembler){//decide which response body you'd return
return ResponseEntity.ok(pagedAssembler.toResource(personHandler.users(pageable), assembler));
}
return ResponseEntity.ok(personHandler.allUsers());
}
但我真正建议你做的是用RESTful URL定义两个API(带有API版本和更清晰的URL),如下所示:
@GetMapping("/v1/users/paged")
public ResponseEntity<PagedResources<PersistentEntityResource>> pagedUsers(Pageable pageable, PersistentEntityResourceAssembler assembler) {
return ResponseEntity.ok(pagedAssembler.toResource(personHandler.users(pageable), assembler));
}
@GetMapping("/v1/users")
public ResponseEntity<List<Person>> allUsers() {
return ResponseEntity.ok(personHandler.allUsers());
}