一html
@RequestMappingjava
RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的全部响应请求的方法都是以该地址做为父路径。web
RequestMapping注解有六个属性,下面咱们把她分红三类进行说明。正则表达式
value: 指定请求的实际地址,指定的地址能够是URI Template 模式(后面将会说明);json
method: 指定请求的method类型, GET、POST、PUT、DELETE等;api
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;cookie
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;session
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;
当使用@RequestMapping URI template 样式映射时, 即 someUrl/{paramId}, 这时的paramId可经过 @Pathvariable注解绑定它传过来的值到方法的参数上。
@RequestHeader 注解,能够把Request请求header部分的值绑定到方法的参数上。
@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:
该注解用来绑定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