Servlet 中常用 RequestDispatcher.forward() 轉向資源。Struts 提供 ActionForward 替代,無需手動建立 Dispatcher 呼叫 forward,簡化流程。
execute 方法回傳 ActionForward 物件:
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
// 原寫法:
// RequestDispatcher rd = request.getRequestDispatcher("/mainMenu.jsp");
// rd.forward(request, response);
// return null;
// 新寫法:
return new ActionForward("/mainMenu.jsp");
}
ActionForward()ActionForward(String path) — 最常用ActionForward(String path, boolean redirect)ActionForward(String name, String path, boolean redirect)ActionForward(String name, String path, boolean redirect, boolean contextRelative)redirect=true 執行重導向(較 forward 慢,預設 false)。contextRelative 指定路徑相對 context 而非 module。name 可用於查找特定 ActionMapping 關聯實例。
getPath()/setPath()、getRedirect()/setRedirect()、getName()/setName()、getContextRelative()/setContextRelative()、toString()、freeze() 固定配置。
所有 RequestDispatcher.forward() 呼叫改為 return new ActionForward("/target.jsp"),程式碼更簡潔直觀。ActionForward 功能豐富,深受歡迎。下一部分將介紹 ActionMapping 進一步優化。