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

Struts 2 回傳 JSON 完整配置指南:root、includeProperties、excludeProperties 詳解

     編輯:Java 程式設計入門

核心問題:預設序列化整個 Action

Struts 2 JSON 外掛預設會序列化 Action 所有 getter 方法回傳值。若需精確控制輸出內容,必須配置 root、includeProperties、excludeProperties 參數。

基礎配置範例

<package name="api" namespace="/api" extends="json-default">
    <action name="getUser" class="com.action.UserAction" method="getUserByName">
        <!-- 僅序列化 userInfo 物件 -->
        <result name="success" type="json">
            <param name="root">userInfo</param>
        </result>
    </action>
</package>

參數完整對照表

參數用途範例值說明
root指定序列化根物件userInfo只輸出該屬性物件,忽略 Action 其他屬性
includeProperties包含指定屬性 (正則)user\.id, user\.name支援 OGNL 路徑表示法,\d+ 表示 List 索引
excludeProperties排除指定屬性 (正則)user\.password, .*\.secret排除優先級高於包含
ignoreHierarchy是否忽略繼承層級屬性falsefalse 會序列化父類屬性,預設 true
noCache防止瀏覽器快取true加入 Cache-Control: no-cache 標頭
contentType指定回應 Content-Typeapplication/json;charset=UTF-8預設已正確設定

進階配置場景

1. 只輸出 List 特定欄位

<result name="success" type="json">
    <param name="includeProperties">
        userList\[\d+\]\.id, userList\[\d+\]\.username, userList\[\d+\]\.email
    </param>
</result>

對應 Action 屬性:List<User> userList,僅輸出每個 User 的 id、username、email。

2. 排除敏感欄位

<result name="success" type="json">
    <param name="excludeProperties">
        .*\.password, .*\.secretKey, .*\.token
    </param>
</result>

使用正則表達式批量排除所有物件的敏感欄位。

3. 序列化父類屬性

<result name="success" type="json">
    <param name="root">data</param>
    <param name="ignoreHierarchy">false</param>
</result>

ignoreHierarchy=false 允許序列化父類定義的屬性 (預設 true 忽略)。

4. 多結果類型切換

<action name="user" class="com.action.UserAction">
    <result name="json" type="json">
        <param name="root">user</param>
    </result>
    <result name="page">/user/detail.jsp</result>
</action>

Action 根據請求決定回傳 json 或 page 結果。

Action 端實作範例


public class UserAction extends ActionSupport {
    private User userInfo;           // 單一物件
    private List<User> userList;     // 列表
    private String totalCount;       // 分頁總數
    private int start, limit;        // 分頁參數

    // getter/setter 略

    public String getUserByName() {
        userInfo = userService.findByName(getName());
        return SUCCESS;
    }

    public String listUsers() {
        userList = userService.findPage(start, limit);
        totalCount = String.valueOf(userService.count());
        return SUCCESS;
    }
}

常見錯誤與除錯

  1. 輸出空物件 {}:確認 root 屬性名稱拼寫、getter 方法存在、屬性非 null
  2. List 輸出為空陣列 []:檢查 includeProperties 正則語法,\d+ 需在 XML 中轉義為 \\d+
  3. 中文亂碼:確認 contentType 含 charset=UTF-8、專案編碼一致、資料庫連線編碼正確
  4. 循環引用 StackOverflow:雙向關聯實體需加 @JsonIgnore 或配置 excludeProperties 排除反向引用

JSON 外掛依賴 (Maven)

<dependency>
    <groupId>org.apache.struts</groupId>
    <artifactId>struts2-json-plugin</artifactId>
    <version>2.5.28</version>
</dependency>

需在 struts.xml 繼承 json-default 套件:extends="json-default"

總結

Struts 2 JSON 輸出控制核心在於 root 定義根節點、includeProperties 白名單、excludeProperties 黑名單 三大參數組合。掌握 OGNL 路徑表示法 (含 \\d+ 列表索引)、正則轉義規則、繼承層級控制,即可精準輸出 API 所需 JSON 結構,避免洩露敏感資料與傳輸冗餘欄位。

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