Resumen de aprendizaje de Spring MVC (7): interacción de datos JSON en Spring MVC

Uno, descripción general de JSON

JSON (JavaScript Object Notation, JS Object Notation) es un formato de intercambio de datos ligero. Como XML, JSON es un formato de datos basado en texto sin formato. Tiene dos estructuras de datos: estructura de objeto y estructura de matriz.

1. Estructura de objeto

La estructura del objeto comienza con "{" y termina con "}". La parte central se compone de 0 o más pares clave / valor separados por "," en inglés, y la clave y el valor están separados por ":" en inglés. La estructura gramatical de la estructura del objeto es la siguiente:

{     clave1:     valor1 , clave2: valor2,     ... }



Entre ellos, la clave debe ser de tipo String, el valor puede ser String, Number, Object, Array y otros tipos de datos. Por ejemplo, un objeto de persona contiene información como nombre, contraseña, edad, etc., utilizando la representación JSON de la siguiente manera:

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



2. Estructura de datos

La estructura de la matriz comienza con "[" y termina con "]", y la parte central consta de una lista de 0 o más valores separados por "," en inglés. La estructura gramatical de la estructura de la matriz es la siguiente:

{     valor1,     valor2,     ... }



Las dos estructuras de datos anteriores (objeto, matriz) también se pueden combinar para formar una estructura de datos más compleja. Por ejemplo, un objeto de estudiante contiene objetos sno, sname, hobby y college, y su representación JSON es la siguiente:

{     "sno": "202102030001",     "sname": "Zhang San",     "hobby": ["ping pong", "fútbol"],     "universidad": {         "cname": "Universidad de Tsinghua",         "ciudad" : "Beijing"     } }







Sitio web de verificación en línea para formato de datos JSON: https://www.bejson.com/

Dos, caso de interacción de datos JSON

(1) Importe el paquete del tarro.

<!-- 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) Cree un directorio de archivos js en webapp, e introduzca jquery y luego 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>

Si necesita eliminar la intercepción de img y css por dispaterServlet en el desarrollo posterior, agregue:

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

Cabe señalar aquí: el directorio js está debajo de la aplicación web.

(4) Crear usuario de clase de entidad.

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) Realice la interacción de datos JSON en la página 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) Cree un método para procesar la solicitud.

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

La anotación @RequestBody en el método se usa para vincular los datos en formato JSON en el cuerpo de la solicitud de interfaz al usuario del parámetro formal, y la anotación @ResponseBody se usa para devolver directamente el objeto Person (cuando se devuelve un objeto POJO, se convierte a datos en formato JSON de forma predeterminada para la respuesta).

(7) Procedimiento de prueba

Supongo que te gusta

Origin blog.csdn.net/weixin_47382783/article/details/113577296
Recomendado
Clasificación