REST通过id和昵称获取用户

时间:2017-07-13 20:58:47

标签: java spring rest mapping uri

当我需要按ID(例如“api.com/id5”)和昵称(“api.com/nick1”)查找用户时,创建@RequestMapping的最佳方法是什么?我有相同模式的问题,Spring映射可以将“id1”定义为昵称(但这是不可能的,因为在注册前检查昵称)。我认为代码必须是这样的:

@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 ...;
    }

还有一个解决方案:从uri路径中获取一个字符串并手动检查,它是id还是昵称。 那么,如何以正确的方式做到这一点?

1 个答案:

答案 0 :(得分:2)

使用@PathVariable并在其间添加斜杠,因此PathVariable独立并且唯一标识。

@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 ...;
}