业务对象:
public class Student {
String studentName;
String studentHobby;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getStudentHobby() {
return studentHobby;
}
public void setStudentHobby(String studentHobby) {
this.studentHobby = studentHobby;
}
}
表单页面FormDemo.jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>表单提交页面</title>
</head>
<body>
<h1>请输入用户名和爱好</h1>
<form action="/submitAdmissionForm.html" method="post">
<p>
学生姓名: <input type="text" name="studentName"/>
</p>
<p>
学生爱好: <input type="text" name="studentHobby"/>
</p>
<input type="submit" value="提交"/>
</form>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>提交结果</title>
</head>
<body>
<h1>恭喜你,提交成功!!!</h1>
<table>
<tr>
<td> 学生姓名:</td>
<td>${student1.studentName}</td>
</tr>
<tr>
<td> 学生爱好:</td>
<td>${student1.studentHobby}</td>
</tr>
</table>
</body>
</html>
controller:
@Controller
public class FormSubmitController {
@RequestMapping(value = "/admissionForm.html",method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {
ModelAndView modelAndView = new ModelAndView("FormDemo");
return modelAndView;
}
@RequestMapping(value = "/submitAdmissionForm.html", method = RequestMethod.POST)
public ModelAndView submitForm(@ModelAttribute("student1") Student student1) {
ModelAndView modelAndView = new ModelAndView("SubmitSuccess");
modelAndView.addObject("student1", student1);
return modelAndView;
}
}
这里通过@ModelAttribute注解把客户端提交的表单参数封装成Student业务对象,需要注意的是,表单字段名需要与业务对象属性名保持一致,框架才能自动映射成一个对象。
配置并启动Tomcat,在浏览器中访问:http://localhost:8080/admissionForm.html 输入表单参数
提交后