Spring MVC learning summary (7): JSON data interaction in Spring MVC

One, JSON overview

JSON (JavaScript Object Notation, JS object notation) is a lightweight data exchange format. Like XML, JSON is a data format based on plain text. It has two data structures: object structure and array structure.

1. Object structure

The object structure starts with "{" and ends with "}". The middle part is composed of 0 or more key/value pairs separated by English ",", and the key and value are separated by English ":". The grammatical structure of the object structure is as follows:

{
    key1:value1,
    key2:value2,
    ...
}

Among them, key must be String type, value can be String, Number, Object, Array and other data types. For example, a person object contains information such as name, password, age, etc., using JSON representation as follows:

{
    "name":"tom",
    "assword":"123456",
    "age":40
}

2. Data structure

The array structure starts with "[" and ends with "]", and the middle part consists of a list of 0 or more values ​​separated by English ",". The syntax structure of the array structure is as follows:

{
    value1,
    value2,
    ...
}

The above two (object, array) data structures can also be combined to form a more complex data structure. For example, a student object contains sno, sname, hobby, and college objects, and its JSON representation is as follows:

{     "sno":"202102030001",     "sname":"Zhang San",     "hobby":["ping pong","football"],     "college":{         "cname":"Tsinghua University",         "city" :"Beijing"     } }







Online verification website for JSON data format: https://www.bejson.com/

Two, JSON data interaction case

(1) Import the jar package.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind --><dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.10.0</version>
  </dependency>

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

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.10.0</version>
    </dependency>
  </dependencies>

(2) Configure web.xml.

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
  <display-name>Archetype Created Web Application</display-name>
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <!--  指定Spring MVC配置文件的位置    -->
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--
      Servlet一般都是在第一次访问时才加载,此配置表明容器在启动时就立即加载Servlet
      load-on-startup:服务器启动时创建对象,值越小优先级越高,越先创建对象
    -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <!--
        /*和/都是拦截所有请求
        /*:拦截到所有的请求,包括jsp,如果不写,默认值
        /:拦截除*.jsp之外的所有请求
     -->
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
  <!--   字符编码过滤器  -->
  <filter>
    <filter-name>CharacterEncodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <!--  encoding:指定一个具体的字符集  -->
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF-8</param-value>
    </init-param>
    <!-- forceEncoding:处理 response中的字符编码  -->
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>

  </filter>
  <filter-mapping>
    <filter-name>CharacterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>


</web-app>

(3) Create a js file directory under webapp, and introduce jquery, and then configure springmvc.xml.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--  配置注解扫描的包  -->
    <context:component-scan base-package="com.yht.example1"></context:component-scan>
    <!--  配置视图解析器 :拼接页面地址 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--    访问路径的前缀    -->
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <!--    文件后缀    -->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!-- 使用resources过滤掉不需要dispatcherservlet的资源(即静态资源,例如css、js、html、images)。
        在使用resources时必须使用annotation-driven,否则resources元素会阻止任意控制器被调用 -->
    <!-- 允许js目录下的所有文件可见 -->
    <mvc:resources location="/js/" mapping="/js/**" />

</beans>

If you need to remove the interception of img and css by the dispaterServlet in the subsequent development, add:

    <!-- 允许css目录下的所有文件可见 -->
    <mvc:resources location="/css/" mapping="/css/**" />
    <!-- 允许img目录下的所有文件可见 -->
    <mvc:resources location="/img/" mapping="/img/**" />

It should be noted here: the js directory is under the webapp.

(4) Create entity class User.

public class User {
    private String name;
    private String password;
    private Integer age;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;

    public String getName() {
        return name;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", password='" + password + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                '}';
    }
}

(5) Perform JSON data interaction on the page index.jsp.

<%--
  Created by IntelliJ IDEA.
  User: com.yht
  Date: 2021/2/2
  Time: 20:55
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script src="js/jquery-3.5.1.js"></script>
    <script>
        $(function () {
            $("#btn").click(function () {
                var name = $("#name").val();
                var password = $("#password").val();
                var age = $("#age").val();
                $.ajax({
                    //请求路径
                    url : "${pageContext.request.contextPath }/user/testJson",
                    //请求类型
                    type : "post",
                    //data表示发送的数据
                    data : JSON.stringify({
                        name : name,
                        password : password,
                        age : age,
                    }), //定义发送请求的数据格式为JSON字符串
                    contentType : "application/json;charset=utf-8",
                    //定义回调响应的数据格式为JSON字符串,该属性可以省略
                    dataType : "json",
                    //成功响应的结果
                    success : function(data) {
                        if (data != null) {
                            alert("后台返回的用户的用户名:" + data.name + ",密码:" + data.password
                                + ", 年龄:" + data.age );
                        }
                    }
                });
            });
        });
    </script>
</head>
<body>
<form method="post">
    姓名:<input type="text" name="name" id="name"><br>
    密码:<input type="text" name="password" id="password"><br>
    年龄:<input type="text" name="age" id="age"><br>
    <button id="btn">提交</button>
</form>
</body>
</html>

(6) Create a method to process the request.

    /**
     * 接收页面请求的JSON参数,并返回JSON格式的结果
     */
    @RequestMapping("/testJson")
    @ResponseBody
    public User testJson(@RequestBody User user) {
        // 打印接收的JSON格式数据
        System.out.println("接收到的User : " + user);
        // 返回JSON格式的响应
        return user;
    }

The @RequestBody annotation in the method is used to bind the JSON format data in the front-end request body to the formal parameter user, and the @ResponseBody annotation is used to directly return the Person object (when a POJO object is returned, it is converted to JSON format data by default for response).

(7) Test procedure

Guess you like

Origin blog.csdn.net/weixin_47382783/article/details/113577296