Struts2 是基於 MVC 模式的 Web 框架,核心職責:將視圖與業務邏輯解耦。它是 WebWork 與 Struts1 合併演變而來,底層攔截器鏈 + OGNL 表達式 + 結果類型系統構成靈活的請求處理管道。
struts-2.x.x-all.zip,解壓取 lib 下 jar)https://host:port/app/namespace/actionName.actionweb.xml 中 StrutsPrepareAndExecuteFilter 攔截請求struts.xml,按 namespace + action name 匹配 Actionexecute() 方法執行業務邏輯"success")匹配 <result>WEB-INF/lib必備:struts2-core, ognl, freemarker, javassist, commons-lang, commons-fileupload, commons-io 等。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"https://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="front" namespace="/" extends="struts-default">
<action name="index" class="com.myservice.web.Action02">
<result name="success">/Index.jsp</result>
</action>
</package>
</struts>
devMode=true:開發模式,修改配置/類無需重啟熱加載namespace="/":對應 URL 根路徑class:Action 完整類名result name="success":對應 Action 返回值package com.myservice.web;
import com.opensymphony.xwork2.ActionSupport;
public class Action02 extends ActionSupport {
@Override
public String execute() throws Exception {
System.out.println("Action02.execute() 執行了");
return "success";
}
}
為什麼繼承 ActionSupport?
Action 接口(提供 execute()、SUCCESS 等常量)validate()、getText()、addActionError() 等豐富輔助方法ModelDriven、Preparable 等接口,擴展性強<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><title>Struts2 Demo</title></head>
<body>
<h1>明日復明日,明日何其多</h1>
</body>
</html>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
https://localhost:8080/項目名/index.action控制台輸出 Action02.execute() 執行了,頁面顯示「明日復明日...」即成功。
| 方式 | 代碼 | 評價 |
|---|---|---|
| POJO + execute() | public String execute() { return "success"; } | 最簡單,但無輔助功能 |
| 實現 Action 接口 | implements Action { public String execute() {...} } | 標準規範,需自行定義常量 |
| 繼承 ActionSupport (推薦) | extends ActionSupport { @Override public String execute() {...} } | 功能最全,開發效率最高 |
ClassNotFoundException: StrutsPrepareAndExecuteFilter → jar 包缺失或版本衝突Unable to load configuration → struts.xml 路徑錯誤(必須在 classpath 根目錄)或 DTD 解析失敗(離線需複製 dtd 文件)No result defined for action ... and result success → <result> name 與 Action 返回值不匹配404 Not Found → URL 寫錯(漏 .action、namespace 不對)或 web.xml 過濾器映射錯誤Struts2 入門核心三件套:web.xml 配置過濾器、struts.xml 映射 Action、Action 類繼承 ActionSupport。掌握「請求 → 過濾器 → 配置匹配 → 攔截器 → Action → 結果視圖」完整鏈路,後續學習攔截器、OGNL、類型轉換、驗證、文件上傳、JSON 插件等進階特性將事半功倍。