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

Spring4 + SpringMVC 實現 JSON 數據雙向交互完整教程

     編輯:Java 綜合教學

Spring4 + SpringMVC 實現 JSON 數據雙向交互完整教程

Spring 4 內置對 Jackson 的深度整合,配合 @ResponseBody、@RequestBody 輕鬆實現 JSON 自動序列化/反序列化。本文記錄從 JAR 依賴、前端 AJAX、Controller 配置到實體類的完整流程。

一、Maven 核心依賴 (Spring 4 專用)

Spring 3 需手動引入 jackson-core/asl/mapper,Spring 4 僅需 jackson-databind(傳遞依賴 core/annotations):

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version> <!-- 與 Spring 4.3.x 兼容 -->
</dependency>
<!-- SpringMVC 核心 -->
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.2.RELEASE</version>
</dependency>

Maven 依賴結構

二、前端頁面:雙向 AJAX 交互

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <script src="jquery.min.js"></script>
    <script src="jquery.json-2.2.min.js"></script> <!-- 表單轉 JSON -->
    <script>
        // 1. 頁面加載:GET 獲取後端列表數據
        $(function() {
            $.ajax({
                type: "GET",
                contentType: "application/json",
                url: "<%=request.getContextPath()%>/easyui/list.do",
                dataType: "json",
                success: function(data) {
                    if (data && data.success === "true") {
                        $("#info").html("共 " + data.total + " 條數據。<br/>");
                        $.each(data.data, function(i, item) {
                            $("#info").append("編號:" + item.id + ",姓名:" + item.username + ",年齡:" + item.age + "<br/>");
                        });
                    }
                },
                error: function() { alert("加載失敗"); }
            });
        });

        // 2. 表單提交:POST 發送 JSON 到後端
        // 表單序列化為 JSON 對象
        $.fn.serializeObject = function() {
            var o = {}, a = this.serializeArray();
            $.each(a, function() {
                if (o[this.name]) {
                    if (!o[this.name].push) o[this.name] = [o[this.name]];
                    o[this.name].push(this.value || '');
                } else { o[this.name] = this.value || ''; }
            });
            return o;
        };

        $("#submit").click(function() {
            var jsonStr = $.toJSON($("#form").serializeObject()); // 需 jquery.json.js
            alert("發送 JSON: " + jsonStr);

            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: "<%=request.getContextPath()%>/easyui/add.do",
                data: jsonStr,
                dataType: "json",
                success: function(data) { alert("新增成功:" + data.success); },
                error: function() { alert("提交失敗"); }
            });
        });
    </script>
</head>
<body>
    <div id="info"></div>
    <form id="form">
        編號:<input name="id" value="12"/>
        姓名:<input name="username" value="走走走"/>
        年齡:<input name="age" value="44"/>
        <input type="button" id="submit" value="提交"/>
    </form>
</body>
</html>

三、後端 Controller

@Controller
@RequestMapping("/easyui")
public class JsonController {

    /** GET:返回列表數據,自動序列化為 JSON */
    @RequestMapping(value = "/list", method = RequestMethod.GET, consumes = "application/json")
    @ResponseBody
    public Map<String, Object> getUserList() {
        List<UserModel> list = new ArrayList<>();
        UserModel u = new UserModel();
        u.setId("1"); u.setUsername("sss"); u.setAge(222);
        list.add(u);

        Map<String, Object> map = new HashMap<>();
        map.put("total", "1");
        map.put("data", list);
        map.put("success", "true");
        return map; // Spring 自動轉 JSON
    }

    /** POST:接收前端 JSON,自動反序列化為 UserModel */
    @RequestMapping(value = "/add", method = RequestMethod.POST, consumes = "application/json")
    @ResponseBody
    public Map<String, String> addUser(@RequestBody UserModel model) {
        System.out.println("接收到: " + model.getId() + " " + model.getUsername() + " " + model.getAge());
        Map<String, String> map = new HashMap<>();
        map.put("success", "true");
        return map;
    }
}

四、實體類 UserModel

package com.zlay.pojo;

public class UserModel {
    private String id;
    private String username;
    private int age;
    // Getter/Setter 省略
}

五、關鍵註解詳解

註解作用關鍵屬性
@ResponseBody將返回值直接寫入 HTTP Response Body,經 HttpMessageConverter 轉 JSON無
@RequestBody將 HTTP Request Body 內容綁定到參數對象,經 HttpMessageConverter 解析 JSONrequired=true
consumes="application/json"限制請求 Content-Type,僅處理 JSON 請求值為 MIME 類型
produces="application/json"指定響應 Content-Type(@ResponseBody 默認已設置)值為 MIME 類型

六、JSON 工具庫對比

  • jQuery.json.js:$.toJSON(obj)、$.evalJSON(str),輕量、依賴 jQuery
  • json2.js:原生 JSON.stringify()、JSON.parse(),標準化、無依賴,推薦現代項目使用
  • Jackson (後端):Spring 默認 HttpMessageConverter,高性能、支持流式、注解驅動(@JsonProperty、@JsonIgnore 等)

七、常見問題排查

  1. 406 Not Acceptable:缺少 Jackson JAR 或版本不匹配,檢查 jackson-databind 依賴
  2. 415 Unsupported Media Type:請求頭 Content-Type 不是 application/json,或 Controller 缺少 consumes 屬性
  3. 字段為 null:JSON key 與 Java 字段名不一致,添加 @JsonProperty("keyName") 或確保駝峰命名一致
  4. 日期格式化:全局配置 ObjectMapper 設置 setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"))
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved