@RequestParam和@PathVariable的区别及其应用场景

@RequestParam和@PathVariable这两者之间区别不大,主要是请求的URL不一样

用@RequestParam请求接口时,URL是:http://www.test.com/user/getUserById?userId=1

用@PathVariable请求接口时,URL是:http://www.test.com/user/getUserById/2

(1)@PathVariable示例:

    @GetMapping(value="getUserById/{userId}",produces="application/json;charset=utf-8")
    public Object getUserById(@PathVariable String userId) {
        
        JSONObject json  = new JSONObject();
        
        if(!StrUtil.isEmpty(userId)) {
            User user = userService.getUserById(userId);
            json.put("returnCode", "000000");
            json.put("returnMsg", "success");
            json.put("user", user);
        }else {
            json.put("returnCode", "111111");
            json.put("returnMsg", "error");
        }
        return json;

    }

主要应用场景是:不少应用为了实现RestFul的风格,采用@PathVariable这种方式。

例如CSDN:

当然了,有些时候也不是为了RestFul风格而采用这种方式,有些时候觉得?userId=1&&status=1等参数传递方式不是特别好看或者是看着不爽。

 

(2)@RequestParam示例:

    @GetMapping(value="getUserById",produces="application/json;charset=utf-8")
    public Object getUserById(@RequestParam String userId) {
        
        JSONObject json  = new JSONObject();
        
        if(!StrUtil.isEmpty(userId)) {
            User user = userService.getUserById(userId);
            json.put("returnCode", "000000");
            json.put("returnMsg", "success");
            json.put("user", user);
        }else {
            json.put("returnCode", "111111");
            json.put("returnMsg", "error");
        }
        return json;

    }

 应用场景:这种方式应用也非常广,像CSDN或者是博客园都在用它,这里就不贴图了,经常浏览博客和新闻都能看到。

 

最后,你如果问我哪种方式比较好,我的回答是,根据业务场景的需求决定使用其中一种或者是结合使用。不过它们都有一个共同点,那就是都是可见。

posted @ 2018-10-15 19:50  挑战者V  阅读(6257)  评论(0编辑  收藏  举报