处理模型数据
1、通过pojo从表单向controller传递数据
pojp层
Student.java:
public class Student {
private Integer stuId;//学号
private String stuName;//姓名
private Integer StuAge;//年龄
public Student() {
}
public Student(Integer stuId, String stuName, Integer stuAge) {
this.stuId = stuId;
this.stuName = stuName;
StuAge = stuAge;
}
public Integer getStuId() {
return stuId;
}
public void setStuId(Integer stuId) {
this.stuId = stuId;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public Integer getStuAge() {
return StuAge;
}
public void setStuAge(Integer stuAge) {
StuAge = stuAge;
}
@Override
public String toString() {
return "Student{" +
"stuId=" + stuId +
", stuName='" + stuName + '\'' +
", StuAge=" + StuAge +
'}';
}
}
controller层
StudentController.java:
package com.zm.controller;
@Controller
@RequestMapping("/stu")
public class StudentController {
/*跳转到stuForm页面*/
@RequestMapping("/stuForm")
public String stuForm(){
return "stuForm";
}
/*从表单向controller传递数据*/
@RequestMapping("/saveStu")
public String saveStu(Student stu){
System.out.println("从表单向controller传递数据……");
System.out.println(stu);
return "hello";
}
}
jsp页面
stuForm.jsp:
<form method="post" action="saveStu">
<p>
学号:<input type="text" name="stuId">
</p>
<p>
姓名:<input type="text" name="stuName">
</p>
<p>
年龄:<input type="text" name="stuAge">
</p>
<p>
<input type="submit" value="提交">
<input type="reset" value="取消">
</p>
</form>
注意:表单中name属性的值与pojo对象中的属性名一致时,可以自动将数据装配到对象中;否则,要进行处理
2、从controller向页面传递数据
2.1 ModelAndview
StudentControler.java
@Controller
@RequestMapping("/stu")
public class StudentController {
/*从controller向页面传递数据*/
@RequestMapping("/show")
public ModelAndView showStu(){
List<Student> list = new ArrayList<Student>();
list.add(new Student(1,"小明",21));
list.add(new Student(2,"Jack",20));
ModelAndView mav = new ModelAndView();
//设置视图名(即要的页面的名字)
mav.setViewName("showStu");
mav.addObject("list",list);
//返回这个ModelAndView
return mav;
}
}
showStu.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>展示学生信息</title>
</head>
<body>
<table border="1px" cellspacing="0" width="400px">
<tr height="30px">
<th>学号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
<c:forEach items="${list}" var="stu">
<tr height="30px">
<td>${stu.stuId}</td>
<td>${stu.stuName}</td>
<td>${stu.stuAge}</td>
</tr>
</c:forEach>
</table>
</body>
</html>
2.2 Model
controller层:
/*2.Model*/
@RequestMapping("/show2")
public String showStu2(Model model){
List<Student> list = new ArrayList<Student>();
list.add(new Student(12,"小红",22));
list.add(new Student(22,"Tom",21));
model.addAttribute("list",list);
return "showStu";
}
2.3 Map
controller层:
@RequestMapping("/show3")
public String showStu3(Map<String,Student> map){
map.put("stu",new Student(10,"小黑",22));
return "showStu";
}
showStu.jsp:
<ul>
<li>学号:${stu.stuId}</li>
<li>姓名:${stu.stuName}</li>
<li>年龄:${stu.stuAge}</li>
</ul>