Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom response for root request int the Spring REST HATEOAS with both RepositoryRestResource-s and regular controllers

Let's say I have two repositories:

@RepositoryRestResource(collectionResourceRel = "person", path = "person") public interface PersonRepository extends PagingAndSortingRepository<Person, Long> {     List<Person> findByLastName(@Param("name") String name); } 

and

@RepositoryRestResource(collectionResourceRel = "person1", path = "person1") public interface PersonRepository1 extends PagingAndSortingRepository<Person1, Long> {     List<Person1> findByLastName(@Param("name") String name); } 

with one regular controller:

@Controller public class HelloController {     @RequestMapping("/hello")     @ResponseBody     public HttpEntity<Hello> hello(@RequestParam(value = "name", required = false, defaultValue = "World") String name) {         Hello hello = new Hello(String.format("Hello, %s!", name));         hello.add(linkTo(methodOn(HelloController.class).hello(name)).withSelfRel());         return new ResponseEntity<>(hello, HttpStatus.OK);     } } 

Now, a response for http://localhost:8080/ is:

{   "_links" : {     "person" : {       "href" : "http://localhost:8080/person{?page,size,sort}",       "templated" : true     },     "person1" : {       "href" : "http://localhost:8080/person1{?page,size,sort}",       "templated" : true     }   } } 

but I want to get something like this:

{   "_links" : {     "person" : {       "href" : "http://localhost:8080/person{?page,size,sort}",       "templated" : true     },     "person1" : {       "href" : "http://localhost:8080/person1{?page,size,sort}",       "templated" : true     },     "hello" : {       "href" : "http://localhost:8080/hello?name=World"     }   } } 
like image 201
jcoig Avatar asked Sep 11 '14 09:09

jcoig


2 Answers

@Component public class HelloResourceProcessor implements ResourceProcessor<RepositoryLinksResource> {      @Override     public RepositoryLinksResource process(RepositoryLinksResource resource) {         resource.add(ControllerLinkBuilder.linkTo(HelloController.class).withRel("hello"));         return resource;     } } 

based on

  • http://docs.spring.io/spring-data/rest/docs/current/reference/html/#customizing-sdr.customizing-json-output
  • How to add links to root resource in Spring Data REST?
like image 175
palisade Avatar answered Sep 23 '22 23:09

palisade


You need to have a ResourceProcessory for your Person resource registered as a Bean. see https://stackoverflow.com/a/24660635/442773

like image 23
Chris DaMour Avatar answered Sep 21 '22 23:09

Chris DaMour