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

Struts2 通過 Action 返回 JSON 數據完整指南

     編輯:Java 綜合教學

Struts2 通過 Action 返回 JSON 數據完整指南

Struts2 整合 JSON 極為簡單,但配置細節容易遺忘。本文記錄核心步驟與關鍵點,作為快速參考手冊。

一、核心依賴

必須引入 struts2-json-plugin,版本與 Struts2 核心版本對應(示例為 2.3.24):

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

二、Action 類編寫

package com.mz.action;

import com.mz.entity.User;
import com.opensymphony.xwork2.ActionSupport;

public class JsonAction extends ActionSupport {
    private User user;

    public String execute() {
        user = new User();
        user.setId(123);
        user.setUsername("Irasel");
        return SUCCESS;
    }

    public User getUser() { return user; }
    public void setUser(User user) { this.user = user; }
}

User 實體類僅包含 id、username 及對應 Getter/Setter。

三、關鍵配置:struts.xml

<package name="resultJson" namespace="/" extends="json-default">
    <action name="resultJson" class="com.mz.action.JsonAction">
        <result name="success" type="json">
            <param name="root">user</param>
        </result>
    </action>
</package>

⚠️ 核心注意點(重要說三遍)

root 參數值必須為 OGNL 表達式,對應 Action 中的屬性名(此處為 "user"),不可更改參數名 "root"!

四、前端調用示例 (jQuery AJAX)

$.ajax({
    type: "GET",
    contentType: "application/json",
    url: "<%=request.getContextPath()%>/resultJson",
    dataType: "json",
    success: function(data) {
        console.log("返回 JSON:", data);
        // 輸出:{id: 123, username: "Irasel"}
    },
    error: function() { alert("請求失敗"); }
});

五、驗證結果

啟動 Tomcat,訪問 https://localhost:8080/你的項目/resultJson,瀏覽器將直接顯示 JSON 字符串:

JSON 返回結果截圖

六、常見坑點總結

  • 缺少 json-plugin:啟動拋出 NoClassDefFoundError 或結果類型找不到。
  • root 寫錯:寫成字段名而非 OGNL 表達式,或漏寫 root 參數,導致返回空對象 {}。
  • 繼承包錯誤:Package 必須 extends="json-default",否則 type="json" 不識別。
  • GET/POST 不匹配:Action 方法默認支持 POST,若前端用 GET 需在 @Action 或 XML 配置 method="GET"。

七、擴展:接收前端 JSON 數據

若需接收 JSON 請求體,Action 方法添加 @RequestBody 註解(需 Struts2 REST 插件或 Spring MVC 整合),或在攔截器中解析 ServletInputStream。純 Struts2 環境下,表單提交仍以 application/x-www-form-urlencoded 為主。

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