@RequestParam与@PathVariable的区别

spring MVC中,两者的作用都是将request里的参数的值绑定到contorl里的方法参数里的,区别在于,URL写法不同。

使用@RequestParam时,URL是这样的:http://host:port/path?参数名=参数值

使用@PathVariable时,URL是这样的:http://host:port/path/参数值

例如:

 

[java]  view plain  copy
 
  1. @RequestMapping(value="/user",method = RequestMethod.GET)  
  2.    public @ResponseBody  
  3.    User printUser(@RequestParam(value = "id", required = false, defaultValue = "0")  
  4.    int id) {  
  5.     User user = new User();  
  6.        user = userService.getUserById(id);  
  7.        return user;  
  8.    }  
  9.      
  10.    @RequestMapping(value="/user/{id:\\d+}",method = RequestMethod.GET)  
  11.    public @ResponseBody  
  12.    User printUser2(@PathVariable int id) {  
  13.        User user = new User();  
  14.        user = userService.getUserById(id);  
  15.        return user;  
  16.    }  



 

 

上面两个方法,访问路径分别如下:

 


猜你喜欢

转载自xinjiatao.iteye.com/blog/2356276