以下示例演示如何編寫一個簡單的基於Web的應用程序,它使用Spring Web MVC框架使用HTML表單。 首先使用Eclipse IDE,並按照以下步驟使用Spring Web Framework開發基於動態表單的Web應用程序:
- 基於上一小節中的Spring MVC - Hello World實例章節所創建的 HelloWeb來創建一個新的工程為:
FormHandling
,並創建一個包名稱為com.yiibai.springmvc
。 - 在
com.yiibai.springmvc
包下創建兩個Java類Student
,StudentController
。 - 在
jsp
子文件夾下創建兩個視圖文件student.jsp
,result.jsp
。 - 最后一步是創建所有源和配置文件的內容並運行應用程序,如下所述。
完整的項目文件結構如下所示 -
Student.java文件中的代碼內容 -
package com.yiibai.springmvc; public class Student { private Integer age; private String name; private Integer id; public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void setId(Integer id) { this.id = id; } public Integer getId() { return id; } }
StudentController.java 文件中的代碼內容 -
package com.yiibai.springmvc; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.ui.ModelMap; @Controller public class StudentController { @RequestMapping(value = "/student", method = RequestMethod.GET) public ModelAndView student() { return new ModelAndView("student", "command", new Student()); } @RequestMapping(value = "/addStudent", method = RequestMethod.POST) public String addStudent(@ModelAttribute("SpringWeb")Student student, ModelMap model) { model.addAttribute("name", student.getName()); model.addAttribute("age", student.getAge()); model.addAttribute("id", student.getId()); return "result"; } }
這里的第一個服務方法student()
,我們已經在ModelAndView
對象中傳遞了一個名為“command
”的空對象,因為如果在JSP中使用<form:form>
標簽,spring框架需要一個名為“command
”的對象文件。 所以當調用student()
方法時,它返回student.jsp
視圖。
第二個服務方法addStudent()
將在 URLHelloWeb/addStudent
上的POST方法提交時調用。將根據提交的信息准備模型對象。最后,將從服務方法返回“result
”視圖,這將最終渲染result.jsp
視圖。
student.jsp文件的內容如下所示 -
<%@ page contentType="text/html; charset=UTF-8" %> <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <html> <head> <title>Spring MVC表單處理</title> </head> <body> <h2>Student Information</h2> <form:form method="POST" action="/FormHandling/addStudent"> <table> <tr> <td><form:label path="name">名字:</form:label></td> <td><form:input path="name" /></td> </tr> <tr> <td><form:label path="age">年齡:</form:label></td> <td><form:input path="age" /></td> </tr> <tr> <td><form:label path="id">編號:</form:label></td> <td><form:input path="id" /></td> </tr> <tr> <td colspan="2"> <input type="submit" value="提交表單"/> </td> </tr>