在spring mvc中,两者的作用都是将request里的参数的值绑定到contorl里的方法参数里的,区别在于,url写法不同。
使用@RequestParam时,URL是这样的:http://host:port/path?参数名=参数值
使用@PathVariable时,URL是这样的:http://host:port/path/参数值
例如:
@RequestMapping(value="/user",method = RequestMethod.GET)
public @ResponseBody
User printUser(@RequestParam(value = "id", required = false, defaultValue = "0")
int id) {
User user = new User();
user = userService.getUserById(id);
return user;
}
@RequestMapping(value="/user/{id:\d+}",method = RequestMethod.GET)
public @ResponseBody
User printUser2(@PathVariable int id) {
User user = new User();
user = userService.getUserById(id);
return user;
}
上面两个方法,访问路径分别如下:


以上就是对比比较@RequestParam与@PathVariable的用法区别的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号