springmvc中複雜資料繫結以及表單回顯實現
阿新 • • 發佈:2019-02-20
做這個測試,請首先搭建好ssm整合demo,可以參考
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);
*/
}
就會自動回顯,我們只需要瞭解即可,而基本資料的回顯,需要手動操作