在 Spring MVC 中處理表單提交是常見需求。傳統做法可能需要分別繼承 AbstractController 顯示表單,繼承 AbstractCommandController 處理表單,但這會導致維護兩個控制器。SimpleFormController 正是為了解決這個問題而設計:它自動處理 GET 請求顯示表單、POST 請求處理提交,並在驗證失敗時自動重新顯示表單讓用戶修正錯誤。
首先定義一個簡單的命令對象(表單對象)來承載表單數據:
package model;
public class Student {
private String name;
private String sex;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public String getSex() { return sex; }
public void setSex(String sex) { this.sex = sex; }
}
繼承 SimpleFormController 並覆寫關鍵方法:
package Action;
import model.Student;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
public class RegisterStudentController extends SimpleFormController {
public RegisterStudentController() {
this.setCommandClass(Student.class);
}
protected ModelAndView onSubmit(Object object, BindException arg1) throws Exception {
Student stu = (Student) object;
return new ModelAndView(getSuccessView(), "student", stu);
}
}
注意:onSubmit() 可返回 ModelAndView 向成功頁面傳遞數據,而 doSubmitAction() 不能返回數據,兩者同時只有一個生效。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
xmlns="https://java.sun.com/xml/ns/j2ee"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://java.sun.com/xml/ns/j2ee
https://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/train-service.xml,/WEB-INF/train-data.xml,/WEB-INF/train-servlet.xml</param-value>
</context-param>
<servlet>
<servlet-name>train</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>train</servlet-name>
<url-pattern>*.mvc</url-pattern>
</servlet-mapping>
<filter>
<filter-name>character</filter-name>
<filter-class>Action.CharacterFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>character</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
定義控制器 Bean 並配置表單視圖與成功視圖:
<bean id="RegisterStudentController" class="Action.RegisterStudentController">
<property name="formView">
<value>register</value>
</property>
<property name="successView">
<value>success</value>
</property>
</bean>
<bean id="simpleUrlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
<property name="mappings">
<props>
<prop key="/home.mvc">HomeController</prop>
<prop key="/register.mvc">RegisterStudentController</prop>
</props>
</property>
</bean>
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>學生註冊</title>
</head>
<body>
<form action="<%=request.getContextPath() %>/register.mvc" method="post">
姓名:<input type="text" name="name"/><br/>
性別:<input type="text" name="sex"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>註冊成功</title>
</head>
<body>
${student.name}-----${student.sex} <br>
</body>
</html>
啟動應用後訪問 /register.mvc,填寫表單提交,成功頁將顯示提交的學生信息。文中也提到使用 Filter 處理中文編碼問題。