SpringMvc之参数绑定注解详解

  在 SpringMVC 中,提交请求的数据是通过方法形参来接收的。从客户端请求的 key/value 数据,经过参数绑定,将 key/value 数据绑定到 Controller 的形参上,然后在 Controller 就可以直接使用该形参。

一、类型支持

  1、默认支持类型

  SpringMVC 有支持的默认参数类型,我们直接在形参上给出这些默认类型的声明,就能直接使用了。

HttpServletRequest 对象

HttpServletResponse 对象

HttpSession 对象

Model/ModelMap 对象

@RequestMapping("/defaultParameter")
    public ModelAndView defaultParameter(HttpServletRequest request,HttpServletResponse response,
                            HttpSession session,Model model,ModelMap modelMap) throws Exception{return null;
    }

  2、基本数据类型

1、byte,占用一个字节,取值范围为 -128-127,默认是“u0000”,表示空
2、short,占用两个字节,取值范围为 -32768-32767
3、int,占用四个字节,-2147483648-2147483647
4、long,占用八个字节,对 long 型变量赋值时必须加上"L"或“l”,否则不认为是 long5、float,占用四个字节,对 float 型进行赋值的时候必须加上“F”或“f”,如果不加,会产生编译错误,因为系统自动将其定义为 double 型变量。double转换为float类型数据会损失精度。
float a = 12.23产生编译错误的,float a = 12是正确的 6、double,占用八个字节,对 double 型变量赋值的时候最好加上“D”或“d”,但加不加不是硬性规定 7、char,占用两个字节,在定义字符型变量时,要用单引号括起来 8、boolean,只有两个值“true”和“false”,默认值为false,不能用0或非0来代替,这点和C语言不同 
@RequestMapping(value = {"/card"}, method = RequestMethod.GET)
public TravelCard getTravelCard(@RequestParam("amount") long amount) {
    return null;
}

  3、包装数据类型的绑定

  包装类型如Integer、Long、Byte、Double、Float、Short,(String 类型在这也是适用的)。

  建议所有的参数都用包装类型,别用原始类型,因为无法将null转换为原始类型,入参不传递此参数时则会报错。

@RequestMapping(value = {"/card"}, method = RequestMethod.GET)
public TravelCard getTravelCard(@RequestParam("amount") Integer amount) {
    return null;
}

  4、POJO(实体类)类型的绑定

@RequestMapping(value = {"/passenger"}, method = RequestMethod.POST)
public long insertOne(@RequestBody Passenger passenger) {
    LOGGER.info("Get a request for insertPassenger(POST).");
    return this.passengerService.insertOne(passenger);
}

二、@RequestMapping注解属性

  RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。RequestMapping注解有六个属性,下面我们把她分成三类进行说明。

  1、value, method;  

  value:指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);当只设置value一个属性时,value可以省略不写,当有其他属性时则需要加上进行区分。
  method:指定请求的method类型, GET、POST、PUT、DELETE等;

@RequestMapping("/v1/metro")
public class PassengerController {
}

@RequestMapping(value = {"/travel"}, method = RequestMethod.POST)
public Map travel(@RequestParam long passengerId,
                   @RequestParam long startStation,
                   @RequestParam long endStation,
                   @RequestParam int cardType) {return null;
}

  value的uri值为以下三类:

    A) 可以指定为普通的具体值;

    B)  可以指定为含有某变量的一类值(URI Template Patterns with Path Variables);

    C) 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);

    example B)

@RequestMapping(value = {"/travel/{passengerId}"}, method = RequestMethod.GET)
public List<TravelRecord> queryTravelRecords(@PathVariable("passengerId") long passengerId) {return null;
}

    example C)

@RequestMapping("/spring-web/{symbolicName:[a-z-]+}-{version:d.d.d}.{extension:.[a-z]}")  
public void handle(@PathVariable String version, @PathVariable String extension) {      
    // ...   
}

  2、consumes,produces;

  consumes:指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

@Controller  
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")  
public void addPet(@RequestBody Pet pet, Model model) {      
    // implementation omitted  
}  

  方法仅处理request的Content-Type为“application/json”类型的请求。

  produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

@Controller  
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")  
@ResponseBody  
public Pet getPet(@PathVariable String petId, Model model) {      
    // implementation omitted  
}

  方法仅处理request请求中Accept头中包含了"application/json"的请求,同时暗示了返回的内容类型为application/json;

  3、params,headers;

  params:指定request中必须包含某些参数值是,才让该方法处理。

@Controller  
@RequestMapping("/owners/{ownerId}")  
public class RelativePathUriTemplateController {  
  
  @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")  
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {      
    // implementation omitted  
  }  
}

  仅处理请求中包含了名为“myParam”,值为“myValue”的请求;

  headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。

@Controller  
@RequestMapping("/owners/{ownerId}")  
public class RelativePathUriTemplateController {  
  
@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")  
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {      
    // implementation omitted  
  }  
}

  仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.ifeng.com/”的请求;

三、参数绑定

  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注解绑定它传过来的值到方法的参数上。

@RequestMapping(value = {"/travel/{passengerId}"}, method = RequestMethod.GET)
public List<TravelRecord> queryTravelRecords(@PathVariable("passengerId") long passengerId) {
    return null;
}

  若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable("name")指定uri template中的名称。

  2、 @RequestHeader、@CookieValue

  @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)  {  
  //...  
  
} 

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

  有如下Cookie值:

@RequestMapping("/displayHeaderInfo.do")  
public void displayHeaderInfo(@CookieValue("JSESSIONID") String 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) 该注解有3个属性: value、required、defaultValue; value用来指定要传入值的id名称(改变参数名字),required用来指示参数是否必须绑定,defaultValue用于对参数设置默认值,required为true时,如果参数为空,会报错,但是当required=true,和defaultValue= 同时出现时,required失效,可传可不传;

@RequestMapping(value = {"/travel"}, method = RequestMethod.POST)
public Map travel(@RequestParam(defaultValue = 1) long passengerId,
                   @RequestParam long startStation,
                   @RequestParam long endStation,
                   @RequestParam(value="card") int cardType) {
    return null;
}

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

  因为@RequestBody是将post请求中content值转为一个整体对象。@RequestBody的解析有两个条件:
  1. POST请求中content的值必须为json格式(存储形式可以是字符串,也可以是byte数组);
  2. @RequestBody注解的参数类型必须是完全可以接收参数值的类型,比如:Map,JSONObject,或者对应的JavaBean;所以Integer等类型不能作为@RequestBody注解的参数类型。

  4、@SessionAttributes, @ModelAttribute

  @SessionAttributes:
  该注解用来绑定HttpSession中的attribute对象的值,便于在方法中的参数里使用。
  该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象;

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

  @ModelAttribute
  该注解有两个用法,一个是用于方法上,一个是用于参数上;
  用于方法上时: 通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;
  用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:
    A) @SessionAttributes 启用的attribute 对象上;
    B) @ModelAttribute 用于方法上时指定的model对象;
    C) 上述两种情况都没有时,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对象的各属性上。

四、RequestBody、ResponseBody比较

  @RequestBody
  作用:
    i) 该注解用于读取Request请求的body部分数据,使用系统默认配置的HttpMessageConverter进行解析,然后把相应的数据绑定到要返回的对象上;
    ii) 再把HttpMessageConverter返回的对象数据绑定到 controller中方法的参数上。
  使用时机:
    A) GET、POST方式提时, 根据request header Content-Type的值来判断:
      application/x-www-form-urlencoded, 可选(即非必须,因为这种情况的数据@RequestParam, @ModelAttribute也可以处理,当然@RequestBody也能处理);
      multipart/form-data, 不能处理(即使用@RequestBody不能处理这种格式的数据);
      其他格式, 必须(其他格式包括application/json, application/xml等。这些格式的数据,必须使用@RequestBody来处理);
    B) PUT方式提交时, 根据request header Content-Type的值来判断:
      application/x-www-form-urlencoded, 必须;
      multipart/form-data, 不能处理;
      其他格式, 必须;
  说明:request的body部分的数据编码格式由header部分的Content-Type指定;

  @ResponseBody
  作用:
    该注解用于将Controller的方法返回的对象,通过适当的HttpMessageConverter转换为指定格式后,写入到Response对象的body数据区。
  使用时机:
    返回的数据不是html标签的页面,而是其他某种格式的数据时(如json、xml等)使用;