在 Struts 2 框架中,ActionSupport 類提供的 validate() 方法是實現伺服端資料驗證的核心機制。該方法會在 execute() 方法執行前自動被攔截器調用,若驗證失敗,框架會自動導向 struts.xml 中該 Action 對應 name="input" 的 Result 頁面,通常為原表單頁,實現「哪裡來,回哪裡去」的用戶體驗。
@Override
public void validate() {
if (username == null || username.length() < 4 || username.length() > 6) {
this.addActionError("用戶名長度必須在 4-6 字元之間");
}
}
若驗證不通過,呼叫 addActionError() 將錯誤訊息存入 Action 級別的錯誤集合。驗證流程結束後,Struts 2 會檢查是否存在錯誤,若有則跳轉至 input 頁面。
在表單頁(如 register.jsp)引入 Struts 2 標籤庫:
<%@ taglib prefix="s" uri="/struts-tags" %>
使用 <s:actionerror /> 標籤輸出 Action 級別錯誤,並可透過 CSS 樣式美化顯示效果。
if (birthday != null && graduation != null) {
Calendar c1 = Calendar.getInstance();
c1.setTime(birthday);
Calendar c2 = Calendar.getInstance();
c2.setTime(graduation);
if (!c1.before(c2)) {
this.addActionError("出生日期必須早於畢業日期");
}
}
Struts 2 提供兩種錯誤層級,支援差異化顯示:
addActionError(),對應 <s:actionerror />,適用於全域性錯誤(如業務邏輯違規)addFieldError("fieldName", "msg"),對應 <s:fielderror />,適用於特定欄位錯誤(如格式不符)範例:
public void validate() {
if (username == null || username.length() < 4) {
this.addActionError("用戶名驗證失敗(Action 級別)");
this.addFieldError("username", "用戶名長度不足(Field 級別)");
}
}
搭配主題為 simple 的表單,可自訂版面並手動控制 Field 錯誤顯示位置:
<s:form action="RegisterAction" theme="simple">
用戶名: <s:textfield name="username" /><br/>
<s:fielderror fieldName="username" /><br/>
...
</s:form>
Struts 2 標籤(<s:textfield> 等)在驗證失敗導回表單時,會自動將用戶原輸入值回顯於對應欄位。若發生類型轉換失敗(如整數欄位輸入字串),框架會自動將 Invalid field value for field "age" 加入 Field 級別錯誤。
validate() 方法進行輸入驗證input 結果頁;否則執行 execute()getActionErrors() 回傳的是集合副本,對副本呼叫 clear() 不會影響原集合。若需在驗證後清除錯誤並強制執行 execute(),可呼叫 clearAllActionErrors() 或 clearAllFieldErrors()。
Field 錯誤底層以 LinkedHashMap<String, List<String>> 儲存,Key 為欄位名,Value 為錯誤訊息列表,支援單一欄位對應多條錯誤訊息。
validate() 不應包含副作用操作(如資料庫寫入),僅做純驗證邏輯