SpringMVC參數綁定註解

来源:https://www.cnblogs.com/blogcpp/archive/2020/07/03/13232584.html
-Advertisement-
Play Games

轉載:https://blog.csdn.net/walkerJong/article/details/7946109 ...


引言:

接上一篇文章,對@RequestMapping進行地址映射講解之後,該篇主要講解request 數據到handler method 參數數據的綁定所用到的註解和什麼情形下使用;


簡介:

handler method 參數綁定常用的註解,我們根據他們處理的Request的不同內容部分分為四類:(主要講解常用類型)

A、處理requet uri 部分(這裡指uri template中variable,不含queryString部分)的註解:   @PathVariable;

B、處理request header部分的註解:   @RequestHeader, @CookieValue;

C、處理request body部分的註解:@RequestParam,  @RequestBody;

D、處理attribute類型是註解: @SessionAttributes, @ModelAttribute;

 

1、 @PathVariable 

當使用@RequestMapping URI template 樣式映射時, 即 someUrl/{paramId}, 這時的paramId可通過 @Pathvariable註解綁定它傳過來的值到方法的參數上。

示例代碼:

  1. @Controller
  2. @RequestMapping("/owners/{ownerId}")
  3. public class RelativePathUriTemplateController {
  4. @RequestMapping("/pets/{petId}")
  5. public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
  6. // implementation omitted
  7. }
  8. }
上面代碼把URI template 中變數 ownerId的值和petId的值,綁定到方法的參數上。若方法參數名稱和需要綁定的uri template中變數名稱不一致,需要在@PathVariable("name")指定uri template中的名稱。

2、 @RequestHeader、@CookieValue

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

示例代碼:

這是一個Request 的header部分:

Host                    localhost:8080
Accept                  text/html,application/xhtml+xml,application/xml;q=0.9
Accept-Language         fr,en-gb;q=0.7,en;q=0.3
Accept-Encoding         gzip,deflate
Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive              300

  1. @RequestMapping("/displayHeaderInfo.do")
  2. public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
  3. @RequestHeader("Keep-Alive") long keepAlive) {
  4. //...
  5. }
上面的代碼,把request header部分的 Accept-Encoding的值,綁定到參數encoding上了, Keep-Alive header的值綁定到參數keepAlive上。


@CookieValue 可以把Request header中關於cookie的值綁定到方法的參數上。

例如有如下Cookie值:

JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84
參數綁定的代碼:

  1. @RequestMapping("/displayHeaderInfo.do")
  2. public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
  3. //...
  4. }
即把JSESSIONID的值綁定到參數cookie上。


3、@RequestParam, @RequestBody

@RequestParam

A) 常用來處理簡單類型的綁定,通過Request.getParameter() 獲取的String可直接轉換為簡單類型的情況( String--> 簡單類型的轉換操作由ConversionService配置的轉換器來完成);因為使用request.getParameter()方式獲取參數,所以可以處理get 方式中queryString的值,也可以處理post方式中 body data的值;

B)用來處理Content-Type: 為 application/x-www-form-urlencoded編碼的內容,提交方式GET、POST;

C) 該註解有兩個屬性: value、required; value用來指定要傳入值的id名稱,required用來指示參數是否必須綁定;

示例代碼:

  1. @Controller
  2. @RequestMapping("/pets")
  3. @SessionAttributes("pet")
  4. public class EditPetForm {
  5. // ...
  6. @RequestMapping(method = RequestMethod.GET)
  7. public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
  8. Pet pet = this.clinic.loadPet(petId);
  9. model.addAttribute("pet", pet);
  10. return "petForm";
  11. }
  12. // ...


@RequestBody

該註解常用來處理Content-Type: 不是application/x-www-form-urlencoded編碼的內容,例如application/json, application/xml等;

它是通過使用HandlerAdapter 配置的HttpMessageConverters來解析post data body,然後綁定到相應的bean上的。

因為配置有FormHttpMessageConverter,所以也可以用來處理 application/x-www-form-urlencoded的內容,處理完的結果放在一個MultiValueMap<String, String>里,這種情況在某些特殊需求下使用,詳情查看FormHttpMessageConverter api;

示例代碼:

  1. @RequestMapping(value = "/something", method = RequestMethod.PUT)
  2. public void handle(@RequestBody String body, Writer writer) throws IOException {
  3. writer.write(body);
  4. }

4、@SessionAttributes, @ModelAttribute

@SessionAttributes:

該註解用來綁定HttpSession中的attribute對象的值,便於在方法中的參數里使用。

該註解有value、types兩個屬性,可以通過名字和類型指定要使用的attribute 對象;

示例代碼:

  1. @Controller
  2. @RequestMapping("/editPet.do")
  3. @SessionAttributes("pet")
  4. public class EditPetForm {
  5. // ...
  6. }


@ModelAttribute

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

用於方法上時:  通常用來在處理@RequestMapping之前,為請求綁定需要從後臺查詢的model;

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

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

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

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


用到方法上@ModelAttribute的示例代碼:

  1. // Add one attribute
  2. // The return value of the method is added to the model under the name "account"
  3. // You can customize the name via @ModelAttribute("myAccount")
  4. @ModelAttribute
  5. public Account addAccount(@RequestParam String number) {
  6. return accountManager.findAccount(number);
  7. }

這種方式實際的效果就是在調用@RequestMapping的方法之前,為request對象的model里put(“account”, Account);


用在參數上的@ModelAttribute示例代碼:

  1. @RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
  2. public String processSubmit(@ModelAttribute Pet pet) {
  3. }
首先查詢 @SessionAttributes有無綁定的Pet對象,若沒有則查詢@ModelAttribute方法層面上是否綁定了Pet對象,若沒有則將URI template中的值按對應的名稱綁定到Pet對象的各屬性上。

補充講解:

問題: 在不給定註解的情況下,參數是怎樣綁定的?

通過分析AnnotationMethodHandlerAdapter和RequestMappingHandlerAdapter的源代碼發現,方法的參數在不給定參數的情況下:

若要綁定的對象時簡單類型:  調用@RequestParam來處理的。 

若要綁定的對象時複雜類型:  調用@ModelAttribute來處理的。

這裡的簡單類型指java的原始類型(boolean, int 等)、原始類型對象(Boolean, Int等)、String、Date等ConversionService里可以直接String轉換成目標對象的類型;


下麵貼出AnnotationMethodHandlerAdapter中綁定參數的部分源代碼:

  1. private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,
  2. NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception {
  3. Class[] paramTypes = handlerMethod.getParameterTypes();
  4. Object[] args = new Object[paramTypes.length];
  5. for (int i = 0; i < args.length; i++) {
  6. MethodParameter methodParam = new MethodParameter(handlerMethod, i);
  7. methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer);
  8. GenericTypeResolver.resolveParameterType(methodParam, handler.getClass());
  9. String paramName = null;
  10. String headerName = null;
  11. boolean requestBodyFound = false;
  12. String cookieName = null;
  13. String pathVarName = null;
  14. String attrName = null;
  15. boolean required = false;
  16. String defaultValue = null;
  17. boolean validate = false;
  18. Object[] validationHints = null;
  19. int annotationsFound = 0;
  20. Annotation[] paramAnns = methodParam.getParameterAnnotations();
  21. for (Annotation paramAnn : paramAnns) {
  22. if (RequestParam.class.isInstance(paramAnn)) {
  23. RequestParam requestParam = (RequestParam) paramAnn;
  24. paramName = requestParam.value();
  25. required = requestParam.required();
  26. defaultValue = parseDefaultValueAttribute(requestParam.defaultValue());
  27. annotationsFound++;
  28. }
  29. else if (RequestHeader.class.isInstance(paramAnn)) {
  30. RequestHeader requestHeader = (RequestHeader) paramAnn;
  31. headerName = requestHeader.value();
  32. required = requestHeader.required();
  33. defaultValue = parseDefaultValueAttribute(requestHeader.defaultValue());
  34. annotationsFound++;
  35. }
  36. else if (RequestBody.class.isInstance(paramAnn)) {
  37. requestBodyFound = true;
  38. annotationsFound++;
  39. }
  40. else if (CookieValue.class.isInstance(paramAnn)) {
  41. CookieValue cookieValue = (CookieValue) paramAnn;
  42. cookieName = cookieValue.value();
  43. required = cookieValue.required();
  44. defaultValue = parseDefaultValueAttribute(cookieValue.defaultValue());
  45. annotationsFound++;
  46. }
  47. else if (PathVariable.class.isInstance(paramAnn)) {
  48. PathVariable pathVar = (PathVariable) paramAnn;
  49. pathVarName = pathVar.value();
  50. annotationsFound++;
  51. }
  52. else if (ModelAttribute.class.isInstance(paramAnn)) {
  53. ModelAttribute attr = (ModelAttribute) paramAnn;
  54. attrName = attr.value();
  55. annotationsFound++;
  56. }
  57. else if (Value.class.isInstance(paramAnn)) {
  58. defaultValue = ((Value) paramAnn).value();
  59. }
  60. else if (paramAnn.annotationType().getSimpleName().startsWith("Valid")) {
  61. validate = true;
  62. Object value = AnnotationUtils.getValue(paramAnn);
  63. validationHints = (value instanceof Object[] ? (Object[]) value : new Object[] {value});
  64. }
  65. }
  66. if (annotationsFound > 1) {
  67. throw new IllegalStateException("Handler parameter annotations are exclusive choices - " +
  68. "do not specify more than one such annotation on the same parameter: " + handlerMethod);
  69. }
  70. if (annotationsFound == 0) {// 若沒有發現註解
  71. Object argValue = resolveCommonArgument(methodParam, webRequest); //判斷WebRquest是否可賦值給參數
  72. if (argValue != WebArgumentResolver.UNRESOLVED) {
  73. args[i] = argValue;
  74. }
  75. else if (defaultValue != null) {
  76. args[i] = resolveDefaultValue(defaultValue);
  77. }
  78. else {
  79. Class<?> paramType = methodParam.getParameterType();
  80. if (Model.class.isAssignableFrom(paramType) || Map.class.isAssignableFrom(paramType)) {
  81. if (!paramType.isAssignableFrom(implicitModel.getClass())) {
  82. throw new IllegalStateException("Argument [" + paramType.getSimpleName() + "] is of type " +
  83. "Model or Map but is not assignable from the actual model. You may need to switch " +
  84. "newer MVC infrastructure classes to use this argument.");
  85. }
  86. args[i] = implicitModel;
  87. }
  88. else if (SessionStatus.class.isAssignableFrom(paramType)) {
  89. args[i] = this.sessionStatus;
  90. }
  91. else if (HttpEntity.class.isAssignableFrom(paramType)) {
  92. args[i] = resolveHttpEntityRequest(methodParam, webRequest);
  93. }
  94. else if (Errors.class.isAssignableFrom(paramType)) {
  95. throw new IllegalStateException("Errors/BindingResult argument declared " +
  96. "without preceding model attribute. Check your handler method signature!");
  97. }
  98. else if (BeanUtils.isSimpleProperty(paramType)) {// 判斷是否參數類型是否是簡單類型,若是在使用@RequestParam方式來處理,否則使用@ModelAttribute方式處理
  99. paramName = "";
  100. }
  101. else {
  102. attrName = "";
  103. }
  104. }
  105. }
  106. if (paramName != null) {
  107. args[i] = resolveRequestParam(paramName, required, defaultValue, methodParam, webRequest, handler);
  108. }
  109. else if (headerName != null) {
  110. args[i] = resolveRequestHeader(headerName, required, defaultValue, methodParam, webRequest, handler);
  111. }
  112. else if (requestBodyFound) {
  113. args[i] = resolveRequestBody(methodParam, webRequest, handler);
  114. }
  115. else if (cookieName != null) {
  116. args[i] = resolveCookieValue(cookieName, required, defaultValue, methodParam, webRequest, handler);
  117. }
  118. else if (pathVarName != null) {
  119. args[i] = resolvePathVariable(pathVarName, methodParam, webRequest, handler);
  120. }
  121. else if (attrName != null) {
  122. WebDataBinder binder =
  123. resolveModelAttribute(attrName, methodParam, implicitModel, webRequest, handler);
  124. boolean assignBindingResult = (args.length > i + 1 && Errors.class.isAssignableFrom(paramTypes[i + 1]));
  125. if (binder.getTarget() != null) {
  126. doBind(binder, webRequest, validate, validationHints, !assignBindingResult);
  127. }
  128. args[i] = binder.getTarget();
  129. if (assignBindingResult) {
  130. args[i + 1] = binder.getBindingResult();
  131. i++;
  132. }
  133. implicitModel.putAll(binder.getBindingResult().getModel());
  134. }
  135. }
  136. return args;
  137. }

RequestMappingHandlerAdapter中使用的參數綁定,代碼稍微有些不同,有興趣的同仁可以分析下,最後處理的結果都是一樣的。


示例:

  1. @RequestMapping ({"/", "/home"})
  2. public String showHomePage(String key){
  3. logger.debug("key="+key);
  4. return "home";
  5. }
這種情況下,就調用預設的@RequestParam來處理。


  1. @RequestMapping (method = RequestMethod.POST)
  2. public String doRegister(User user){
  3. if(logger.isDebugEnabled()){
  4. logger.debug("process url[/user], method[post] in "+getClass());
  5. logger.debug(user);
  6. }
  7. return "user";
  8. }

這種情況下,就調用@ModelAttribute來處理。


參考文檔:

1、 Spring Web Doc:

spring-3.1.0/docs/spring-framework-reference/html/mvc.html


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 異常處理 把可能會發生的錯誤,提前在代碼里進行捕捉(監測) try : code except Exception: 出錯後要執行的代碼 下麵是常見的異常: attributeError 試圖訪問一個對象沒有的屬性 Nameerror 訪問一個沒有變數 Valueerror 值類型不匹配 impor ...
  • 學習時常常忘記某個容器怎麼用。別怕,只要用時會查。太多也記不過來。 微軟的c++文檔:https://docs.microsoft.com/zh-cn/cpp/standard-library/vector-class?view=vs-2019 又發現一個網上查文檔的網站了,感覺還不錯。鏈接:htt ...
  • volatile 這個關鍵字可能很多朋友都聽說過,或許也都用過。在 Java 5 之前,它是一個備受爭議的關鍵字,因為在程式中使用它往往會導致出人意料的結果。在 Java 5之後,volatile 關鍵字才得以重獲生機。 ...
  • <form action="/search" id="search_form"> <input type="text" name="keywords" value="" placeholder="Furniture Handles" class="jhser" /> <span class="ser ...
  • Java生鮮電商平臺-微服務電商優惠券的架構設計(小程式/APP) 說明:Java生鮮電商平臺的優惠券屬於電子優惠券,不過我們要先看看線下紙質優惠券: 商家決定做促銷,印製了10000張50元代金券; 其中1000張代金券分別發給1000個用戶; 到某一個時刻,這1000個用戶有300個適用了代金券 ...
  • 一、Java基礎知識 二、軟體 1. 軟體是什麼? 軟體=數據+指令[命令]+文檔 2. 軟體開髮指什麼? 軟體開發是根據用戶的需求創建出相應的軟體系統. 軟體開發是一個過程,包含需求的提取,需求分析,軟體的編寫,軟體測試. 三、人與電腦做交互 圖形化界面 vs 命令行方式 dir md rd c ...
  • 前言 剛回到家,又被公司群里的消息轟炸了。讓統計每個人最近是否去過石景山萬達廣場。 這基本上已經是每日必備了,只要有任何風吹草動,就需要我們填各種信息。 我們都知道,北京最近的疫情很不樂觀,從每天的數據就能看出來了。 也許很多小伙伴不在北京,是切實感受不到的。 就拿我自己舉例吧,在去公司的每一天,我 ...
  • 這篇博客還是整理從https://github.com/LyricTian/gin-admin 這個項目中學習的golang相關知識 作者在項目中使用了https://github.com/google/wire 做依賴註入,這個庫我之前沒有使用過,看了作者代碼中的使用,至少剛開始是看著優點懵,不知 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 插件化的需求主要源於對軟體架構靈活性的追求,特別是在開發大型、複雜或需要不斷更新的軟體系統時,插件化可以提高軟體系統的可擴展性、可定製性、隔離性、安全性、可維護性、模塊化、易於升級和更新以及支持第三方開發等方面的能力,從而滿足不斷變化的業務需求和技術挑戰。 一、插件化探索 在WPF中我們想要開 ...
  • 歡迎ReaLTaiizor是一個用戶友好的、以設計為中心的.NET WinForms項目控制項庫,包含廣泛的組件。您可以使用不同的主題選項對項目進行個性化設置,並自定義用戶控制項,以使您的應用程式更加專業。 項目地址:https://github.com/Taiizor/ReaLTaiizor 步驟1: ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • Channel 是乾什麼的 The System.Threading.Channels namespace provides a set of synchronization data structures for passing data between producers and consume ...
  • efcore如何優雅的實現按年分庫按月分表 介紹 本文ShardinfCore版本 本期主角: ShardingCore 一款ef-core下高性能、輕量級針對分表分庫讀寫分離的解決方案,具有零依賴、零學習成本、零業務代碼入侵適配 距離上次發文.net相關的已經有很久了,期間一直在從事java相關的 ...
  • 前言 Spacesniffer 是一個免費的文件掃描工具,通過使用樹狀圖可視化佈局,可以立即瞭解大文件夾的位置,幫助用戶處理找到這些文件夾 當前系統C盤空間 清理後系統C盤空間 下載 Spacesniffer 下載地址:https://spacesniffer.en.softonic.com/dow ...
  • EDP是一套集組織架構,許可權框架【功能許可權,操作許可權,數據訪問許可權,WebApi許可權】,自動化日誌,動態Interface,WebApi管理等基礎功能於一體的,基於.net的企業應用開發框架。通過友好的編碼方式實現數據行、列許可權的管控。 ...
  • 一、ReZero簡介 ReZero是一款.NET中間件 : 全網唯一開源界面操作就能生成API , 可以集成到任何.NET6+ API項目,無破壞性,也可讓非.NET用戶使用exe文件 免費開源:MIT最寬鬆協議 , 一直從事開源事業十年,一直堅持開源 1.1 純ReZero開發 適合.Net Co ...
  • 一:背景 1. 講故事 停了一個月沒有更新文章了,主要是忙於寫 C#內功修煉系列的PPT,現在基本上接近尾聲,可以回頭繼續更新這段時間分析dump的一些事故報告,有朋友微信上找到我,說他們的系統出現了大量的http超時,程式不響應處理了,讓我幫忙看下怎麼回事,dump也抓到了。 二:WinDbg分析 ...
  • 開始做項目管理了(本人3年java,來到這邊之後真沒想到...),天天開會溝通整理需求,他們講話的時候忙裡偷閑整理一下常用的方法,其實語言還是有共通性的,基本上看到方法名就大概能猜出來用法。出去打水的時候看到外面太陽好好,真想在外面坐著曬太陽,回來的時候好兄弟三年前送給我的鍵盤D鍵不靈了,在打"等待 ...