Spring Boot參數綁定註解詳解及其使用場景

在使用Spring Boot做接口開發的過程當中發現接受參數的註解,有時不能準確理解其含義,故抽空總結一下以備未來參閱。json

首先將經常使用的handler method註解經過他們處理Request的不一樣內容部分,分類以下:cookie

1. 處理request uri部分(這裏指uri template中variable,不含queryString部分)的註解: @PathVariable;

2. 處理request header部分的註解:@RequestHeader,@CookieValue;

3. 處理request body部分的註解:@RequestParam, @RequestBody;

4. 處理attribute類型是註解:@SessionAttributes, @ModelAttribute;

下面是幾個註解的說明:session

1. @RequestParam

  • 經常使用來處理簡單類型的綁定,經過Request.getParameter()獲取的String可直接轉換爲簡單類型的狀況;由於使用request.getParameter()方式獲取參數,因此能夠處理get和post方式中queryString的值,也能夠處理post方式中post方式中body data的值,此時的請求類型爲application/x-www-form-urlencoded,若是類型爲application/json,只能用@RequestBody處理;app

  • 該註解有兩個屬性:value、required;value用來指定要傳入值的id名稱,required不寫默認是true;框架

@RequestMapping("/login")
public String login(@RequestParam(value="username") String username, @RequestParam(value="password") String password){

	return username+password;
}

2. @RequestBody

  • 該註解經常使用來處理Content-Type:通常是application/json,application/xml;經過使用HandlerAdapter配置的HttpMessageConverters來解析post data body,而後綁定到相應的bean上的。支持post、put方式。
@RequestMapping(value="/something", method=RequestMethod.PUT)
public void handle(@RequestBody String body){
	System.out.println(body);
}

3. @PathVariable

  • 經過@PathVariable能夠將URL中佔位符參數綁定到控制器處理方法的入參中:URL中的{xxx}佔位符能夠經過@PathVariable("xxx")綁定到操做方法的入參中。促使SpringMVC支持Rest風格。
@RequestMapping("/get/{id}")
public void getSomethingById(@PathVariable String id) {
	// implementation omitted
}

4. @RequestHeader,@CookieValue;

(1) @RequestHeader

@RequestHeader註解,能夠把Request請求header部分的值綁定到方法的參數上。jsp

@RequestMapping("/setHeader")
public void setHeaderInfo(@RequestHeader("Accept-Encoding") String encoding, @RequestHeader("Keep-Alive") long keepAlive) {

}
  • 上述代碼將request header部分的Accept-Encoding的值,綁定到參數encoding上了,Keep-Alive header的值綁定到參數keepAlive上。

爲了固定參數統一處理,固然也支持在header中傳入參數,如token信息,此時的寫法以下:post

@RequestMapping("/setHeader")
public void setHeaderInfo(@RequestHeader String token) {
	//...
}

(2)@CookieValue

@CookieValue能夠把Request header中關於Cookie的值綁定到方法的參數上。ui

@RequestMapping("/setHeader")
public void setHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
	// ...
}

上述代碼將JSESSIONID的值綁定到參數cookie上。url

5. @SessionAttributes, @ModelAttribute

(1)SessionAttributes

該註解用來綁定HttpSession中的attribute對象的值,便於在方法中的參數裏使用。默認狀況下SpringMVC將模型中的數據存儲到request域中。當一個請求結束後,數據就失效了。若是要誇頁面使用,那麼須要使用到session。而@SessionAttribute註解就可使得模型中的數據存儲一份到session域中。.net

@Controller
@RequestMapping("/editPet.do")
@SessionAttributes("attr1","attr2")
public class TestSessionAttributes {

	@RequestMapping(values="/index1")
	public ModelAndView index(){
		ModelAndView mav = new ModelAndView("index.jsp");
		mav.addObject("attr1","attr1Value");
		mav.addObject("attr2","attr2Value");
		return mav;
	}
	
	
	@RequestMapping(values="/index2")
	public ModelAndView index2(@ModelAttribute("attr1") String attr1, @ModelAttribute("attr2") String attr2) {
		ModelAndView mav = new ModelAndView("success.jsp");
		return mav;
	}
}

index方法返回一個ModelAndView其中包括視圖index.jsp和兩個鍵值放在model中,在沒有加入@SessionAttributes註解的時候,放入model當中的鍵值是request級別的。

如今由於在Controller上面標記了@SessionAttributes(value={"attr1", "attr2"})那麼model中的attr1, attr2會同步到session中,這樣訪問index而後再去訪問index2的時候也會獲取這兩個屬性的值。

當須要清除session中的值的時候,咱們只須要在controller的方法中傳入一個SessionStatus的類型對象,經過調用setComplete方法就能夠清除了。

@RequestMapping(params="method=index3")
public ModelAndView index4(SessionStatus status) {
	ModelAndView mav = new ModelAndView("success.jsp");
	status.setComplete();
	return mav;
}

另外,@SessionAttribute註解只能在類上使用,不能在方法上使用。

(2)ModelAttribute

該註解有兩個用法,一個是用於方法上,一個是用於參數上;

用於方法上時:一般用來在處理@RequestMapping以前,爲請求綁定須要從後臺查詢的model;

用於參數上時:用來經過名稱對應,把相應名稱的值綁定到註解的參數bean上;

要綁定的值來源於:

A) @SessionAttributes啓用的attribute對象上;

B) @ModelAttribute用於方法上時指定的model對象;

C) 上述兩種狀況都沒有時,new一個須要綁定的bean對象,而後把request中按名稱對應的方式把值綁定到bean中。

  • @ModelAttribute用在參數上:
@RequestMapping("/hello")
public ModelAndView hello(@ModelAttribute Account account) {
	acount.setAge(12);
	account.setName("456");
	return new ModelAndView("hello");
}

註解在方法參數上的@ModelAttribute說明了該方法的值將由model中取得。若是model中找不到,那麼該參數會先被實例化,而後被添加到model中。在model中存在之後,請求中全部名稱匹配的參數都會填充到該參數中。這在Spring MVC中被稱爲數據綁定,一個很是有用的特性,節約了每次都須要手動從表格數據中轉換這些字段數據的時間。

  • @ModelAttribute用在方法上:

方法經過返回值的方式默認地將添加一個屬性。屬性名沒有被顯式指定的時候,框架將根據屬性的類型給予一個默認名稱。例如:本例返回一個Account類型的對象,則默認的屬性名爲"account",你能夠經過設置@ModelAttribute註解的值來改變默認值。

@ModelAttribute
public Account addAccount(@RequestParam(value = "name", defaultValue = "test") String name) {
	Account ac = new Account();
	ac.setName(name);
	ac.setAge(12);
	return ac;
}

參考文章:

https://blog.csdn.net/ztchun/article/details/84073120

相關文章
相關標籤/搜索