Struts 2.0.6 GA 釋出標誌著 WebWork 正式併入 Apache 主線。本文記錄從零搭建 Struts 2 + Spring 整合項目的完整步驟,涵蓋依賴管理、核心配置、動作開發與最佳實踐,作為遷移與新項目啟動的參考模板。
webapp/
├── src/
│ ├── main/
│ │ ├── java/tutorial/HelloWorld.java
│ │ ├── resources/struts.xml
│ │ └── webapp/
│ │ ├── WEB-INF/
│ │ │ ├── web.xml
│ │ │ ├── applicationContext.xml
│ │ │ └── lib/ (見下表)
│ │ └── helloWorld.jsp
│ └── test/
| 類別 | JAR (Struts 2.0.6) |
|---|---|
| 核心 | struts2-core-2.0.6.jar, xwork-2.0.0.jar, struts2-api-2.0.6.jar |
| 模板引擎 | freemarker-2.3.8.jar |
| 表達式語言 | ognl-2.6.9.jar |
| 日誌 | commons-logging-1.1.jar |
| Spring 整合 | struts2-spring-plugin-2.0.6.jar |
| Spring | spring.jar (2.5.x) |
<web-app version="2.4" xmlns="https://java.sun.com/xml/ns/j2ee">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
<beans xmlns="https://www.springframework.org/schema/beans">
<bean id="helloWorld" class="tutorial.HelloWorld" />
</beans>
<struts>
<constant name="struts.objectFactory" value="spring" />
<package name="default" extends="struts-default" namespace="/">
<action name="HelloWorld" class="helloWorld"> <!-- 此處寫 Spring bean id -->
<result>/helloWorld.jsp</result>
</action>
</package>
</struts>
package tutorial;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorld extends ActionSupport {
public static final String MESSAGE = "Struts 2 + Spring 整合成功!";
private String message;
public String execute() {
setMessage(MESSAGE);
return SUCCESS;
}
// getter/setter 省略
}
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head><title>Hello World</title></head>
<body>
<h2><s:property value="message" /></h2>
</body>
</html>
StrutsPrepareAndExecuteFilter (2.1.3+ 替代 FilterDispatcher) 初始化 StrutsObjectFactorystruts.objectFactory=spring 觸發 SpringObjectFactory 載入WebApplicationContext.getBean("helloWorld")execute() → 結果視圖渲染| 現象 | 原因 | 解決 |
|---|---|---|
| ClassNotFound: FilterDispatcher | Struts 2.1.3+ 已移除 | 改用 org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter |
| Action 依賴注入失效 (null) | struts.xml 中 class 寫成全限定類名 | 必須寫 Spring bean id (如 "helloWorld") |
| OGNL 表達式報錯 | Getter/Setter 命名不規範 | 嚴格遵循 JavaBean 規範,或使用 @Action 註解 (2.1+) |
@Action, @Result) 替代 XMLstruts.xml,逐步引入 struts2-convention-plugin 實現約定優於配置完整 Maven 項目代碼見附件,包含 Jetty 插件配置,mvn jetty:run 即時運行驗證。