本篇博文將介紹幾種如何處理url中的參數(shù)的注解@PathVaribale、@RequestParam、@GetMapping。
其中,各注解的作用為:
@PathVaribale 獲取url中的數(shù)據(jù)
@RequestParam獲取請(qǐng)求參數(shù)的值
@GetMapping 組合注解,是@RequestMapping(method = RequestMethod.GET)的縮寫
@PathVaribale 獲取url中的數(shù)據(jù)
看一個(gè)例子,如果我們需要獲取Url:localhost:8080/hello/id中的id值,實(shí)現(xiàn)代碼如下:
@RestController
public class HelloController {
@RequestMapping(value="/hello/{id}",method= RequestMethod.GET)
public String sayHello(@PathVariable("id") Integer id){
return "id:"+id;
}
}

同樣,如果我們需要在url有多個(gè)參數(shù)需要獲取,則如下代碼所示來做就可以了。
@RestController
public class HelloController {
@RequestMapping(value="/hello/{id}/{name}",method= RequestMethod.GET)
public String sayHello(@PathVariable("id") Integer id,@PathVariable("name") String name){
return "id:"+id+" name:"+name;
}
}

以上,通過@PathVariable注解來獲取URL中的參數(shù)時(shí)的前提條件是我們知道url的格式時(shí)怎么樣的。
只有知道url的格式,我們才能在指定的方法上通過相同的格式獲取相應(yīng)位置的參數(shù)值。
一般情況下,url的格式為:localhost:8080/hello?id=98,這種情況下該如何來獲取其id值呢,這就需要借助于@RequestParam來完成了
@RequestParam 獲取請(qǐng)求參數(shù)的值
直接看一個(gè)例子,如下
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(@RequestParam("id") Integer id){
return "id:"+id;
}
}
在瀏覽器中輸入地址:localhost:8080/hello?id=1000,可以看到如下的結(jié)果:

當(dāng)我們?cè)跒g覽器中輸入地址:localhost:8080/hello?id ,即不輸入id的具體值,此時(shí)返回的結(jié)果為null。具體測(cè)試結(jié)果如下:

但是,當(dāng)我們?cè)跒g覽器中輸入地址:localhost:8080/hello ,即不輸入id參數(shù),則會(huì)報(bào)如下錯(cuò)誤:

@RequestParam注解給我們提供了這種解決方案,即允許用戶不輸入id時(shí),使用默認(rèn)值,具體代碼如下:
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
//required=false 表示url中可以不傳入id參數(shù),此時(shí)就使用默認(rèn)參數(shù)
public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){
return "id:"+id;
}
}


如果在url中有多個(gè)參數(shù),即類似于localhost:8080/hello?id=98&&name=wojiushimogui這樣的url,同樣可以這樣來處理。具體代碼如下:
/**
* Created by wuranghao on 2017/4/7.
*/
@RestController
public class HelloController {
@RequestMapping(value="/hello",method= RequestMethod.GET)
public String sayHello(@RequestParam("id") Integer id,@RequestParam("name") String name){
return "id:"+id+ " name:"+name;
}
}
在瀏覽器中的測(cè)試結(jié)果如下:

@GetMapping 組合注解
@GetMapping是一個(gè)組合注解,是@RequestMapping(method = RequestMethod.GET)的縮寫。該注解將HTTP Get 映射到特定的處理方法上。
即可以使用@GetMapping(value = “/hello”)來代替@RequestMapping(value=”/hello”,method= RequestMethod.GET)。即可以讓我們精簡(jiǎn)代碼。
例子
@RestController
public class HelloController {
//@RequestMapping(value="/hello",method= RequestMethod.GET)
@GetMapping(value = "/hello")
//required=false 表示url中可以不傳入id參數(shù),此時(shí)就使用默認(rèn)參數(shù)
public String sayHello(@RequestParam(value="id",required = false,defaultValue = "1") Integer id){
return "id:"+id;
}
}
小結(jié)
本篇博文介紹了幾種常用獲取url中的參數(shù)哈,比較簡(jiǎn)單。