在spring MVC中,兩者的作用都是將request里的參數(shù)的值綁定到contorl里的方法參數(shù)里的,區(qū)別在于,URL寫法不同。
使用@RequestParam時(shí),URL是這樣的:http://host:port/path?參數(shù)名=參數(shù)值
使用@PathVariable時(shí),URL是這樣的:http://host:port/path/參數(shù)值
例如:
- @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}",method = RequestMethod.GET)
- public @ResponseBody
- User printUser2(@PathVariable int id) {
- User user = new User();
- user = userService.getUserById(id);
- return user;
- }
上面兩個(gè)方法,訪問路徑分別如下: