SpringMVC数据绑定
SpringMVC学习系列(5) 之 数据绑定-2
在系列(4)中我们介绍了如何用@RequestParam来绑定数据,下面我们来看一下其它几个数据绑定注解的使用方法。
1.@PathVariable 用来绑定URL模板变量值,这个我们已经在系列(3)中介绍了使用方法,这里不在赘述。
2.@CookieValue 用来绑定Cookie中的数据。下面我们用获取Cookie中的sessionId做测试:
在DataBindController添加cookiebind action,代码如下:

//@CookieValue Test
@RequestMapping(value="/cookiebind", method = {RequestMethod.GET})
public String cookieBind(HttpServletRequest request, Model model, @CookieValue(value="JSESSIONID", defaultValue="") String jsessionId){ model.addAttribute("jsessionId", jsessionId);
return "cookiebindresult";
}

在views文件夹中添加一个cookiebindresult.jsp视图,代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${jsessionId}
</body>
</html>

运行测试:

可以看到已经获取到了sessionId。
注:@CookieValue 与@RequestParam 一样也有3个参数,其含义与的@RequestParam 参数含义相同。
3.@RequestHeader 用来绑定请求头中的数据,我们用@RequestHeader获取User-Agent 来做演示:
在DataBindController添加requestheaderbind action,代码如下:

//@RequestHeader Test
@RequestMapping(value="/requestheaderbind", method = {RequestMethod.GET})
public String requestHeaderBind(HttpServletRequest request, Model model, @RequestHeader(value="User-Agent", defaultValue="") String userAgent){ model.addAttribute("userAgent", userAgent);
return "requestheaderbindresult";
}

在views文件夹中添加一个requestheaderbindresult.jsp视图,代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${userAgent}
</body>
</html>

运行测试:

可以看到已经获取到了User-Agent 。
注:@RequestHeader 与@RequestParam 一样也有3个参数,其含义与的@RequestParam 参数含义相同。
4.@ModelAttribute 绑定数据到模型中。在系列(4)的modelAutoBind action中我们将表单提交的数据添加到Model中的代码如下:
@RequestMapping(value="/modelautobind", method = {RequestMethod.POST})
public String modelAutoBind(HttpServletRequest request, Model model, AccountModel accountModel){
model.addAttribute("accountmodel", accountModel);
return "modelautobindresult";
}
而借助于@ModelAttribute 我们可以更简单的讲数据添加到Model中,把上面的代码修改为:
@RequestMapping(value="/modelautobind", method = {RequestMethod.POST})
public String modelAutoBind(HttpServletRequest request, @ModelAttribute("accountmodel") AccountModel accountModel){
return "modelautobindresult";
}
运行测试:

可以看到依然成功的绑定了提交的数据。
5.Model中的数据作用域是Request级别的,也就是说在一个Request请求中是获取不到其它Request请求的Model的数据的。但我们可以用@SessionAttributes 把数据存储到session中,来保持多次请求间数据,这样就可以来实现比如分步骤提交表单等需求。下面我们来看如何分2步把数据绑定到AccountModel中:
在DataBindController上添加:
@SessionAttributes(value = "sessionaccountmodel")
在DataBindController添加usernamebind和passwordbind action,代码如下:

//@SessionAttributes Test
@ModelAttribute("sessionaccountmodel")
public AccountModel initAccountModel(){ return new AccountModel();
} @RequestMapping(value="/usernamebind", method = {RequestMethod.GET})
public String userNameBind( Model model, AccountModel accountModel){ model.addAttribute("sessionaccountmodel", new AccountModel());
return "usernamebind";
} @RequestMapping(value="/usernamebind", method = {RequestMethod.POST})
public String userNameBindPost( @ModelAttribute("sessionaccountmodel") AccountModel accountModel){ //重定向到密码绑定测试
return "redirect:passwordbind";
} @RequestMapping(value="/passwordbind", method = {RequestMethod.GET})
public String passwordBind(@ModelAttribute("sessionaccountmodel") AccountModel accountModel){ return "passwordbind";
} @RequestMapping(value="/passwordbind", method = {RequestMethod.POST})
public String passwordBindPost(@ModelAttribute("sessionaccountmodel") AccountModel accountModel, SessionStatus status){ //销毁@SessionAttributes存储的对象
status.setComplete();
//显示绑定结果
return "sessionmodelbindresult";
}

由于我们在controller上指定了@SessionAttributes,所以在@ModelAttribute(“xxx”)注解的参数会直接在@SessionAttributes中查找名为”xxx”的对象,如果没有找到则调用@ModelAttribute(“xxx”)注解的方法返回对象并存入@SessionAttributes(如果没有找到且没有@ModelAttribute(“xxx”)注解的方法就会抛出HttpSessionRequiredException)。当执行到最后一步就可以调用SessionStatus .setComplete()方法把@SessionAttributes中保存对象销毁了(不会清除HttpSession中的数据)。
在views文件夹中添加usernamebind.jsp、passwordbind.jsp和sessionmodelbindresult.jsp视图内容分别如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form:form modelAttribute="sessionaccountmodel" method="post">
用户名:<form:input path="username"/><br/>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form:form modelAttribute="sessionaccountmodel" method="post">
密 码:<form:password path="password"/><br/>
<input type="submit" value="Submit" />
</form:form>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
用户名:${sessionaccountmodel.username}<br/>
密 码:${sessionaccountmodel.password}
</body>
</html>

运行测试:



可以看到我们已经成功的分2步把数据绑定到AccountModel中了。
注:
@SessionAttributes有value和types两个参数其中value指明要对象的名称,types指定要绑定对象的类型,如@SessionAttributes(value = "sessionaccountmodel", types=AccountModel.class)两者是and关系,需要同时满足。也可以同时指定多个value和types 如:@SessionAttributes(value = {"aa", "aa"} , types={XXX.class, YYY.class}) 。
6.@RequestBody 调用合适的MessageConvert来把非application/x-www-form-urlencoded请求中的内容转换为指定的对象它通常与@ResponseBody合用,@ResponseBody与.@RequestBody刚好相反,他把指定的对象转换为合适的内容(请求头为Accept:application/json 则返回json数据)并返回。这里我们用一个ajax请求做演示:
由于Spring默认解析json用的是Jackson,所以我们这里要把jackson-core-asl-1.9.13.jar和jackson-mapper-asl-1.9.13.jar两个包添加到我们项目。
修改AccountModel让其继承Serializable接口,并添加一个空的构造函数(为了Jackson做转换)。
在DataBindController添加requestBodyBindaction,代码如下:

//@RequestBody Test
@RequestMapping(value="/requestbodybind", method = {RequestMethod.GET})
public String requestBodyBind(Model model){ model.addAttribute("accountmodel", new AccountModel());
return "requestbodybind";
} @RequestMapping(value="/requestbodybind", method = {RequestMethod.POST})
public @ResponseBody AccountModel requestBodyBind(@RequestBody AccountModel accountModel){ return accountModel;
}

在views文件夹中添加requestbodybind.jsp视图内容如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <html>
<head> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form:form modelAttribute="accountmodel" method="post">
用户名:<form:input path="username"/><br/>
密 码:<form:password path="password"/><br/>
<input type="button" id="submit" value="Submit" />
</form:form> <script type="text/javascript">
$(function() {
$("#submit").click(function() {
var postdata = '{"username":"' + $('#username').val() + '","password":"' + $('#password').val() + '"}';
$.ajax({
type : 'POST',
contentType : 'application/json',
url : 'http://localhost:8080/SpringMVCLesson/databind/requestbodybind',
processData : false,
dataType : 'json',
data : postdata,
success : function(data) {
alert('username : '+data.username+'\npassword : '+data.password);
},
error : function() {
alert('error...');
}
});
});
});
</script>
</body>
</html>

运行测试:

结果正确,证明转换成功。
7.@RequestPart 绑定“multipart/form-data“类型数据,支持javax.servlet.http.Part文件上传,并可可以进行类型转换,详见官方文档:
代码下载:http://pan.baidu.com/s/1hqqVLTa
数据绑定部分的内容到此结束。
SpringMVC数据绑定的更多相关文章
- SpringMVC数据绑定全面示例(复杂对象,数组等)
点击链接查询原文 http://www.xdemo.org/springmvc-data-bind/ 已经使用SpringMVC开发了几个项目,平时也有不少朋友问我数据怎么传输,怎么绑定之类的话题,今 ...
- springMVC数据绑定入门
数据绑定是将用户输入绑定到领域模型的一种特性. @controller 注解使类生效 @RequestMapping(value="",meithod = RequestMetho ...
- 《SpringMVC数据绑定入门》笔记
基本类型 最好使用封装类型 简单多数据&多层级对象 简单多数据 单个对象,直接使用属性名=值即可 多层级对象 属性.属性=值即可 同属性多对象 WebDataBinder只在当前类中生效,不是 ...
- SpringMVC:数据绑定入门(-)
1.数据类型,可以绑定基本数据类型,如int age,或者包装类型如:Integer age; 两者的区别:int 类型时,必填该参数,Integer 可以为空. 2.绑定数组 , 3.绑定对象. 3 ...
- SpringMVC数据绑定一(基本类型、数组和对象(简单对象、层级对象、多参数对象))
一.int和Integer类型 如:参数为int类型的请求 @Controller public class TestController { @RequestMapping(value=" ...
- SpringMVC数据绑定二(List、Set和Map类型)
1.List类型绑定 //联系信息类 用户类的子属性 public class ContactInfo { private String phone; private String address; ...
- SpringMVC数据绑定四(自定义的类型转换器)
1.PropertyEditor 继承PropertyEditorSupport //controller @Controller public class TestController extend ...
- SpringMVC数据绑定三(JSON 、XML))
dhc chrome 地址https://chrome.google.com/webstore/detail/restlet-client-rest-api-t/aejoelaoggembcahagi ...
- SpringMVC:数据绑定入门(二)
1.为了实现所输入的数据格式与所需要的匹配该如何做到?例如:http://localhost:8080/date1.do?date1=2018-01-01,其中输入的date1的数据类型为一个格式为& ...
随机推荐
- 从头开始学JavaScript (十二)——Array类型
原文:从头开始学JavaScript (十二)--Array类型 一.数组的创建 注:ECMAscript数组的每一项都可以保存任何类型的数据 1.1Array构造函数 var colors = ne ...
- crawler_分布式网络爬虫的设计与实现_设计图
一.集中调度式 二.p2p 三.混合调度式 四.大型集群
- ASP.NET MVC学习之控制器篇扩展性
原文:ASP.NET MVC学习之控制器篇扩展性 一.前言 在之前的一篇随笔中已经讲述过控制器,而今天的随笔是作为之前的扩展. 二.正文 1.自定义动作方法 相信大家在开发过程一定会遇到动作方法的重名 ...
- [使用]Git--命令行
如何利用终端命令将文件上传到github远程服务器 (1) git status 命令查看下状态. (2) git pull 更新代码,确保代码是库上最新代码,防止覆盖其他人的提交. (3) git ...
- js小记 function 的 length 属性
原文:js小记 function 的 length 属性 [1,2,3]., ,这个略懂js的都知道. 但是 eval.length,RegExp.length,"".toStr ...
- SP服务商收益究竟有多大?
揭秘spspsp服务商怎样盈利?代办sp服务商又称持增值电信----移动网信息服务许可证信息提供商,sp主要业务有短信彩信(手机报.短信群发.客服系统).WAP.彩铃.IVR.百宝箱.JAVA游戏.B ...
- NPOI 的使用心得
Excel 数据 通过 c# 代码逻辑 导入 到数据库 . 其中各种坑爹.原因是 单元格 数据 与 数据库 字段的数据类型 会有出入.因为 Excel 是人工输入. 比如 一个单元格 本来 只能 ...
- (工具)source insight高速增加时间代码
这篇文章是程序代码更改由其他用户. 不是原厂原装,例如下列总结,使用作为个人笔记. (1)打开projectbase.打开文件Utils.em,插入下面代码: //插入时间 macro MonthTo ...
- JVM截至多少线程可以创建: unable to create new native thread
最近的测试需要很长的连接server.这些数据需要达到100W长连接,试client.一个线程来保持连接.查找linuxserver创建者默认3200当多个线程.这个错误将得到"java.l ...
- hdu 4893 Wow! Such Sequence!
http://acm.hdu.edu.cn/showproblem.php?pid=4893 三种操作: 1 k d - "add" 2 l r - "query sum ...