引言:

原文链接:http://blog.csdn.net/kobejayandy/article/details/12690161

接上一篇文章,对@RequestMapping进行地址映射讲解之后,该篇主要讲解request 数据到handler method 参数数据的绑定所用到的注解和什么情形下使用;

简介:

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

示例代码:

  1. @Controller
  2. @RequestMapping("/owners/{ownerId}")
  3. public class RelativePathUriTemplateController {
  4. @RequestMapping("/pets/{petId}")
  5. public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
  6. // implementation omitted
  7. }
  8. }

上面代码把URI template 中变量 ownerId的值和petId的值,绑定到方法的参数上。若方法参数名称和需要绑定的uri template中变量名称不一致,需要在@PathVariable("name")指定uri template中的名称。

2、 @RequestHeader、@CookieValue

@RequestHeader 注解,可以把Request请求header部分的值绑定到方法的参数上。

示例代码:

这是一个Request 的header部分:

  1. Host                    localhost:8080
  2. Accept                  text/html,application/xhtml+xml,application/xml;q=0.9
  3. Accept-Language         fr,en-gb;q=0.7,en;q=0.3
  4. Accept-Encoding         gzip,deflate
  5. Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7
  6. Keep-Alive              300
  1. @RequestMapping("/displayHeaderInfo.do")
  2. public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,
  3. @RequestHeader("Keep-Alive") long keepAlive)  {
  4. //...
  5. }

上面的代码,把request header部分的 Accept-Encoding的值,绑定到参数encoding上了, Keep-Alive header的值绑定到参数keepAlive上。

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

例如有如下Cookie值:

  1. JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84

参数绑定的代码:

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

即把JSESSIONID的值绑定到参数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) 该注解有两个属性: value、required; value用来指定要传入值的id名称,required用来指示参数是否必须绑定;

示例代码:

  1. @Controller
  2. @RequestMapping("/pets")
  3. @SessionAttributes("pet")
  4. public class EditPetForm {
  5. // ...
  6. @RequestMapping(method = RequestMethod.GET)
  7. public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
  8. Pet pet = this.clinic.loadPet(petId);
  9. model.addAttribute("pet", pet);
  10. return "petForm";
  11. }
  12. // ...

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

示例代码:

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

4、@SessionAttributes, @ModelAttribute

@SessionAttributes:

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

该注解有value、types两个属性,可以通过名字和类型指定要使用的attribute 对象;

示例代码:

  1. @Controller
  2. @RequestMapping("/editPet.do")
  3. @SessionAttributes("pet")
  4. public class EditPetForm {
  5. // ...
  6. }

@ModelAttribute

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

用于方法上时:  通常用来在处理@RequestMapping之前,为请求绑定需要从后台查询的model;

用于参数上时: 用来通过名称对应,把相应名称的值绑定到注解的参数bean上;要绑定的值来源于:

A) @SessionAttributes 启用的attribute 对象上;

B) @ModelAttribute 用于方法上时指定的model对象;

C) 上述两种情况都没有时,new一个需要绑定的bean对象,然后把request中按名称对应的方式把值绑定到bean中。

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

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

这种方式实际的效果就是在调用@RequestMapping的方法之前,为request对象的model里put(“account”, Account);

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

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

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

springmvc用来绑定参数的注解(转)的更多相关文章

  1. SpringMVC中,前台jsp封装参数,绑定参数,传递参数到后台controller的过程详解

    前台到后台的流程:前台jsp->后台:controller控制器层->service业务层->DAO数据访问层->数据库model模型层. 从上面流程可知,前台jsp的数据,想 ...

  2. SpringMVC第四篇【参数绑定详讲、默认支持参数类型、自定义参数绑定、RequestParam注解】

    参数绑定 我们在Controller使用方法参数接收值,就是把web端的值给接收到Controller中处理,这个过程就叫做参数绑定- 默认支持的参数类型 从上面的用法我们可以发现,我们可以使用req ...

  3. 16 SpringMVC 的请求参数的绑定与常用注解

    1.SpringMVC 绑定请求参数 (1)支持的数据类型 基本类型参数: 包括基本类型和 String 类型POJO 类型参数: 包括实体类,以及关联的实体类数组和集合类型参数: 包括 List 结 ...

  4. Springmvc的handler method参数绑定常用的注解

    转自:http://blog.longjiazuo.com/archives/1149   1. 简介: handler method参数绑定常用的注解,我们根据他们处理的Request的不同内容部分 ...

  5. SpringMVC源码之参数解析绑定原理

    摘要 本文从源码层面简单讲解SpringMVC的参数绑定原理 SpringMVC参数绑定相关组件的初始化过程 在理解初始化之前,先来认识一个接口 HandlerMethodArgumentResolv ...

  6. SpringMVC之Controller和参数绑定

    在上一篇Spring+SpringMVC+Mybatis整合中说到了SSM的整合,并且在其中添加了一个简单的查询功能,目的只是将整个整合的流程进行一个梳理,下面在上一篇中工程的基础上再说一些关于Spr ...

  7. springMVC第二天——高级参数绑定与其它特性

    大纲摘要: 1.高级参数绑定 a) 数组类型的参数绑定 b) List类型的绑定 2.@RequestMapping注解的使用 3.Controller方法返回值 4.Springmvc中异常处理 5 ...

  8. SpringMVC中post请求参数注解@requestBody使用问题

    一.httpClient发送Post 原文https://www.cnblogs.com/Vdiao/p/5339487.html public static String httpPostWithJ ...

  9. SSM框架之SpringMVC(2)参数绑定及自定义类型转换

    SpringMVC(2)参数绑定及自定义类型转换 1.请求参数的绑定 1.1. 请求参数的绑定说明 1.1.1.绑定机制 表单提交的数据都是k=v格式的 username=haha&passw ...

随机推荐

  1. CWM是什么?

    CWM [1]  (CommonWarehouseMetamodel公共仓库元模型)是OMG组织在数据仓库系统中定义了一套完整的元模型体系结构,用于数据仓库构建和应用的元数据建模.公共仓库元模型指定的 ...

  2. android studio 中类似VS的代码折叠功能Region

    1. 打开android studio 2. 选择要折叠的代码 3. 按Ctrl + Alt + T 选择 “region .. end region comments” Group selectio ...

  3. Jenkins+maven+Tomcat+SVN一键自动打包部署应用到服务器

    今天请教了大神,终于把jenkins给搞明白了 现在做下笔记,防止自己老年痴呆又忘了怎么配置 (截图可能不够清晰,有不清楚的随时评论打call) 机器配置: 安装配置规划 机器 192.168.169 ...

  4. HDU1712:ACboy needs your help(分组背包)

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=1712 解释看这里:http://www.cnblogs.com/zhangmingcheng/p/3940 ...

  5. PAT 1035 Password [字符串][简单]

    1035 Password (20 分) To prepare for PAT, the judge sometimes has to generate random passwords for th ...

  6. curl: (60) SSL certificate problem: unable to get local issuer certificate

    国内私募机构九鼎控股打造APP,来就送 20元现金领取地址:http://jdb.jiudingcapital.com/phone.html 内部邀请码:C8E245J (不写邀请码,没有现金送) 国 ...

  7. HTML 2 (Day49)

    一.table标签 http://www.cnblogs.com/shaojiafeng/p/7516741.html 二.form 表单属性 action:表单提交到哪.一般指向服务端一个程序,程序 ...

  8. 同步锁,死锁现象与递归锁,信息量Semaphore.....(Day36)

    一.同步锁 三个需要注意的点: #1.线程抢的是GIL锁,GIL锁相当于执行权限,拿到执行权限后才能拿到互斥锁Lock,其他线程也可以抢到GIL,但如果发现Lock仍然没有被释放则阻塞,即便是拿到执行 ...

  9. knockout 学习使用笔记------绑定值时赋值失败

    在使用knockout绑定值的时候,发现无论怎么赋值都赋值失败,最后检查前端页面才发现,同一个属性绑定值的时候,绑定了两次,而在js中进行属性绑定的时候是双向绑定的,SO,产生了交互影响.谨记之. 并 ...

  10. Unity,自带Random函数,上下限注意的地方

    Random.Range() 该函数有两个重载,分别是 float和 int 的,这两者还是有差别的,具体是: float型,随机值涵盖: 最小和最大值 Random.Range(0f,1f) 是有可 ...