雖然 SSH 框架盛行,但初學者仍應從 Struts 基礎入手,一步一腳印建立扎實基礎。
Model 2 架構透過單一控制元件接收請求,該元件可自行處理或委派給其他元件,再將回應生成任務交給適當視圖元件。Front Controller 是實現此需求的經典模式之一。

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

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)。
public abstract class Action {
public abstract String process(HttpServletRequest req, HttpServletResponse res);
}
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 配置檔以提高彈性。
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 案例講解。