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;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章