1

What is the best way to create @RequestMapping when i need to find user by id (e.g. "api.com/id5") and by nickname ("api.com/nick1")? I have problem with same pattern and Spring mapping can define "id1" as a nickname (but it is impossible because the nicknames are checked before registration). I thought that the code has to be like this:

@RequestMapping(value = "/id{id}", method = RequestMethod.GET)
    public ResponseEntity<Object> getUserById(@PathParam("id") long id){
        return ...;
    }

    @RequestMapping(value = "/{nickname}", method = RequestMethod.GET)
    public ResponseEntity getUserByNickname(@PathParam("nickname") String nickname){
        return ...;
    }

One more solution: get just a string from uri path and manually check, is it an id or nickname. So, how to do it the right way?

Vadym Borys
  • 115
  • 2
  • 11

1 Answers1

2

Use @PathVariable and put slashes in between, so the PathVariable stands by itself and is uniquely identified.

@RequestMapping(value = "/id/{id}", method = RequestMethod.GET)
public ResponseEntity getUserById(@PathVariable("id") long id){
    return ...;
}

@RequestMapping(value = "/user/{name}", method = RequestMethod.GET)
public ResponseEntity getUserByNickname(@PathVariable("name") String name){
    return ...;
}
A1m
  • 2,897
  • 2
  • 24
  • 39