【轉】springmvc請求綁定註解詳解

html

@RequestMappingjava

RequestMapping是一個用來處理請求地址映射的註解,可用於類或方法上。用於類上,表示類中的全部響應請求的方法都是以該地址做爲父路徑。web

RequestMapping註解有六個屬性,下面咱們把她分紅三類進行說明。正則表達式

一、 value, method;

value:     指定請求的實際地址,指定的地址能夠是URI Template 模式(後面將會說明);json

method:  指定請求的method類型, GET、POST、PUT、DELETE等;api

二、 consumes,produces;

consumes: 指定處理請求的提交內容類型(Content-Type),例如application/json, text/html;cookie

produces:    指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回;session

三、 params,headers;

params: 指定request中必須包含某些參數值是,才讓該方法處理。app

headers: 指定request中必須包含某些指定的header值,才能讓該方法處理請求。post

注:

value的uri值爲如下三類:

A) 能夠指定爲普通的具體值;

B)  能夠指定爲含有某變量的一類值(URI Template Patterns with Path Variables);

C) 能夠指定爲含正則表達式的一類值( URI Template Patterns with Regular Expressions);

 

二 

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;

一、 @PathVariable 

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

二、 @RequestHeader、@CookieValue

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

三、@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用來指示參數是否必須綁定;

@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;

四、@SessionAttributes, @ModelAttribute

@SessionAttributes:

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

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

@ModelAttribute

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

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

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

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

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

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

在不給定註解的狀況下,參數是怎樣綁定的?

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

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

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

這裏的簡單類型指Java的原始類型(boolean, int 等)、原始類型對象(Boolean, Int等)、String、Date等ConversionService裏能夠直接String轉換成目標對象的類型;

 

hanler的處理代碼邏輯以下

 

private Object[] resolveHandlerArguments(Method handlerMethod, Object handler,  
            NativeWebRequest webRequest, ExtendedModelMap implicitModel) throws Exception {  
  
        Class[] paramTypes = handlerMethod.getParameterTypes();  
        Object[] args = new Object[paramTypes.length];  
  
        for (int i = 0; i < args.length; i++) {  
            MethodParameter methodParam = new MethodParameter(handlerMethod, i);  
            methodParam.initParameterNameDiscovery(this.parameterNameDiscoverer);  
            GenericTypeResolver.resolveParameterType(methodParam, handler.getClass());  
            String paramName = null;  
            String headerName = null;  
            boolean requestBodyFound = false;  
            String cookieName = null;  
            String pathVarName = null;  
            String attrName = null;  
            boolean required = false;  
            String defaultValue = null;  
            boolean validate = false;  
            Object[] validationHints = null;  
            int annotationsFound = 0;  
            Annotation[] paramAnns = methodParam.getParameterAnnotations();  
  
            for (Annotation paramAnn : paramAnns) {  
                if (RequestParam.class.isInstance(paramAnn)) {  
                    RequestParam requestParam = (RequestParam) paramAnn;  
                    paramName = requestParam.value();  
                    required = requestParam.required();  
                    defaultValue = parseDefaultValueAttribute(requestParam.defaultValue());  
                    annotationsFound++;  
                }  
                else if (RequestHeader.class.isInstance(paramAnn)) {  
                    RequestHeader requestHeader = (RequestHeader) paramAnn;  
                    headerName = requestHeader.value();  
                    required = requestHeader.required();  
                    defaultValue = parseDefaultValueAttribute(requestHeader.defaultValue());  
                    annotationsFound++;  
                }  
                else if (RequestBody.class.isInstance(paramAnn)) {  
                    requestBodyFound = true;  
                    annotationsFound++;  
                }  
                else if (CookieValue.class.isInstance(paramAnn)) {  
                    CookieValue cookieValue = (CookieValue) paramAnn;  
                    cookieName = cookieValue.value();  
                    required = cookieValue.required();  
                    defaultValue = parseDefaultValueAttribute(cookieValue.defaultValue());  
                    annotationsFound++;  
                }  
                else if (PathVariable.class.isInstance(paramAnn)) {  
                    PathVariable pathVar = (PathVariable) paramAnn;  
                    pathVarName = pathVar.value();  
                    annotationsFound++;  
                }  
                else if (ModelAttribute.class.isInstance(paramAnn)) {  
                    ModelAttribute attr = (ModelAttribute) paramAnn;  
                    attrName = attr.value();  
                    annotationsFound++;  
                }  
                else if (Value.class.isInstance(paramAnn)) {  
                    defaultValue = ((Value) paramAnn).value();  
                }  
                else if (paramAnn.annotationType().getSimpleName().startsWith("Valid")) {  
                    validate = true;  
                    Object value = AnnotationUtils.getValue(paramAnn);  
                    validationHints = (value instanceof Object[] ? (Object[]) value : new Object[] {value});  
                }  
            }  
  
            if (annotationsFound > 1) {  
                throw new IllegalStateException("Handler parameter annotations are exclusive choices - " +  
                        "do not specify more than one such annotation on the same parameter: " + handlerMethod);  
            }  
  
            if (annotationsFound == 0) {// 若沒有發現註解  
                Object argValue = resolveCommonArgument(methodParam, webRequest);    //判斷WebRquest是否可賦值給參數  
                if (argValue != WebArgumentResolver.UNRESOLVED) {  
                    args[i] = argValue;  
                }  
                else if (defaultValue != null) {  
                    args[i] = resolveDefaultValue(defaultValue);  
                }  
                else {  
                    Class<?> paramType = methodParam.getParameterType();  
                    if (Model.class.isAssignableFrom(paramType) || Map.class.isAssignableFrom(paramType)) {  
                        if (!paramType.isAssignableFrom(implicitModel.getClass())) {  
                            throw new IllegalStateException("Argument [" + paramType.getSimpleName() + "] is of type " +  
                                    "Model or Map but is not assignable from the actual model. You may need to switch " +  
                                    "newer MVC infrastructure classes to use this argument.");  
                        }  
                        args[i] = implicitModel;  
                    }  
                    else if (SessionStatus.class.isAssignableFrom(paramType)) {  
                        args[i] = this.sessionStatus;  
                    }  
                    else if (HttpEntity.class.isAssignableFrom(paramType)) {  
                        args[i] = resolveHttpEntityRequest(methodParam, webRequest);  
                    }  
                    else if (Errors.class.isAssignableFrom(paramType)) {  
                        throw new IllegalStateException("Errors/BindingResult argument declared " +  
                                "without preceding model attribute. Check your handler method signature!");  
                    }  
                    else if (BeanUtils.isSimpleProperty(paramType)) {// 判斷是否參數類型是不是簡單類型,如果在使用@RequestParam方式來處理,不然使用@ModelAttribute方式處理  
                        paramName = "";  
                    }  
                    else {  
                        attrName = "";  
                    }  
                }  
            }  
  
            if (paramName != null) {  
                args[i] = resolveRequestParam(paramName, required, defaultValue, methodParam, webRequest, handler);  
            }  
            else if (headerName != null) {  
                args[i] = resolveRequestHeader(headerName, required, defaultValue, methodParam, webRequest, handler);  
            }  
            else if (requestBodyFound) {  
                args[i] = resolveRequestBody(methodParam, webRequest, handler);  
            }  
            else if (cookieName != null) {  
                args[i] = resolveCookieValue(cookieName, required, defaultValue, methodParam, webRequest, handler);  
            }  
            else if (pathVarName != null) {  
                args[i] = resolvePathVariable(pathVarName, methodParam, webRequest, handler);  
            }  
            else if (attrName != null) {  
                WebDataBinder binder =  
                        resolveModelAttribute(attrName, methodParam, implicitModel, webRequest, handler);  
                boolean assignBindingResult = (args.length > i + 1 && Errors.class.isAssignableFrom(paramTypes[i + 1]));  
                if (binder.getTarget() != null) {  
                    doBind(binder, webRequest, validate, validationHints, !assignBindingResult);  
                }  
                args[i] = binder.getTarget();  
                if (assignBindingResult) {  
                    args[i + 1] = binder.getBindingResult();  
                    i++;  
                }  
                implicitModel.putAll(binder.getBindingResult().getModel());  
            }  
        }  
  
        return args;  
    }

 

 

原文地址 

http://blog.csdn.net/walkerjong/article/details/7946109

http://blog.csdn.net/walkerjong/article/details/7994326

相關文章
相關標籤/搜索