您的位置:首页 > 编程语言 > Java开发

springmvc中复杂数据绑定以及表单回显实现

2016-05-04 13:24 525 查看

做这个测试,请首先搭建好ssm整合demo,可以参考

我的这篇文章:http://blog.csdn.net/do_bset_yourself/article/details/51298799

1.springmvc的复杂数据绑定 :

首先贴出:原始po类

public class Student {
private Integer sid;

private String name;

private Integer age;
setter..
getter..

}


包装类型po

public class StudentVo{
private List<Student> students;

public List<Student> getStudents() {
return students;
}

public void setStudents(List<Student> students) {
this.students = students;
}

}


1. 包装类型的po类数据,以及list绑定

页面

包装类型po,及list类型绑定
<form action="${pageContext.request.contextPath }/student/addStudent.action" method="post">
1:
name<input type="text" name="students[0].name"><br/>
age:<input type="text" name="students[0].age"><br/>
<hr/>
name<input type="text" name="students[1].name"><br/>
age:<input type="text" name="students[1].age"><br/>
<hr/>
name<input type="text" name="students[2].name"><br/>
age:<input type="text" name="students[2].age"><br/>
<hr/>
<input type="submit"  value="批量添加">
</form>


contrler代码实现参数绑定,注意页面只需要写参数的属性就可以实现绑定

/**
* @param model
* @param studentVo
* 实现复杂类型的数据绑定及list<po>绑定
*/
@RequestMapping("/addStudent.action")
public String addStudents(Model model,StudentVo studentVo){
studentService.addStudents(studentVo);
return "index";

}


2. 数组绑定,po类数组也是一样的

页面定义

springmvc数据绑定,数组类型数据绑定:

<form action="${pageContext.request.contextPath }/student2/selectStudentsByIds.action" method="post">
id:<input type="text" name="sids" ><br/>
id:<input type="text" name="sids" ><br/>
id:<input type="text" name="sids" ><br/>
<input type="submit"  value="查询" >
</form>


controler代码

/**
* @param model
* @param sids
* @return
*
*
* 根据多个id查询数据,即验证数组类型数据绑定
*/
@RequestMapping("/selectStudentsByIds.action")
public String selectStudents(Model model,Integer[] sids){
//查询
List<Student> students=studentService.selectStudent(sids);
//设置显示
model.addAttribute("students", students);
//返回视图
return "showStudents";
}


传递数组时,注意使用相同的name,即数组参数名

springmvc中表单回显机制简介

springmvc中表单回显基本没有介绍的必要

因为 springmvc默认是支持po类回显的,会默认将执行po类的回显,如果你的页面参数和controler方法中参数一致,就会自动回显例如

页面中定义表单为:

<form action="${pageContext.request.contextPath }/student/insert.action" method="post">
name<input type="text" name="name" value="${student.name }"><br/>
age:<input type="text" name="age" value="${student.age }"><br/>
<input type="submit"  value="添加" >


controler中如下

@RequestMapping("/insert.action")
public String insertStudent(Model model, Student student){
/*就会会默认将执行model.addAttribute("student", student);
* 注意,key的值就是参数的值,如果页面不一致和参数不一致需要手动回显
* 而基本数据的回显,需要手动操作model.addAttribute("sid", sid);
*/
}


就会自动回显,我们只需要了解即可,而基本数据的回显,需要手动操作
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring mvc 表单