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

Struts2 核心配置與類型轉換完整指南

     編輯:Java 程式設計入門

一、Action 配置中的預設值解析

在 Struts2 的 struts.xml 中定義 Action 時,若省略特定屬性,框架會採用預設值。理解這些預設行為能簡化配置:

  • class 屬性:若未指定,預設為 ActionSupport。
  • method 屬性:若未指定,預設執行 execute() 方法。
  • result 的 name 屬性:若未指定,預設值為 success。
<package name="csdn" namespace="/test" extends="struts-default">
    <action name="helloworld" class="cn.csdn.action.HelloWorldAction" method="execute">
        <result name="success">/WEB-INF/page/hello.jsp</result>
    </action>
</package>

二、Result 類型詳解:轉發與重定向

Struts2 提供多種結果類型,對應不同的視圖跳轉需求:

  • dispatcher(預設):請求轉發,保留 request 作用域數據。
  • redirect:重定向,request 數據會丟失,適用於防止表單重複提交。
  • redirectAction:重定向到另一個 Action,支援跨命名空間跳轉。
  • plainText:直接輸出原始文件內容(如 JSP 源碼),常用於調試。

redirectAction 進階用法

<!-- 同包下 -->
<result type="redirectAction">helloworld</result>

<!-- 跨命名空間 -->
<result type="redirectAction">
    <param name="actionName">helloworld</param>
    <param name="namespace">/test</param>
</result>

<!-- 支援 OGNL 表達式傳參 -->
<result type="redirect">view.jsp?id=${id}</result>

三、全域 Result:多 Action 共享視圖

當多個 Action 需要返回相同視圖(如通用錯誤頁),可在 <package> 下定義 <global-results>:

<package name="demo" extends="struts-default">
    <global-results>
        <result name="message">/message.jsp</result>
    </global-results>
</package>

四、Action 屬性依賴注入

Struts2 支援在配置文件中透過 <param> 為 Action 屬性注入值,前提是屬性必須提供 setter 方法:

public class HelloWorldAction {
    private String savePath;
    // getter/setter 省略
}

<action name="helloworld" class="cn.csdn.action.HelloWorldAction">
    <param name="savePath">/images</param>
    <result name="success">/WEB-INF/page/hello.jsp</result>
</action>

五、自定義請求副檔名

預設 Struts2 處理 *.action 請求,可透過常量 struts.action.extension 修改:

<constant name="struts.action.extension" value="do"/>
<!-- 多副檔名用逗號分隔 -->
<constant name="struts.action.extension" value="do,go"/>

六、常量配置與載入優先順序

常量可在 struts.xml 或 struts.properties 中定義,建議集中在 struts.xml 管理。載入順序(後者覆蓋前者):

  1. struts-default.xml
  2. struts-plugin.xml
  3. struts.xml
  4. struts.properties
  5. web.xml

七、常用常量速查表

常量名稱用途建議值(開發/生產)
struts.i18n.encoding預設編碼集UTF-8
struts.action.extension請求副檔名do,action
struts.serve.static.browserCache靜態資源瀏覽器快取false / true
struts.configuration.xml.reload配置檔熱重載true / false
struts.devMode開發模式(詳細錯誤)true / false
struts.ui.theme預設 UI 主題simple
struts.objectFactorySpring 整合工廠spring
struts.enable.DynamicMethodInvocation動態方法調用開關false(安全)
struts.multipart.maxSize上傳檔案大小限制10701096 (10MB)

八、模組化配置:拆分 struts.xml

大型專案建議按模組拆分配置檔,再用 <include> 引入:

<struts>
    <include file="struts-user.xml"/>
    <include file="struts-order.xml"/>
</struts>

九、動態方法調用與通配符映射

1. 動態方法調用(! 符號)

// URL: /test/helloworld!other.action
public String other() { ... }

可透過 struts.enable.DynamicMethodInvocation=false 關閉以提升安全性。

2. 通配符映射(* 符號)

<action name="helloworld_*" class="cn.csdn.action.HelloWorldAction" method="{1}">
    <result name="success">/WEB-INF/page/hello.jsp</result>
</action>
// 訪問 other():/test/helloworld_other.action

十、請求參數接收方式

基本類型自動映射

Action 定義同名屬性 + setter,Struts2 自動將請求參數轉型賦值。

// URL: /test/view.action?id=78
private Integer id; // 自動轉換 String → Integer

複合類型(對象圖)映射

請求參數用 對象.屬性 格式,框架自動實例化對象並填充屬性。

// URL: /test/view.action?product.id=78
private Product product; // 自動 new Product() 並 setId(78)

十一、類型轉換核心機制

HTTP 參數本質是字串,但業務邏輯需要豐富類型(日期、數字、集合、JavaBean)。Struts2 內建強大的類型轉換器,基於 OGNL 實現雙向轉換。

內建轉換支援

  • 基本類型:boolean, char, int, long, double, float 及其包裝類
  • 日期:java.util.Date(依 Locale SHORT 格式)
  • 集合:陣列、List、Map(元素預設為 String,可自定義轉換器)

自定義類型轉換器開發

繼承 ognl.DefaultTypeConverter,實現 convertValue(Map context, Object value, Class toType):

  • context:轉換上下文
  • value:待轉換值(字串陣列,對應 getParameterValues())
  • toType:目標類型,據此判斷轉換方向(String→Object 或 Object→String)
public class MyDateConverter extends DefaultTypeConverter {
    @Override
    public Object convertValue(Map<String, Object> context, Object value, Class toType) {
        if (toType == Date.class) {
            // String[] → Date
            String[] vals = (String[]) value;
            return DateFormat.getDateInstance(DateFormat.SHORT).parse(vals[0]);
        } else if (toType == String.class) {
            // Date → String
            return DateFormat.getDateInstance(DateFormat.SHORT).format((Date) value);
        }
        return null;
    }
}

註冊方式:在 xwork-conversion.properties 或 Action 同包下的 ActionName-conversion.properties 指定轉換器類名。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved