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

2

29

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"
    }
  }
}
Lema answered 11/9, 2014 at 9:12 Comment(0)
P
31
@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

Plains answered 30/9, 2014 at 10:21 Comment(0)
U
1

You need to have a ResourceProcessory for your Person resource registered as a Bean. see https://mcmap.net/q/502436/-canonical-_links-with-spring-hateoas

Unmarked answered 16/9, 2014 at 17:26 Comment(1)
But I don't want to change response for any of http://localhost:8080/person, http://localhost:8080/person1 or http://localhost:8080/hello requests. I want to change auto-generated response for http://localhost:8080/ request.Lema

© 2022 - 2024 — McMap. All rights reserved.