How to add query string parameters with Spring HATEOAS?
Asked Answered
J

1

13

I'm trying to generate a link to search resources. So, I want to create a resource that provides a link to my search:

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

The response 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 that I can't figure out how to add query string parameters to the url in the line:

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

Because the result of that line is:

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

Any ideas?

Johnny answered 24/3, 2014 at 16:16 Comment(0)
C
6

There are a couple of (potential) mismatches between the names that you have used in your resources and desired output, hence I am not able to map that very well.

Anyway, you need to use the methodOn of ControllerLinkBuilder. Here's a good example that should get you going.

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

Canard answered 24/3, 2014 at 19:29 Comment(1)
There was a typo in my @RequestMapping on ResourceController class. I edited so the code is consistent.Johnny

© 2022 - 2024 — McMap. All rights reserved.