@ModelAttribute用法
Using on a method argument
@Controller
public class StudentAdmissionController {
...
@RequestMapping(value="/submitAdmissionForm.html", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(@ModelAttribute("student1") Student student1) {
ModelAndView model = new ModelAndView("AdmissionSuccess");
model.addObject("headerMessage","Gontu College of Engineering, India");
return model;
}
}
public class Student {
private String studentName;
private 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;
}
}
html form
<html>
<body>
<h1> STUDENT ADMISSION FORM FOR ENGINEERING COURSES</h1>
<form action="/FirstSpringMVCProject/submitAdmissionForm.html" method="post">
<p>
Student's Name : <input type="text" name="studentName" />
</p>
<p>
Student's Hobby : <input type="text" name="studentHobby" />
</p>
<input type="submit" value="Submit this form by clicking here" />
</form>
</body>
</html>
html result
<html>
<body>
<h1>${headerMessage}</h1>
<h3>Congratulations!! the Engineering college has processed your Application form successfully</h3>
<h2>Details submitted by you:: </h2>
<table>
<tr>
<td>Student Name :</td>
<td>${student1.studentName}</td>
</tr>
<tr>
<td>Student Hobby :</td>
<td>${student1.studentHobby}</td>
</tr>
</table>
</body>
</html>
Using at a method level
@Controller
public class StudentAdmissionController {
@RequestMapping(value="/admissionForm.html", method = RequestMethod.GET)
public ModelAndView getAdmissionForm() {
ModelAndView model1 = new ModelAndView("AdmissionForm");
return model1;
}
@ModelAttribute
public void addingCommonObjects(Model model1) {
model1.addAttribute("headerMessage", "Gontu College of Engineering, India");
}
@RequestMapping(value="/submitAdmissionForm.html", method = RequestMethod.POST)
public ModelAndView submitAdmissionForm(@ModelAttribute("student1") Student student1) {
ModelAndView model1 = new ModelAndView("AdmissionSuccess");
return model1;
}
}