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

Struts 簡單案例教學 (一):Front Controller 模式核心解析

     編輯:Java 相關知識

前言

雖然 SSH 框架盛行,但初學者仍應從 Struts 基礎入手,一步一腳印建立扎實基礎。

Front Controller 模式核心概念

Model 2 架構透過單一控制元件接收請求,該元件可自行處理或委派給其他元件,再將回應生成任務交給適當視圖元件。Front Controller 是實現此需求的經典模式之一。

Front Controller 架構圖

問題與解決

問題:所有功能集中在單一 Servlet 會導致控制器臃腫。

解決方案:

  1. 多個 Front Controller 分工處理不同領域
  2. Command and Controller (命令與控制器) 模式:將具體處理邏輯封裝至獨立命令元件

Command and Controller 架構圖

Front Controller 基礎框架實作

public class FrontController extends HttpServlet {
    protected void processRequest(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextView);
        dispatcher.forward(req, res);
    }
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException { processRequest(req, res); }
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException { processRequest(req, res); }
}

processRequest 統一處理 GET/POST,執行業務邏輯後轉發至視圖 (JSP)。

Command and Controller 策略實作

1. 定義命令介面

public abstract class Action {
    public abstract String process(HttpServletRequest req, HttpServletResponse res);
}

2. 請求類型通訊映射

Servlet 映射:

<servlet>
    <servlet-name>FrontController</servlet-name>
    <servlet-class>com.wxhx.controller.FrontController</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>FrontController</servlet-name>
    <url-pattern>/controller/*</url-pattern>
</servlet-mapping>

從路徑資訊取得命令名稱,透過 ActionHelper 映射至具體類別:

public class ActionHelper {
    private static HashMap actions = new HashMap();
    static {
        actions.put("Login", "com.sample.LoginAction");
    }
    public static Action getAction(String name) {
        Action action = null;
        try {
            Class c = Class.forName((String) actions.get(name));
            action = (Action) c.newInstance();
        } catch (Exception e) { e.printStackTrace(); }
        return action;
    }
}

建議將映射外部化至 XML 配置檔以提高彈性。

3. 整合至 FrontController

public class FrontController extends HttpServlet {
    protected void processRequest(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        String actionName = req.getPathInfo().substring(1); // 取得路徑如 /controller/Login -> Login
        Action action = ActionHelper.getAction(actionName);
        String nextView = action.process(req, res);
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextView);
        dispatcher.forward(req, res);
    }
    // doGet/doPost 略...
}

結語

以上即為簡易 Front Controller 框架核心實作。Struts 正是此模式的成熟擴充實現。下一部分將進入具體 Struts 案例講解。

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