@RequestParam @RequestBody @PathVariable 等参数绑定注解详解

简介:
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

带占位符的 URL 是 Spring3.0 新增的功能,该功能在SpringMVC 向 REST 目标挺进发展过程中具有里程碑的意义

通过 @PathVariable 可以将 URL 中占位符参数绑定到控制器处理方法的入参中:URL 中的 {xxx} 占位符可以通过@PathVariable("xxx") 绑定到操作方法的入参中。

/** 
     * localhost:8080/springmvc/hello/pathVariable/bigsea 
     * localhost:8080/springmvc/hello/pathVariable/sea 
     * 这些URL 都会 执行此方法 并且将  <b>bigsea</b>、<b>sea</b> 作为参数 传递到name字段 
     * @param name 
     * @return 
     */  
    @RequestMapping("/pathVariable/{name}")  
    public String pathVariable(@PathVariable("name")String name){  
        System.out.println("hello "+name);  
        return "helloworld";  
    }  
JSP


<h1>pathVariable</h1>  
<a href="${pageContext.request.contextPath}/hello/pathVariable/bigsea" > name is bigsea </a>  
<br/>  
<a href="${pageContext.request.contextPath}/hello/pathVariable/sea" > name is sea</a>  
<br/>  

 

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

@RequestParam


1.常用来处理简单类型的绑定,通过Request.getParameter() 获取的String可直接转换为简单类型的情况( String--> 简单类型的转换操作由ConversionService配置的转换器来完成);因为使用request.getParameter()方式获取参数,所以可以处理get 方式中queryString的值,也可以处理post方式中 body data的值;

2.用来处理Content-Type: 为 application/x-www-form-urlencoded编码的内容,提交方式GET、POST;

3.该注解有两个属性: value、required; value用来指定要传入值的id名称,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

1、@requestBody注解常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容,比如说:application/json或者是application/xml等。一般情况下来说常用其来处理application/json类型。

2、通过@requestBody可以将请求体中的JSON字符串绑定到相应的bean上,当然,也可以将其分别绑定到对应的字符串上。
    例如说以下情况:

$.ajax({
        url:"/login",
        type:"POST",
        data:'{"userName":"admin","pwd","admin123"}',
        content-type:"application/json charset=utf-8",
        success:function(data){
          alert("request success ! ");
        }
    });

    @requestMapping("/login")
    public void login(@requestBody String userName,@requestBody String pwd){
      System.out.println(userName+" :"+pwd);
    }
    

这种情况是将JSON字符串中的两个变量的值分别赋予了两个字符串,但是呢假如我有一个User类,拥有如下字段:
String userName;
String pwd;
    
那么上述参数可以改为以下形式:
@requestBody User user 这种形式会将JSON字符串中的值赋予user中
对应的属性上需要注意的是,JSON字符串中的key必须对应user中的属性名,否则是请求不过去的。

3、在一些特殊情况@requestBody也可以用来处理content-type类型为application/x-www-form-urlcoded的内容,只不过这种方式不是很常用,在处理这类请求的时候,@requestBody会将处理结果放到一个MultiValueMap<String,String>中,这种情况一般在
特殊情况下才会使用,
  例如jQuery easyUI的datagrid请求数据的时候需要使用到这种方式、小型项目只创建一个POJO类的话也可以使用这种接受方式.

@sessionattributes 

@sessionattributes注解应用到Controller上面,可以将Model中的属性同步到session当中。


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

@ModelAttribute

@ModelAttribute通常使用在Controller方法的参数注解中,用于解释model entity,但同时,也可以放在方法注解里。

如果把@ModelAttribute放在方法的注解上时,代表的是:该Controller的所有方法在调用前,先执行此@ModelAttribute方法

 

@Controller
@RequestMapping(value="test")
public class PassportController {

    @ModelAttribute
    public void preRun() {
        System.out.println("Test Pre-Run");
    }
    
    @RequestMapping(method=RequestMethod.GET)
    public String index() {
        return "login/index";
    }
    
    @RequestMapping(value="login", method=RequestMethod.POST)
    public ModelAndView login(@ModelAttribute @Valid Account account, BindingResult result)
        :
        :
    }
    
    @RequestMapping(value="logout", method=RequestMethod.GET)
    public String logout() {
        :
        :
    }
    
}

在调用所有方法之前,都会先执行preRun()方法。
 @Controller 
 2 public class HelloWorldController { 
 3     @ModelAttribute("user") 
 4     public User addAccount() { 
 5         return new User("jz","123"); 
 6      } 
 7 
 8     @RequestMapping(value = "/helloWorld") 
 9     public String helloWorld(@ModelAttribute("user") User user) { 
10            user.setUserName("jizhou"); 
11            return "helloWorld"; 
12         } 
13   }

在这个例子里,@ModelAttribute("user") User user注释方法参数,参数user的值来源于addAccount()方法中的model属性。
  此时如果方法体没有标注@SessionAttributes("user"),那么scope为request,如果标注了,那么scope为session



绑定请求参数到命令对象:放在功能处理方法的入参上时,用于将多个请求参数绑定到一个命令对象,从而简化绑定流程,而且自动暴露为模型数据用于视图页面展示时使用。

  其实  @ModelAttribute 此处对于供视图页面展示来说与 model.addAttribute("attributeName", abc); 功能类似。

1 @Controller 
2 public class HelloWorldController { 
3     @RequestMapping(value = "/helloWorld") 
4     public String helloWorld(@ModelAttribute User user) { 
5         return "helloWorld"; 
6      } 
7 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值