@RequestParam與@PathVariable的區別

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

 

 

上面兩個方法,訪問路徑分別如下:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章