引言

承接上一篇文章对 @RequestMapping 地址映射的讲解,本文主要讲解请求数据(Request)到处理器方法(Handler Method)参数数据绑定时所用到的注解,以及它们各自适用的情形。

注解分类简介

Handler Method 参数绑定常用的注解,根据它们处理的 Request 不同内容部分,主要分为以下四类(本文主要讲解常用类型):

  • 处理 Request URI 部分(指 URI Template 中的 variable,不含 queryString 部分):@PathVariable
  • 处理 Request Header 部分@RequestHeader, @CookieValue
  • 处理 Request Body 部分@RequestParam, @RequestBody
  • 处理 Attribute 类型@SessionAttributes, @ModelAttribute

1. @PathVariable

当使用 @RequestMapping 的 URI Template 样式映射时(例如 someUrl/{paramId}),可通过 @PathVariable 注解将 URI 中的变量值绑定到方法的参数上。

示例代码:

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
 
    @RequestMapping("/pets/{petId}")
    public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
        // implementation omitted
    }
}

上述代码将 URI Template 中的变量 ownerIdpetId 的值,分别绑定到方法的参数上。若方法参数名称与 URI Template 中的变量名称不一致,需要在 @PathVariable("name") 中指定 URI Template 中的名称。

2. @RequestHeader、@CookieValue

@RequestHeader

@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

绑定代码:

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
                              @RequestHeader("Keep-Alive") long keepAlive) {
    //...
}

上面的代码将 Request Header 部分的 Accept-Encoding 值绑定到参数 encoding 上,Keep-Alive Header 的值绑定到参数 keepAlive 上。

@CookieValue

@CookieValue 可以把 Request Header 中关于 Cookie 的值绑定到方法的参数上。

示例场景:

例如有如下 Cookie 值:

JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84

参数绑定代码:

@RequestMapping("/displayHeaderInfo.do")
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie) {
    //...
}

即把 JSESSIONID 的值绑定到参数 cookie 上。

3. @RequestParam, @RequestBody

@RequestParam

  1. 常用来处理简单类型的绑定。通过 Request.getParameter() 获取的 String 可直接转换为简单类型(String 到简单类型的转换操作由 ConversionService 配置的转换器来完成)。因为使用 request.getParameter() 方式获取参数,所以既可以处理 GET 方式中 queryString 的值,也可以处理 POST 方式中 Body Data 的值。
  2. 用来处理 Content-Typeapplication/x-www-form-urlencoded 编码的内容,提交方式支持 GET、POST。
  3. 该注解有两个主要属性:

    • value:用来指定要传入值的参数名称。
    • required:用来指示参数是否必须绑定。

示例代码:

@Controller
@RequestMapping("/pets")
@SessionAttributes("pet")
public class EditPetForm {
 
    // ...
 
    @RequestMapping(method = RequestMethod.GET)
    public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
        Pet pet = this.clinic.loadPet(petId);
        model.addAttribute("pet", pet);
        return "petForm";
    }
 
    // ...
}

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

示例代码:

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

4. @SessionAttributes, @ModelAttribute

@SessionAttributes

该注解用来绑定 HttpSession 中的 Attribute 对象的值,便于在方法中的参数里使用。

该注解有 valuetypes 两个属性,可以通过名字和类型指定要使用的 Attribute 对象。

示例代码:

@Controller
@RequestMapping("/editPet.do")
@SessionAttributes("pet")
public class EditPetForm {
    // ...
}

@ModelAttribute

该注解有两个用法:一个是用于方法上,一个是用于参数上。

  • 用于方法上时:通常用来在处理 @RequestMapping 之前,为请求绑定需要从后台查询的 Model。
  • 用于参数上时:用来通过名称对应,把相应名称的值绑定到注解的参数 Bean 上。要绑定的值来源于:

    1. @SessionAttributes 启用的 Attribute 对象上;
    2. @ModelAttribute 用于方法上时指定的 Model 对象;
    3. 上述两种情况都没有时,new 一个需要绑定的 Bean 对象,然后把 Request 中按名称对应的方式把值绑定到 Bean 中。

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

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

这种方式实际的效果就是在调用 @RequestMapping 的方法之前,为 Request 对象的 Model 里 put("account", Account)

用在参数上的 @ModelAttribute 示例代码:

@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)
public String processSubmit(@ModelAttribute Pet pet) {
   
}

首先查询 @SessionAttributes 有无绑定的 Pet 对象,若没有则查询 @ModelAttribute 方法层面上是否绑定了 Pet 对象,若没有则将 URI Template 中的值按对应的名称绑定到 Pet 对象的各属性上。

补充讲解:在不给定注解的情况下,参数是怎样绑定的?

通过分析 AnnotationMethodHandlerAdapterRequestMappingHandlerAdapter 的源代码发现,方法的参数在不给定注解的情况下:

  • 若要绑定的对象是简单类型:调用 @RequestParam 来处理。
  • 若要绑定的对象是复杂类型:调用 @ModelAttribute 来处理。

这里的简单类型指 Java 的原始类型(boolean, int 等)、原始类型对象(Boolean, Integer 等)、StringDateConversionService 里可以直接 String 转换成目标对象的类型。

下面贴出 AnnotationMethodHandlerAdapter 中绑定参数的部分源代码:

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

RequestMappingHandlerAdapter 中使用的参数绑定,代码稍微有些不同,有兴趣的同仁可以分析下,最后处理的结果都是一样的。

示例 1:

@RequestMapping({"/", "/home"})
public String showHomePage(String key){
    logger.debug("key="+key);
    return "home";
}

这种情况下,就调用默认的 @RequestParam 来处理。

示例 2:

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

这种情况下,就调用 @ModelAttribute 来处理。

参考文档

  1. Spring Web Doc: spring-3.1.0/docs/spring-framework-reference/html/mvc.html
说明:本文基于 Spring 3.1.0 版本编写,文中涉及的 AnnotationMethodHandlerAdapter 类在 Spring 3.2 中已被标记为 deprecated,并在 Spring 5.0 中移除(由 RequestMappingHandlerAdapter 完全取代)。虽然参数绑定的核心逻辑与结论在现代版本中依然适用,但源码分析部分仅适用于旧版本参考。