開發者在使用 Struts2 時,嘗試通過標簽從 ActionContext 或 ValueStack 中取出 errors 集合並顯示,但常規方法未能如願。
Struts2 將驗證錯誤存儲在 ActionContext.getActionContext().get("errors") 中,或通過 ActionSupport 的 getActionErrors() 方法獲取。在 JSP 頁面可使用以下標簽:
<!-- 方式一:使用 s:actionerror 標簽(推薦) -->
<s:actionerror />
<!-- 方式二:遍歷 errors 集合 -->
<s:iterator value="actionErrors">
<div class="error"><s:property /></div>
</s:iterator>
<!-- 方式三:從 ActionContext 直接取值 -->
<s:property value="#request.errors" />
ActionSupport 或實現 ValidationAware 接口。actionErrors 集合並返回 INPUT 結果。<s:actionerror/> 會自動渲染為 <ul><li>...</li></ul> 結構,可通過 CSS 定制樣式。若上述方法仍無效,請檢查攔截器棧是否包含 validation 和 workflow 攔截器,以及 JSP 頁面是否正確引入 Struts 標簽庫。