首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Spring MVC 表單控制器 SimpleFormController 全流程詳解

     編輯:Java 相關知識

表單處理標準流程

Web 應用中表單提交流程:顯示表單 → 用戶填寫提交 → 服務端綁定/驗證 → 成功轉成功頁、失敗回表單頁顯示錯誤。Spring MVC SimpleFormController 將此流程封裝為模板方法,開發者只需擴展關鍵點。

控制器實現兩種方式

方式一:覆寫 doSubmitAction()(無需返回模型)

public class UserRegisterController extends SimpleFormController {
    private BbtForum bbtForum;
    public UserRegisterController() { setCommandClass(User.class); }
    protected void doSubmitAction(Object command) throws Exception {
        User user = (User) command;
        bbtForum.registerUser(user);
    }
}

方式二:覆寫 onSubmit()(需向成功頁傳模型)

protected ModelAndView onSubmit(Object command, BindException errors) throws Exception {
    User user = (User) command;
    bbtForum.registerUser(user);
    return new ModelAndView(getSuccessView(), "user", user); // 邏輯視圖名來自 successView 屬性
}

優先級:onSubmit() > doSubmitAction(),二者只會執行一個。

視圖配置

<bean name="/registerUser.html" class="com.baobaotao.web.user.UserRegisterController">
    <property name="bbtForum" ref="bbtForum"/>
    <property name="formView" value="register"/>      <!-- 表單頁 -->
    <property name="successView" value="registerSuccess"/> <!-- 成功頁 -->
</bean>

配合 InternalResourceViewResolver(prefix=/WEB-INF/jsp/, suffix=.jsp)解析為具體 JSP。

表單頁面:Spring Form 標籤綁定

<%@ taglib prefix="form" uri="https://www.springframework.org/tags/form" %>
<form:form>  <!-- 無需 action,自動提交到當前控制器 -->
    用戶名:<form:input path="userName"/> <font color="red"><form:errors path="userName"/></font><br/>
    密碼:<form:password path="password"/> <font color="red"><form:errors path="password"/></font><br/>
    Email:<form:input path="email"/> <font color="red"><form:errors path="email"/></font><br/>
    <input type="submit" value="註冊"/>
</form:form>

完整工作流程(16 步)

  1. GET 請求 → formBackingObject() 創建命令對象(可覆寫從 DB 加載編輯數據)
  2. initBinder() 註冊自定義屬性編輯器(非基本類型必需)
  3. bindOnNewForm 決定是否將 GET 參數綁定到命令對象(默認 false)
  4. onBindOnNewForm() 綁定後回調
  5. referenceData() 準備下拉框等參考數據(返回 ModelMap)
  6. 渲染 formView 顯示表單
  7. 用戶提交 → POST 請求
  8. sessionForm 判斷是否從 Session 取命令對象(默認 false)
  9. POST 參數填充命令對象
  10. onBind() 綁定後、驗證前回調
  11. validateOnBinding 觸發 Validator 驗證,錯誤收集到 Errors
  12. onBindAndValidate() 驗證後回調(適合業務規則驗證,如用戶名唯一性)
  13. processFormSubmission() 內部處理提交
  14. 有錯誤 → 回 formView;無錯誤 → 繼續
  15. isFormChangeRequest() 判斷是否表單變更請求(默認 false)
  16. 執行 onSubmit() 或 doSubmitAction() → 返回 successView

關鍵擴展點示例

編輯表單預加載數據

protected Object formBackingObject(HttpServletRequest request) throws Exception {
    int userId = ServletRequestUtils.getIntParameter(request, "userId", -1);
    return bbtForum.getUser(userId);
}

業務層驗證(用戶名唯一性)

protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) {
    User user = (User) command;
    if (bbtForum.isExsitUserName(user.getUserName())) {
        errors.rejectValue("userName", "exists.userName", "用戶名已存在");
    }
}

驗證器與國際化錯誤消息

public class UserValidator implements Validator {
    private static final Pattern EMAIL_PATTERN = Pattern.compile("\\w+@\\w+\\.\\w{2,3}");
    public boolean supports(Class clazz) { return User.class.equals(clazz); }
    public void validate(Object target, Errors errors) {
        User u = (User) target;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "required.username", "用戶名必填");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "required.password", "密碼必填");
        if (!EMAIL_PATTERN.matcher(u.getEmail()).matches())
            errors.rejectValue("email", "invalid.email", "Email格式錯誤");
    }
}

配置 ResourceBundleMessageSource (bean name="messageSource") 指定 basenames=errors,提供 errors.properties、errors_zh_CN.properties 實現錯誤消息國際化。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved