Spring MVC学習の概要(7):SpringMVCでのJSONデータの相互作用

1つ、JSONの概要

JSON(JavaScript Object Notation、JSオブジェクト表記)は軽量のデータ交換フォーマットです。XMLと同様に、JSONはプレーンテキストに基づくデータ形式です。オブジェクト構造と配列構造の2つのデータ構造があります。

1.オブジェクト構造

オブジェクト構造は「{」で始まり「}」で終わります。中央部分は英語の「、」で区切られた0個以上のキーと値のペアで構成され、キーと値は英語の「:」で区切られます。オブジェクト構造の文法構造は次のとおりです。

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



その中で、キーは文字列型である必要があり、値は文字列、数値、オブジェクト、配列、およびその他のデータ型である可能性があります。たとえば、personオブジェクトには、次のようにJSON表現を使用して、名前、パスワード、年齢などの情報が含まれています。

{     "名前": "トム"、     "暗殺者": "123456"、     "年齢":40 }



2.データ構造

配列構造は「[」で始まり「]」で終わり、中央部分は英語の「、」で区切られた0個以上の値のリストで構成されます。配列構造の文法構造は次のとおりです。

{     value1、     value2、     ... }



上記の2つの(オブジェクト、配列)データ構造を組み合わせて、より複雑なデータ構造を形成することもできます。たとえば、studentオブジェクトにはsno、sname、hobby、collegeオブジェクトが含まれ、そのJSON表現は次のとおりです。

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







JSONデータ形式のオンライン検証Webサイト:https//www.bejson.com/

2、JSONデータの相互作用の場合

(1)jarパッケージをインポートします。

<!-- 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)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)webappの下にjsファイルディレクトリを作成し、jqueryを導入してから、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>

後続の開発でdispaterServletによるimgとcssのインターセプトを削除する必要がある場合は、以下を追加します。

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

ここで注意する必要があります:jsディレクトリはwebappの下にあります。

(4)エンティティクラス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)ページindex.jspでJSONデータの相互作用を実行します。

<%--
  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)リクエストを処理するメソッドを作成します。

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

メソッドの@RequestBodyアノテーションは、フロントエンドリクエストボディのJSON形式データを仮パラメーターuserにバインドするために使用され、@ ResponseBodyアノテーションは、Personオブジェクトを直接返すために使用されます(POJOオブジェクトが返されると、応答のためにデフォルトでJSON形式のデータに変換されます)。

(7)試験手順

おすすめ

転載: blog.csdn.net/weixin_47382783/article/details/113577296