How to add query string parameters using Spring HATEOAS?

I am trying to create a resource search link. So, I want to create a resource that provides a link to my search:

POST /resourcesearch {param1: "value1",param2:"value2"} 

The answer should be:

 {"links":[ { "rel":"self", "href":"http://localhost:8080/resourcesearch" }, { "rel":"resources", "href":"http://localhost:8080/resources?param1=value1&param2=value2" } } 

Here is my code:

 @Controller @RequestMapping("/resourcesearch") public class ResourceSearchController{ @RequestMapping(method = RequestMethod.POST) public ResponseEntity<ResourceSupport> createResourceSearch(@RequestBody ResourceDTO dto){ ResourceSupport resource = new ResourceSupport(); //... do something here to build query string based on "dto" resource.add(linkTo(ResourceController.class).withRel("resources")); return new ResponseEntity<ResourceSupport>(resource, HttpStatus.CREATED); } } =========================================== @Controller @RequestMapping("/resources") public class ResourceController{ @RequestMapping(method = RequestMethod.GET) public ResponseEntity<CollectionDTO> listResources(@RequestParam("param1") String param1, @RequestParam("param2") String param2){ ... } } 

The thing is, I cannot figure out how to add query string parameters to the URL in the string:

 resource.add(linkTo(ResourceController.class).withRel("resources")); 

Because the result of this line:

 { "links" : [ { "rel":"resources", "href":"http://localhost:8080/resources" } ] } 

Any ideas?

+6
source share
1 answer

There are several (potential) inconsistencies between the names that you used in your resources and the desired result, so I can’t accurately display this.

In any case, you need to use methodOn ControllerLinkBuilder . Here is a good example that should make you.

For more complex examples, unit tests for Spring HATEOAS are a good source of examples.

+4
source

All Articles