通過@ModelAttribute註解封裝客戶端提交表單引數為一個業務物件
阿新 • • 發佈:2019-01-02
業務物件:
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檔案
提交成功的頁面SubmitSuccess.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 輸入表單引數
提交後