Struts 2 基於攔截器機制,以 Filter 為核心控制器。本文記錄從建立專案到運行第一個 Action 的完整步驟。
web.xml<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>
註:Struts 2.3+ 使用 StrutsPrepareAndExecuteFilter;2.5+ 為 StrutsPrepareAndExecuteFilter (同名但包路徑不同)。
位置:src/struts.xml (Classpath 根目錄)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"https://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="helloworld" class="com.example.HelloWorldAction">
<result>/result.jsp</result>
</action>
</package>
</struts>
package com.example;
import com.opensymphony.xwork2.ActionSupport;
public class HelloWorldAction extends ActionSupport {
@Override
public String execute() throws Exception {
System.out.println("執行 Action");
return SUCCESS; // 對應 struts-default 中定義的 "success" 結果
}
}
<%@ page contentType="text/html;charset=UTF-8" %>
<html><body>
This is result.jsp!
</body></html>
https://localhost:8080/專案名/helloworld.action

ActionSupport (實作 Action 介面、提供預設 execute()、支援驗證/國際化)dispatcher (轉發),可指定 redirect、chain、stream 等namespace + action name 組成訪問路徑