@RequestParam和@PathVariable的区别及其应用场景
2022-09-16 09:12 ly772186472 阅读(179) 评论(0) 收藏 举报@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这种方式。

当然了,有些时候也不是为了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; }
浙公网安备 33010602011771号