1. 程式人生 > >(轉)@RequestParam @RequestBody @PathVariable 等參數綁定註解詳解

(轉)@RequestParam @RequestBody @PathVariable 等參數綁定註解詳解

erro 後綁定 false zip ons type() eba veh manager

引言:

接上一篇文章,對@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註解綁定它傳過來的值到方法的參數上。

示例代碼:

[java] view plaincopyprint?技術分享技術分享
  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. }
[java] view plain copy print?
  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部分:

[plain] view plaincopyprint?技術分享技術分享
  1. Host localhost:8080
  2. Accept text/html,application/xhtml+xml,application/xml;q=0.9
  3. Accept-Language fr,en-gb;q=0.7,en;q=0.3
  4. Accept-Encoding gzip,deflate
  5. Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
  6. Keep-Alive 300
[plain] view plain copy print?
  1. Host localhost:8080
  2. Accept text/html,application/xhtml+xml,application/xml;q=0.9
  3. Accept-Language fr,en-gb;q=0.7,en;q=0.3
  4. Accept-Encoding gzip,deflate
  5. Accept-Charset ISO-8859-1,utf-8;q=0.7,*;q=0.7
  6. Keep-Alive 300

[java] view plaincopyprint?技術分享技術分享
  1. @RequestMapping("/displayHeaderInfo.do")
  2. public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
  3. @RequestHeader("Keep-Alive")long keepAlive) {
  4. //...
  5. }
[java] view plain copy print?
  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值:

[java] view plaincopyprint?技術分享技術分享
  1. JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84
[java] view plain copy print?
  1. JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84

參數綁定的代碼:

[java] view plaincopyprint?技術分享技術分享
  1. @RequestMapping("/displayHeaderInfo.do")
  2. public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
  3. //...
  4. }
[java] view plain copy print?
  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用來指示參數是否必須綁定;

示例代碼:

[java] view plaincopyprint?技術分享技術分享
  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. // ...
[java] view plain copy print?
  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;

示例代碼:

[java] view plaincopyprint?技術分享技術分享
  1. @RequestMapping(value ="/something", method = RequestMethod.PUT)
  2. public void handle(@RequestBody String body, Writer writer)throws IOException {
  3. writer.write(body);
  4. }
[java] view plain copy print?
  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 對象;

示例代碼:

[java] view plaincopyprint?技術分享技術分享
  1. @Controller
  2. @RequestMapping("/editPet.do")
  3. @SessionAttributes("pet")
  4. public class EditPetForm {
  5. // ...
  6. }
[java] view plain copy print?
  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的示例代碼:

[java] view plaincopyprint?技術分享技術分享
  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. }
[java] view plain copy print?
  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示例代碼:

[java] view plaincopyprint?技術分享技術分享
  1. @RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
  2. public String processSubmit(@ModelAttribute Pet pet) {
  3. }
[java] view plain copy print?
  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中綁定參數的部分源代碼:

[java] view plaincopyprint?技術分享技術分享
  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. thrownew 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. elseif (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. elseif (Errors.class.isAssignableFrom(paramType)) {
  95. throw new IllegalStateException("Errors/BindingResult argument declared " +
  96. "without preceding model attribute. Check your handler method signature!");
  97. }
  98. elseif (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. }
[java] view plain copy print?
  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中使用的參數綁定,代碼稍微有些不同,有興趣的同仁可以分析下,最後處理的結果都是一樣的。

示例:

[java] view plaincopyprint?技術分享技術分享
  1. @RequestMapping ({"/","/home"})
  2. public String showHomePage(String key){
  3. logger.debug("key="+key);
  4. return "home";
  5. }
[java] view plain copy print?
  1. @RequestMapping ({"/", "/home"})
  2. public String showHomePage(String key){
  3. logger.debug("key="+key);
  4. return "home";
  5. }

這種情況下,就調用默認的@RequestParam來處理。

[java] view plaincopyprint?技術分享技術分享
  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. }
[java] view plain copy print?
  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來處理。

(轉)@RequestParam @RequestBody @PathVariable 等參數綁定註解詳解