Struts2 <result> 的 type 屬性決定視圖渲染方式。本文系統整理 12 種內建 Result 類型、對應類、適用場景、關鍵參數,並重點解析 redirect vs redirectAction 差異、redirectAction 參數傳遞、JSON 插件集成等實戰技巧。
| Type | 實現類 | 用途 | 關鍵參數 |
|---|---|---|---|
| chain | ActionChainResult | Action 鏈,保留 Request 屬性 | - |
| dispatcher | ServletDispatcherResult | 默認,轉發到 JSP/頁面 | location (默認) |
| freemarker | FreemarkerResult | 渲染 FreeMarker 模板 | location |
| httpheader | HttpHeaderResult | 控制 HTTP 狀態碼/頭 | status, headers |
| stream | StreamResult | 輸出 InputStream(文件下載/AJAX) | inputName, contentType, contentDisposition, bufferSize |
| velocity | VelocityResult | 渲染 Velocity 模板 | location |
| xslt | XSLTResult | XML/XSLT 轉換 | location, stylesheet |
| plainText | PlainTextResult | 直接輸出文本(源碼查看) | location, charSet |
| redirect | ServletRedirectResult | 重定向 URL,Request 丟失 | location, parse |
| redirectAction | ServletActionRedirectResult | 重定向到 Action,Request 丟失 | actionName, namespace, suppressEmptyParameters |
| redirect-action | ServletActionRedirectResult | 同 redirectAction(別名) | 同上 |
| json | JSONResult | 序列化 Action 屬性為 JSON | includeProperties, excludeProperties, root |
| 維度 | redirect | redirectAction |
|---|---|---|
| 後綴 | 需 .action | 無需後綴 |
| 命名空間 | 可跨命名空間 | 僅同一命名空間 |
| 參數傳遞 | 手動拼接 URL | 原生支持 OGNL/EL 表達式 |
<!-- redirect 需完整路徑 -->
<result name="success" type="redirect">viewTask.action</result>
<!-- redirectAction 僅需 Action 名 -->
<result name="success" type="redirectAction">viewTask</result>
<action name="enterpreinfo" class="preinfoBusinessAction" method="enterPreinfoSub">
<result name="success" type="redirectAction">
showpreinfo?preinfo.order_number=${preinfo.order_number}&preinfo.company_name=${preinfo.company_name}
</result>
<result name="error" type="redirect">
<param name="location">/error.jsp</param>
</result>
</action>
注意:XML 中 & 必須轉義為 &,否則解析報錯。
<package name="struts2" extends="json-default" namespace="/">
<action name="login" class="loginAction" method="login">
<result type="json">
<param name="includeProperties">success,result</param>
</result>
</action>
<action name="main" class="loginAction" method="main">
<result name="main">/index.jsp</result>
</action>
</package>
Action 需提供 success、result 屬性及 Getter,includeProperties 以逗號分隔指定序列化字段。
dispatcher (默認)streamredirectActionjson (需 struts2-json-plugin)chain