@RequestParam和@PathVariable的区别及其应用场景
2022-09-16 09:12 ly772186472 阅读(169) 评论(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; }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现