简介:

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

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

  上面代码把URI template中变量ownerId的值和petId的值,绑定到方法的参数上。若方法参数名称和需要绑定的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  
View Code

相关文章: