在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;
- }
上面两个方法,访问路径分别如下:


本文介绍了 Spring MVC 中的两种参数绑定方式:@RequestParam 和 @PathVariable。@RequestParam 用于从 URL 查询字符串中获取参数,而 @PathVariable 则是从 URL 路径中直接获取值。举例说明了两者在实际使用时的URL形式,并展示了如何在控制器方法中接收参数。
5219

被折叠的 条评论
为什么被折叠?



