国产一级a片免费看高清,亚洲熟女中文字幕在线视频,黄三级高清在线播放,免费黄色视频在线看

打開APP
userphoto
未登錄

開通VIP,暢享免費(fèi)電子書等14項(xiàng)超值服

開通VIP
@RequestParam @RequestBody @PathVariable 等參數(shù)綁...

引言:

接上一篇文章,對(duì)@RequestMapping進(jìn)行地址映射講解之后,該篇主要講解request 數(shù)據(jù)到handler method 參數(shù)數(shù)據(jù)的綁定所用到的注解和什么情形下使用;


簡(jiǎn)介:

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

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

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

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

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

 

1、 @PathVariable 

當(dāng)使用@RequestMapping URI template 樣式映射時(shí), 即 someUrl/{paramId}, 這時(shí)的paramId可通過 @Pathvariable注解綁定它傳過來(lái)的值到方法的參數(shù)上。

示例代碼:

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

2、 @RequestHeader、@CookieValue

@RequestHeader 注解,可以把Request請(qǐng)求header部分的值綁定到方法的參數(shù)上。

示例代碼:

這是一個(gè)Request 的header部分:

  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  

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


@CookieValue 可以把Request header中關(guān)于cookie的值綁定到方法的參數(shù)上。

例如有如下Cookie值:

  1. JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84  
參數(shù)綁定的代碼:

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


3、@RequestParam, @RequestBody

@RequestParam

A) 常用來(lái)處理簡(jiǎn)單類型的綁定,通過Request.getParameter() 獲取的String可直接轉(zhuǎn)換為簡(jiǎn)單類型的情況( String--> 簡(jiǎn)單類型的轉(zhuǎn)換操作由ConversionService配置的轉(zhuǎn)換器來(lái)完成);因?yàn)槭褂胷equest.getParameter()方式獲取參數(shù),所以可以處理get 方式中queryString的值,也可以處理post方式中 body data的值;

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

C) 該注解有兩個(gè)屬性: value、required; value用來(lái)指定要傳入值的id名稱,required用來(lái)指示參數(shù)是否必須綁定;

示例代碼:

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


@RequestBody

該注解常用來(lái)處理Content-Type: 不是application/x-www-form-urlencoded編碼的內(nèi)容,例如application/json, application/xml等;

它是通過使用HandlerAdapter 配置的HttpMessageConverters來(lái)解析post data body,然后綁定到相應(yīng)的bean上的。

因?yàn)榕渲糜蠪ormHttpMessageConverter,所以也可以用來(lái)處理 application/x-www-form-urlencoded的內(nèi)容,處理完的結(jié)果放在一個(gè)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:

該注解用來(lái)綁定HttpSession中的attribute對(duì)象的值,便于在方法中的參數(shù)里使用。

該注解有value、types兩個(gè)屬性,可以通過名字和類型指定要使用的attribute 對(duì)象;

示例代碼:

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


@ModelAttribute

該注解有兩個(gè)用法,一個(gè)是用于方法上,一個(gè)是用于參數(shù)上;

用于方法上時(shí):  通常用來(lái)在處理@RequestMapping之前,為請(qǐng)求綁定需要從后臺(tái)查詢的model;

用于參數(shù)上時(shí): 用來(lái)通過名稱對(duì)應(yīng),把相應(yīng)名稱的值綁定到注解的參數(shù)bean上;要綁定的值來(lái)源于:

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

B) @ModelAttribute 用于方法上時(shí)指定的model對(duì)象;

C) 上述兩種情況都沒有時(shí),new一個(gè)需要綁定的bean對(duì)象,然后把request中按名稱對(duì)應(yīng)的方式把值綁定到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.   
  5. @ModelAttribute  
  6. public Account addAccount(@RequestParam String number) {  
  7.     return accountManager.findAccount(number);  
  8. }  

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


用在參數(shù)上的@ModelAttribute示例代碼:

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

補(bǔ)充講解:

問題: 在不給定注解的情況下,參數(shù)是怎樣綁定的?

通過分析AnnotationMethodHandlerAdapter和RequestMappingHandlerAdapter的源代碼發(fā)現(xiàn),方法的參數(shù)在不給定參數(shù)的情況下:

若要綁定的對(duì)象時(shí)簡(jiǎn)單類型:  調(diào)用@RequestParam來(lái)處理的。 

若要綁定的對(duì)象時(shí)復(fù)雜類型:  調(diào)用@ModelAttribute來(lái)處理的。

這里的簡(jiǎn)單類型指java的原始類型(boolean, int 等)、原始類型對(duì)象(Boolean, Int等)、String、Date等ConversionService里可以直接String轉(zhuǎn)換成目標(biāo)對(duì)象的類型;


下面貼出AnnotationMethodHandlerAdapter中綁定參數(shù)的部分源代碼:

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

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


示例:

  1. @RequestMapping ({"/""/home"})  
  2.     public String showHomePage(String key){  
  3.           
  4.         logger.debug("key="+key);  
  5.           
  6.         return "home";  
  7.     }  
這種情況下,就調(diào)用默認(rèn)的@RequestParam來(lái)處理。


  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.   
  8.     return "user";  
  9. }  

這種情況下,就調(diào)用@ModelAttribute來(lái)處理。


參考文檔:

1、 Spring Web Doc:

spring-3.1.0/docs/spring-framework-reference/html/mvc.html
本站僅提供存儲(chǔ)服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊舉報(bào)。
打開APP,閱讀全文并永久保存 查看更多類似文章
猜你喜歡
類似文章
Spring MVC常用注解整理
springmvc請(qǐng)求參數(shù)獲取的幾種方法
Spring MVC 接收請(qǐng)求參數(shù)所有方式總結(jié)!
springmvc常用注解標(biāo)簽詳解
SpringMVC 基礎(chǔ)知識(shí)點(diǎn)小結(jié)
SpringMVC Controller介紹
更多類似文章 >>
生活服務(wù)
分享 收藏 導(dǎo)長(zhǎng)圖 關(guān)注 下載文章
綁定賬號(hào)成功
后續(xù)可登錄賬號(hào)暢享VIP特權(quán)!
如果VIP功能使用有故障,
可點(diǎn)擊這里聯(lián)系客服!

聯(lián)系客服