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

Struts 2 Result 參數完整指南:類型、配置、動態導向與最佳實踐

     編輯:Java 相關知識

前言

Result 是 Struts 2 處理請求的第二階段:根據業務邏輯結果選擇視圖。本文全面解析 Result 類型體系、參數配置、動態導向機制、全局結果集與實戰最佳實踐。

一、Result 類型體系(struts-default.xml 內建)

類型名實現類用途
dispatcherServletDispatcherResult預設,轉發到 JSP/頁面
redirectServletRedirectResult客戶端重導向 (302)
redirectActionServletActionRedirectResult重導向到另一 Action
chainActionChainResultAction 鏈轉發(共享請求)
streamStreamResult文件下載、二進制流輸出
jsonJSONResultAJAX 返回 JSON(需 json-plugin)
freemarkerFreemarkerResultFreeMarker 模板渲染
velocityVelocityResultVelocity 模板渲染
xsltXSLTResultXML/XSLT 轉換
plainTextPlainTextResult原始文本輸出(如源碼)
httpheaderHttpHeaderResult控制 HTTP 狀態碼/頭

二、基礎配置語法

1. 最簡配置(預設 dispatcher、預設 name="success")

<action name="hello" class="com.example.HelloAction">
    <result>/hello.jsp</result>
</action>

2. 完整配置

<action name="hello" class="com.example.HelloAction">
    <result name="success" type="dispatcher">
        <param name="location">/hello.jsp</param>
        <param name="parse">true</param> <!-- 解析 OGNL 表達式 -->
    </result>
    <result name="error" type="dispatcher">/error.jsp</result>
    <result name="input" type="dispatcher">/input.jsp</result>
</action>

3. 多結果配置

<action name="user" class="com.example.UserAction">
    <result>/user_list.jsp</result>
    <result name="create">/user_form.jsp</result>
    <result name="edit">/user_form.jsp</result>
    <result name="delete" type="redirectAction">user</result>
    <result name="error">/error.jsp</result>
</action>

三、核心參數詳解

1. location(所有類型通用)

目標資源路徑。支援 OGNL 表達式(parse="true" 時):

<result name="success" type="dispatcher">
    <param name="location">/user/${userId}/detail.jsp</param>
</result>

2. parse(dispatcher 類型)

true(預設):解析 location 中的 OGNL 表達式。false:按字面路徑處理,效能略高。

3. redirect/redirectAction 專用參數

參數說明
parse是否解析 OGNL(預設 true)
anchor錨點,如 #section1
encode是否 URL 編碼參數(預設 true)

4. stream 類型專用參數(文件下載)

<result name="download" type="stream">
    <param name="contentType">application/octet-stream</param>
    <param name="inputName">inputStream</param> <-- Action 的 getInputStream() -->
    <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>
    <param name="bufferSize">4096</param>
</result>

5. json 類型專用參數(struts2-json-plugin)

<result name="ajax" type="json">
    <param name="root">dataMap</param> <-- 序列化的根對象(需有 getter) -->
    <param name="includeProperties">userList\.[^,]+</param> <-- 正則包含 -->
    <param name="excludeProperties">password,secret</param> <-- 排除敏感字段 -->
    <param name="ignoreHierarchy">false</param>
    <param name="encodeAsUTF8">true</param>
</result>

四、動態結果導向(Runtime Result Resolution)

1. Action 屬性驅動

public class DynamicAction {
    private String nextPage; // 對應 getter

    public String execute() {
        // 業務邏輯決定導向
        if (isAdmin) nextPage = "/admin/dashboard.jsp";
        else nextPage = "/user/home.jsp";
        return "dynamic";
    }

    public String getNextPage() { return nextPage; }
}
<action name="dynamic" class="com.example.DynamicAction">
    <result name="dynamic" type="dispatcher">${nextPage}</result>
</action>

2. redirectAction 動態參數

<action name="goto" class="com.example.GotoAction">
    <result name="go" type="redirectAction">
        <param name="actionName">${targetAction}</param>
        <param name="namespace">${targetNamespace}</param>
        <param name="id">${entityId}</param>
    </result>
</action>

五、全局結果集

<package name="base" extends="struts-default">
    <global-results>
        <result name="error">/common/error.jsp</result>
        <result name="login" type="redirectAction">LoginAction!input</result>
        <result name="noPermission" type="redirectAction">AccessDeniedAction</result>
    </global-results>
</package>

所有繼承 base 的包自動擁有。Action 可同名覆蓋。

六、實戰最佳實踐

場景推薦 Result 類型關鍵配置
普通頁面跳轉dispatcher(預設)location 指向 JSP
表單提交後redirect / redirectActionPRG 模式,防重複提交
文件下載streaminputName、contentDisposition
AJAX 回調jsonroot、excludeProperties
多步驟流程chain共享 request 範圍數據
REST 風格 APIhttpheader + stream/json控制狀態碼、Content-Type

七、常見坑點

  • redirect 後 request 屬性丟失:需用 Session/Flash 暫存數據。
  • chain 導致死循環:Action A chain → B,B chain → A。檢查結果名稱邏輯。
  • stream 下載中文檔名亂碼:contentDisposition 中檔名需 URLEncoder.encode(fileName, "UTF-8")。
  • json 類型序列化循環引用:配置 excludeProperties 排除反向關聯,或使用 DTO。
  • 動態 location 為空:導致轉發到根目錄,驗證 Action 屬性非空。

八、總結

Struts 2 Result 機制靈活強大。掌握類型選擇、參數配置、動態導向、全局複用四大核心,即可應對 95% 的視圖導向場景。實戰中堅持:表單提交用 redirect、AJAX 用 json、下載用 stream、錯誤頁用 global-results,配置清晰、維護無憂。

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