<html:cancel> 標籤產生的 HTML 為:
<input type="submit" name="org.apache.struts.taglib.html.CANCEL" value="返回" onclick="bCancel=true;">
關鍵點:
type="submit" — 會提交表單name="org.apache.struts.taglib.html.CANCEL" — 特殊參數名,Struts 攔截識別onclick="bCancel=true;" — JavaScript 旗標,配合 Validator 跳過驗證Struts 自動產生的驗證 JavaScript:
var bCancel = false;
function validateForm(form) {
if (bCancel) return true; // 取消時跳過驗證
return validateRequired(form) && validateMaxLength(form) ...;
}
若 Action 未處理取消邏輯,Cancel 鍵效果等同 Submit!
public class MyAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
if (isCancelled(request)) {
return mapping.findForward("cancel"); // 導向取消頁面
}
// 正常業務邏輯
return mapping.findForward("success");
}
}
// Action.java
protected boolean isCancelled(HttpServletRequest request) {
return request.getAttribute(Globals.CANCEL_KEY) != null;
}
Globals.CANCEL_KEY = "org.apache.struts.action.CANCEL"。
關鍵在 processPopulate():
protected void processPopulate(HttpServletRequest request, HttpServletResponse response,
ActionForm form, ActionMapping mapping) throws ServletException {
// ... 填充表單屬性 ...
// 檢測 Cancel 按鈕
if (request.getParameter(Constants.CANCEL_PROPERTY) != null ||
request.getParameter(Constants.CANCEL_PROPERTY_X) != null) {
request.setAttribute(Globals.CANCEL_KEY, Boolean.TRUE);
}
}
Constants.CANCEL_PROPERTY = "org.apache.struts.taglib.html.CANCEL",與 Cancel 標籤產生的 name 屬性完全一致。
org.apache.struts.taglib.html.CANCELActionServlet.process() → RequestProcessor.process()processPopulate() 偵測到參數 → request.setAttribute(Globals.CANCEL_KEY, Boolean.TRUE)processValidate() 發現 CANCEL_KEY 存在 → 跳過表單驗證isCancelled(request) → 返回 true → 導向取消頁面isCancelled()Constants.CANCEL_PROPERTY_X 處理圖片型提交按鈕(<input type="image">)產生的 name.x/name.y 參數