@RequestParam与@PathVariable的区别


转自:https://www.cnblogs.com/hq233/p/7146264.html

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.    }  

 

 

 

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

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM