【问题标题】:REST get user by id and nickname [duplicate]REST通过ID和昵称获取用户[重复]
【发布时间】:2017-12-18 20:03:16
【问题描述】:

当我需要按 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 还是昵称。 那么,如何正确地做到这一点呢?

【问题讨论】:

    标签: java spring rest mapping uri


    【解决方案1】:

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

    【讨论】:

    • "api,com/users/id/5" 没问题,但在第二种方法中,我将拥有 "api.com/users/user/bublik"。坏主意
    猜你喜欢
    • 2013-10-15
    • 2021-07-30
    • 2021-04-05
    • 2018-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多