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

Struts 2 註解驅動開發全攻略:Action、結果、攔截器、驗證、類型轉換零配置

     編輯:Java 相關知識

Struts 2 註解零配置開發完整實戰手冊

Struts 2 通過約定優於配置 + 註解驅動,徹底擺脫冗長的 struts.xml。本文系統梳理 Action 映射、結果視圖、攔截器鏈、驗證規則、類型轉換五大註解體系。

核心依賴 (Maven)

<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-convention-plugin</artifactId>
    <version>2.5.30</version>
</dependency>
<!-- 核心依賴自動傳遞:xwork, ognl, freemarker, javassist 等 -->

Action 註解體系

註解作用關鍵屬性
@Namespace定義命名空間value="/admin"
@Action映射 URL 到方法value="login", results={@Result...}
@Actions同一類多個 Actionvalue={@Action(...), @Action(...)}
@Result定義單個結果視圖name="success", location="/jsp/home.jsp", type="dispatcher"
@Results定義多個結果集合value={@Result(...), @Result(...)}
@ResultPath結果視圖根路徑value="/WEB-INF/content"

完整 Action 示例

@Namespace("/user")
@ResultPath("/WEB-INF/jsp")
@Results({
    @Result(name="success", location="profile.jsp"),
    @Result(name="input", location="login.jsp"),
    @Result(name="json", type="json", params={"root", "user"})
})
public class UserAction extends ActionSupport {
    private User user;
    
    @Action(value="login", 
        results={@Result(name="success", type="redirectAction", location="profile")})
    public String login() {
        if (userService.authenticate(user.getUsername(), user.getPassword())) {
            return SUCCESS;
        }
        return INPUT;
    }
    
    @Action("profile")
    public String profile() { return SUCCESS; }
    
    @Action(value="api/user", results=@Result(name="success", type="json"))
    public String apiUser() { return SUCCESS; }
    
    // Getter/Setter 省略
}

攔截器註解 (AOP 風格)

public class SecureAction extends ActionSupport {
    @Before
    public void checkAuth() throws AuthenticationException {
        if (!SecurityUtils.isLoggedIn()) throw new AuthenticationException();
    }
    
    @After
    public void auditLog() { AuditLogger.log(ActionContext.getContext()); }
    
    @BeforeResult
    public void prepareViewData() { /* 裝配頁面數據 */ }
    
    @Action("secure")
    public String execute() { return SUCCESS; }
}

執行順序:@Before -> Action 方法 -> @BeforeResult -> 結果視圖渲染 -> @After

驗證註解體系 (JSR-303 風格)

註解驗證規則關鍵屬性
@RequiredStringValidator非空字符串trim=true, message="用戶名必填"
@RequiredFieldValidator非空對象fieldName="user", message="用戶對象必填"
@IntRangeFieldValidator整數範圍min="18", max="100", message="年齡18-100"
@DoubleRangeFieldValidator浮點數範圍minInclusive="0.01", maxInclusive="9999.99"
@DateRangeFieldValidator日期範圍min="2000-01-01", max="2024-12-31"
@EmailValidator郵箱格式message="郵箱格式錯誤"
@UrlValidatorURL 格式
@RegexFieldValidator正則表達式expression="^1[3-9]\\d{9}$", message="手機號錯誤"
@StringLengthFieldValidator字符串長度minLength="6", maxLength="20", trim=true
@ExpressionValidatorOGNL 表達式expression="password == confirmPassword"
@Validations分組多規則requiredStrings={@RequiredStringValidator(...)}
@CustomValidator自定義驗證器type="myValidator", fieldName="field"

驗證實戰示例

public class RegisterAction extends ActionSupport {
    private String username, password, email, phone;
    
    @Validations(
        requiredStrings = {
            @RequiredStringValidator(fieldName="username", message="用戶名必填", trim=true),
            @RequiredStringValidator(fieldName="password", message="密碼必填")
        },
        stringLengthFields = {
            @StringLengthFieldValidator(fieldName="username", minLength="3", maxLength="16")
        },
        regexFields = {
            @RegexFieldValidator(fieldName="email", expression="^[\\w.-]+@[\\w.-]+\\.\\w+$", message="郵箱格式錯誤"),
            @RegexFieldValidator(fieldName="phone", expression="^1[3-9]\\d{9}$", message="手機號格式錯誤")
        }
    )
    @Action(value="register", results={
        @Result(name="success", location="welcome.jsp"),
        @Result(name="input", location="register.jsp")
    })
    public String register() {
        userService.register(username, password, email, phone);
        return SUCCESS;
    }
}

類型轉換註解

@Conversion // 類級別啟用類型轉換
public class OrderAction extends ActionSupport {
    @CreateIfNull(value=true)  // 自動實例化集合
    @Element(value=OrderItem.class) // 集合泛型類型
    private List items;
    
    @Key(value=Long.class)     // Map Key 類型
    @KeyProperty(value="id")   // Map Key 來源屬性
    private Map productMap;
    
    @TypeConversion(rule=ConversionRule.COLLECTION, converter="com.my.DateConverter")
    public void setCreateTime(Date time) { this.createTime = time; }
}

web.xml 極簡配置

<filter>
    <filter-name>struts2</filter-name>
    <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    <init-param>
        <param-name>struts.devMode</param-name>
        <param-value>true</param-value>
    </init-param>
    <init-param>
        <param-name>struts.convention.action.packages</param-name>
        <param-value>com.myapp.action</param-value> 
    </init-param>
</filter>

約定優於配置規則

  • Action 類命名:`*Action`、實現 `Action` 接口、或註解 `@Action`
  • 結果視圖:默認 `dispatcher` 類型,路徑 `/WEB-INF/content/{namespace}/{actionName}{resultName}.jsp`
  • 方法映射:默認 `execute()`,可通過 `@Action` 指定 `method` 屬性
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved