天天看點

關于spring mvc Controller的幾個注解

如果方法參數類型不是string,就要進行自動類型轉換.詳細參考method parameters and type conversion.

@requestparam:綁定請求參數到方法參數.required預設是true.

@requestbody:綁定http請求體到方法參數.通過httpmessageconverter将請求體轉換到方法參數.httpmessageconverter負責将http請求消息轉換成一個對象和将一個對象轉換為響應體.requestmappinghandleradapter預設使用以下httpmessageconverters來支援@requestbody注解:

bytearrayhttpmessageconverter轉換byte數組.

stringhttpmessageconverter轉換字元串.

formhttpmessageconverter轉換表單資料成(或來自于)multivaluemap<string, string>

sourcehttpmessageconverter轉換成(或來自于)javax.xml.transform.source

對于更詳細就要參考message converters了

@responsebody:與@requestbody類似.這個注解放在一個方法上,表明傳回類型應該直接寫入到http響應體(而不是放入model或解析為視圖名字)

@cookievalue:綁定http cookie到方法參數.

@requestheader:綁定請求頭到方法參數.

@modelattribute有兩種使用場景.

1.放在方法的參數.@modelattribute映射一個model屬性到具體的方法參數.這就是controller如何獲得一個引用到這個對象來hold住表單輸入的資料.此參數可以聲明為表單傳回對象的具體類型而不是java.lang.object泛型,進而增強類型安全.

2.放在方法級别上.提供為model引用資料.這種用法簽名能包含@requestmapping标注的同樣的類型.

@modelattribute标注的方法能在@requestmapping标注的方法之前執行.這樣有效在預放具有特定屬性的隐式model,往往從資料庫加載.

@sessionattributes:将特定屬性存入session.