SpringMVC——ResponseBody響應json數據

導入jquery文件

在SpringMVC工程的webapp目錄下創建js文件夾,用於存放jquery.js文件。
但是在springmvc中導入js等靜態文件時,會被DispatcherServlet攔截,從而導致不能被使用。因而首先需要在SpringMVC工程的配置文件中設置靜態資源不進行攔截

配置靜態資源不被攔截:mvc:resources標籤

屬性 功能
location 表示webapp目錄下的static包下的所有文件目錄,此文件目錄不攔截
mapping 表示以/static開頭的所有請求路徑,通過此屬性自動尋找配置文件

在配置文件中配置靜態資源不攔截

    
    <!--設置靜態資源不攔截 
        該配置作用:DispatcherServlet不會攔截以/static開頭的所有請求路徑
                    並當作靜態資源進行處理
    -->
    <mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
    <mvc:resources mapping="/css/**" location="/css/"/>
    <mvc:resources mapping="/images/**" location="/images"/>

異步請求獲取請求體數據

編寫jsp代碼

<%@page contentType="text/html; charset=UTF-8" language="java"  isELIgnored="false" %>

<html>
    <head>
        <title>requestMapping的使用</title>
        <script src="js/jquery-3.4.1.min.js"></script>
        <script>
            //頁面加載
            $(function () {
                //綁定button的點擊事件
                $("#testJson").click(function () {
                    $.ajax({
                        url:"${pageContext.request.contextPath}/testJson",
                        contentType:"application/json;charset=utf-8",
                        data:'{"id":1,"name":"testJson","money":1000}',
                        dateType:"json",
                        type:"post",
                        success:function (data) {
                            alert(data);
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <!--測試Ajax異步請求-->
        <input id="testJson" type="button" value="測試ajax請求json和響應json"/>
    </body>
</html>

編寫Controller代碼

package com.liang.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestJsonController {
     
     /**
     * 獲取請求體的數據
     * @param body
     */
    @RequestMapping(path = "/testJson")
    public void testJson(@RequestBody  String body){
        System.out.println("testJson方法執行了...");
        System.out.println(body);
    }
}

將獲取到的請求體數據轉換爲javaBean對象

導入所需jar
SpringMVC默認用MappingJacksonHttpMessageConverter對json數據進行轉換。需要導入響應的jar

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.11.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.11.1</version>
    </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.11.1</version>
    </dependency>

修改Controller代碼

package com.liang.controller;

import com.liang.domain.Account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestJsonController {

    /**
     * 獲取請求體的數據,並轉化爲javaBean數據
     * @param account
     */
    @RequestMapping(path = "/testJson")
    public void testJson(@RequestBody Account account){
        System.out.println("testJson方法執行了...");
        System.out.println(account);
    }
}

Account實體類代碼

package com.liang.domain;

import java.io.Serializable;

/**
 * 賬戶實體類
 */
public class Account implements Serializable {

    private Integer id;
    private String name;
    private Float money;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Float getMoney() {
        return money;
    }

    public void setMoney(Float money) {
        this.money = money;
    }

    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

將JavaBean對象轉化爲json數據,直接響應

修改jsp代碼

<%@page contentType="text/html; charset=UTF-8" language="java"  isELIgnored="false" %>

<html>
    <head>
        <title>requestMapping的使用</title>
        <script src="js/jquery-3.4.1.min.js"></script>
        <script>
            //頁面加載
            $(function () {
                //綁定button的點擊事件
                $("#testJson").click(function () {
                    $.ajax({
                        url:"${pageContext.request.contextPath}/testJson",
                        contentType:"application/json;charset=utf-8",
                        data:'{"id":1,"name":"testJson","money":1000}',
                        dateType:"json",
                        type:"post",
                        success:function (data) {
                            alert(data.id+" : "+data.name+" : "+data.money);
                        }
                    });
                });
            });
        </script>
    </head>
    <body>
        <!--測試Ajax異步請求-->
        <input id="testJson" type="button" value="測試ajax請求json和響應json"/>
    </body>
</html>

修改Controller代碼

package com.liang.controller;

import com.liang.domain.Account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestJsonController {

    /**
     * 獲取請求體的數據,並轉化爲javaBean數據
     * @param account
     */
    @RequestMapping(path = "/testJson")
    public @ResponseBody Account testJson(@RequestBody Account account){
        System.out.println("testJson方法執行了...");
        System.out.println(account);
        account.setMoney(9999f);
        return account;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章