SpringMVC学习系列(4) 之 数据绑定-1(二)

2014-11-23 21:35:42 · 作者: · 浏览: 32
在views文件夹中添加parambind. jsp和parambindresult.jsp两个视图,内容分别如下:
复制代码
<%@ page language="java" contentType="text/ html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here


复制代码
复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
自动绑定数据:

${urlParam}
${formParam}
${formFileName}



手动获取数据:

${urlParam1}
${formParam1}
${formFileName1}
复制代码
运行项目,输入内容,选择上传文件:
1
提交查看结果:
2
可以看到绑定的数据已经获取到了。
上面我们演示了如何把数据绑定到单个变量,但在实际应用中我们通常需要获取的是model对象,别担心,我们不需要把数据绑定到一个个变量然后在对model赋值,只需要把model加入相应的action参数(这里不需要指定绑定数据的注解)Spring MVC会自动进行数据转换并绑定到model对象上,一切就是这么简单。测试如下:
添加一个AccountModel类作为测试的model:
复制代码
package com.demo.web.models;
public class AccountModel {
private String username;
private String password;
public void setUsername(String username){
this.username=username;
}
public void setPassword(String password){
this.password=password;
}
public String getUsername(){
return this.username;
}
public String getPassword(){
return this.password;
}
}
复制代码
在DataBindController里面添加2个modelAutoBind的action分别对应get和post请求:
复制代码
@RequestMapping(value="/modelautobind", method = {RequestMethod.GET})
public String modelAutoBind(HttpServletRequest request, Model model){
model.addAttribute("accountmodel", new AccountModel());
return "modelautobind";
}
@RequestMapping(value="/modelautobind", method = {RequestMethod.POST})
public String modelAutoBind(HttpServletRequest request, Model model, AccountModel accountModel){
model.addAttribute("accountmodel", accountModel);
return "modelautobindresult";
}
复制代码
在views文件夹中添加modelautobind.jsp和modelautobindresult.jsp 2个视图用于提交数据和展示提交的数据:
modelautobind.jsp:
复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
Insert title here
用户名:
密 码:
复制代码
modelautobindresult.jsp :
复制代码
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
用户名:${accountmodel.username}
密 码:${accountmodel.password}