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

善用 ActionForward 優化 Struts 應用程式

     編輯:Java 相關知識

Servlet 中常用 RequestDispatcher.forward() 轉向資源。Struts 提供 ActionForward 替代,無需手動建立 Dispatcher 呼叫 forward,簡化流程。

ActionForward 在 Action 中的使用

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() 固定配置。

Login 範例重構

所有 RequestDispatcher.forward() 呼叫改為 return new ActionForward("/target.jsp"),程式碼更簡潔直觀。ActionForward 功能豐富,深受歡迎。下一部分將介紹 ActionMapping 進一步優化。

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