SpringBoot處理url中的參數的註解,springbooturl
1.介紹幾種如何處理url中的參數的註解
@PathVaribale 擷取url中的資料
@RequestParam 擷取請求參數的值
@GetMapping 組合註解,是 @RequestMapping(method = RequestMethod.GET) 的縮寫
(1)PathVaribale 擷取url中的資料
看一個例子,如果我們需要擷取Url=localhost:8080/hello/id中的id值,實現代碼如下:
1 @RestController2 public class HelloController {3 @RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET)4 public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){5 return "id:"+id+" name:"+name;6 }7 }
在瀏覽器中 輸入地址: localhost:8080/hello/100/helloworld 然後會在html頁面上列印出:
id:81
同樣,如果我們需要在url有多個參數需要擷取,則如下代碼所示來做就可以了。
1 @RestController2 public class HelloController {3 @RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET)4 public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){5 return "id:"+id+" name:"+name;6 }7 }
在瀏覽器中輸入地址: localhost:8080/hello/100/helloworld 然後會在html頁面上列印出:
id:100 name:helloworld
以上,通過 @PathVariable 註解來擷取URL中的參數時的前提條件是我們知道url的格式時怎麼樣的。
只有知道url的格式,我們才能在指定的方法上通過相同的格式擷取相應位置的參數值。
一般情況下,url的格式為: localhost:8080/hello?id=98 ,這種情況下該如何來擷取其id值呢,這就需要藉助於 @RequestParam 來完成了
2.@RequestParam 擷取請求參數的值
例如:
@RestControllerpublic class HelloController { @RequestMapping(value="/hello",method= RequestMethod.GET) public String sayHello(@RequestParam("id") Integer id){ return "id:"+id; }}
在瀏覽器中輸入地址: localhost:8080/hello?id=1000 ,可以看到如下的結果:
id:1000
當我們在瀏覽器中輸入地址: localhost:8080/hello?id ,即不輸入id的具體值,此時返回的結果為null。具體測試結果如下:
id:null
但是,當我們在瀏覽器中輸入地址: localhost:8080/hello ,即不輸入id參數,則會報如下錯誤:
whitelable Error Page錯誤
@RequestParam 註解給我們提供了這種解決方案,即允許使用者不輸入id時,使用預設值,具體代碼如下:
1 @RestController2 public class HelloController {3 @RequestMapping(value="/hello",method= RequestMethod.GET)4 //required=false 表示url中可以不穿入id參數,此時就使用預設參數5 public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){6 return "id:"+id;7 }8 }
如果在url中有多個參數,即類似於 localhost:8080/hello?id=98&&name=helloworld 這樣的url,同樣可以這樣來處理。具體代碼如下:
1 @RestController2 public class HelloController {3 @RequestMapping(value="/hello",method= RequestMethod.GET)4 public String sayHello(@RequestParam("id") Integer id,@RequestParam("name") String name){5 return "id:"+id+ " name:"+name;6 }7 }
在瀏覽器中的測試結果如下: localhost:8080/hello?id=1000&name=helloworld 地址,就會顯示下面的內容:
id:1000 name:helloworld
3.@GetMapping 組合註解
@GetMapping 是一個組合註解,是 @RequestMapping(method = RequestMethod.GET) 的縮寫。該註解將HTTP Get 映射到 特定的處理方法上。
即可以使用 @GetMapping(value = “/hello”) 來代替 @RequestMapping(value=”/hello”,method= RequestMethod.GET) 。即可以讓我們精簡代碼。
1 @RestController2 public class HelloController {3 //@RequestMapping(value="/hello",method= RequestMethod.GET)4 @GetMapping(value = "/hello")5 //required=false 表示url中可以不穿入id參數,此時就使用預設參數6 public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){7 return "id:"+id;8 }9 }
4.PostMapping組合註解:
方法同GetMapping
參考:http://blog.csdn.net/u010412719/article/details/69788227