14.Spring MVC JSON数据交互

我们知道,Spring MVC 在传递数据时,通常都需要对数据的类型和格式进行转换。而这些数据不仅可以常见的 String 类型,还可以是 JSON 等其他类型。

JSON 是近些年一种比较流行的数据格式,它与 XML 相似,也是用来存储数据的。但相较于 XML,JSON 数据占用的空间更小,解析速度更快。因此,使用 JSON 数据进行前后台的数据交互也是一种十分常见的手段。

本节将针对 Spring MVC 的 JSON 类型数据交互进行讲解。

JSON 概述

JSON(JavaScript Object Notation,JS 对象标记)是一种轻量级的数据交互格式。与 XML 一样,JSON 也是一种基于纯文本的数据格式。通过它,我们不仅能够传递 String、Number、Boolean 等简单类型的数据,还可以传递数组、Object 对象等复杂类型的数据。

JSON 支持 2 种数据结构,它们分别是对象结构和数组结构。

1. 对象结构

JSON 的对象结构以“{”开始,以“}”结束,中间则由 0 个或多个以英文的逗号(即“,”)分隔的 key/value 对构成。

对象结构的语法结构如下。

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


其中,key 必须为 String 类型,value 可以是 String、Number、Object、Array 等数据类型。

例如,一个 person 对象包含姓名、密码、年龄等信息,使用 JSON 的表示形式如下:

{
    "pname":"张三",
    "password":"123456",
    "page":40
}

2. 数组结构

JSON 的数组结构以“[”开始、以“]”结束,中间部分由 0 个或多个以英文的逗号(即“,”)分隔的值列表组成。

数组结构的语法结构如下:

{
    value1,
    value2,
    ...
}


例如,一个数组中包含了 String、Number、Boolean、null 多种类型的数据,使用 JSON 的数组结构表示形式如下。

[
    "c语言中文网",
    123456789,
    true,
    null
]


上述两种(对象、数组)数据结构也可以分别组合构成更加复杂的数据结构。

例如,一个 student 对象包含 sno、sname、hobby 和 college 等多个属性,其 JSON 表示形式如下。

{
    "sno":"201802228888",
    "sname":"张三",
    "hobby":[
        "篮球",
        "足球"
    ],
    "college":{
        "cname":"清华大学",
        "city":"北京",
        "code":100000
    }
}

JSON 数据转换

为了实现浏览器与控制器类之间的 JSON 数据交互,Spring MVC 提供了一个默认的 MappingJackson2HttpMessageConverter 类,来处理 JSON 格式请求和响应。通过它,我们既可以将 Java 对象转换为 JSON 数据,也可以将 JSON 数据转换为 Java 对象。

引入依赖包

想要使用 MappingJackson2HttpMessageConverter 对 JSON 数据进行转换,第一步就是要将 Jackson 的依赖包引入到 Spring MVC 项目中。

  • jackson-annotations-x.x.x.jar:JSON 转换的注解包
  • jackson-core-x.x.x.jar:JSON 转换的核心包
  • jackson-databind-x.x.x.jar:JSON 转换的数据绑定包


以上这些 Jackson 的开源依赖包都可以通过“https://mvnrepository.com/artifact/com.fasterxml.jackson.core”下载得到。

JSON 转换注解

Spring MVC 为我们提供了两个十分重要的与 JSON 格式转换相关的注解,它们分别是 @RequestBody 和 @ResponseBody。

注解 位置 说明
@RequestBody 方法的形参上 该注解用于将请求体中的数据绑定到控制器方法的形参上。
@ResponseBody 方法上 该注解用于将控制器方法的返回值,直接作为响应报文的响应体响应到
浏览器上。

示例 

下面我们通过一个实例,来演示下如何通过这两个注解对 JSON 进行转换。

1. 新建一个名为 springmvc-json-demo 的 Web 项目,并将 Spring MVC 和 Jackson 的依赖包引入到项目中,其 web.xml 配置如下。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
  5. version="4.0">
  6.  
  7. <!--请求和响应的字符串过滤器-->
  8. <filter>
  9. <filter-name>CharacterEncodingFilter</filter-name>
  10. <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  11. <init-param>
  12. <param-name>encoding</param-name>
  13. <param-value>UTF-8</param-value>
  14. </init-param>
  15. <init-param>
  16. <param-name>forceResponseEncoding</param-name>
  17. <param-value>true</param-value>
  18. </init-param>
  19. </filter>
  20. <filter-mapping>
  21. <filter-name>CharacterEncodingFilter</filter-name>
  22. <url-pattern>/*</url-pattern>
  23. </filter-mapping>
  24.  
  25. <!--来处理 PUT 和 DELETE 请求的过滤器-->
  26. <filter>
  27. <filter-name>HiddenHttpMethodFilter</filter-name>
  28. <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  29. </filter>
  30. <filter-mapping>
  31. <filter-name>HiddenHttpMethodFilter</filter-name>
  32. <url-pattern>/*</url-pattern>
  33. </filter-mapping>
  34.  
  35. <!-- 配置SpringMVC的前端控制器,对浏览器发送的请求统一进行处理 -->
  36. <servlet>
  37. <servlet-name>dispatcherServlet</servlet-name>
  38. <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  39. <!--配置 DispatcherServlet 的一个初始化参数:spring mvc 配置文件按的位置和名称-->
  40. <init-param>
  41. <param-name>contextConfigLocation</param-name>
  42. <param-value>classpath:springMVC.xml</param-value>
  43. </init-param>
  44.  
  45. <!--作为框架的核心组件,在启动过程中有大量的初始化操作要做
  46. 而这些操作放在第一次请求时才执行会严重影响访问速度
  47. 因此需要通过此标签将启动控制DispatcherServlet的初始化时间提前到服务器启动时-->
  48. <load-on-startup>1</load-on-startup>
  49. </servlet>
  50.  
  51. <servlet-mapping>
  52. <servlet-name>dispatcherServlet</servlet-name>
  53. <!--设置springMVC的核心控制器所能处理的请求的请求路径
  54. /所匹配的请求可以是/login或.html或.js或.css方式的请求路径
  55. 但是/不能匹配.jsp请求路径的请求-->
  56. <url-pattern>/</url-pattern>
  57. </servlet-mapping>
  58.  
  59. </web-app>


2. 在 src 目录下(类路径下)新建一个 Spring MVC 的配置文件 springMVC.xml,配置内容如下。

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4.        xmlns:context="http://www.springframework.org/schema/context"
  5.        xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.        xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans.xsd
  8.        http://www.springframework.org/schema/context
  9.        https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
  10.  
  11.     <!--开启组件扫描-->
  12.     <context:component-scan base-package="net.biancheng.c"></context:component-scan>
  13.  
  14.     <!-- 配置 Thymeleaf 视图解析器 -->
  15.     <bean id="viewResolver"
  16.           class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
  17.         <property name="order" value="1"/>
  18.         <property name="characterEncoding" value="UTF-8"/>
  19.         <property name="templateEngine">
  20.             <bean class="org.thymeleaf.spring5.SpringTemplateEngine">
  21.                 <property name="templateResolver">
  22.                     <bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
  23.                         <!-- 视图前缀 -->
  24.                         <property name="prefix" value="/WEB-INF/templates/"/>
  25.                         <!-- 视图后缀 -->
  26.                         <property name="suffix" value=".html"/>
  27.                         <property name="templateMode" value="HTML5"/>
  28.                         <property name="characterEncoding" value="UTF-8"/>
  29.                     </bean>
  30.                 </property>
  31.             </bean>
  32.         </property>
  33.     </bean>
  34.  
  35.     <!-- view-name:设置请求地址所对应的视图名称-->
  36.     <mvc:view-controller path="/products" view-name="product_list"></mvc:view-controller>
  37.     <!-- view-name:设置请求地址所对应的视图名称-->
  38.     <mvc:view-controller path="/" view-name="login"></mvc:view-controller>
  39.  
  40.     <!-- 当SpringMVC中设置任何一个view-controller时,其他控制器中的请求映射将全部失效,此时需要在SpringMVC的核心配置文件中设置开启mvc注解驱动的标签-->
  41.     <mvc:annotation-driven></mvc:annotation-driven>
  42.     <!--静态资源映射-->
  43.     <mvc:resources mapping="/js/" location="/js/**"></mvc:resources>
  44. </beans>


在 Spring MVC 的配置文件中,除了配置了组件扫描和视图解析器外,我们还配置如下两个元素:

  • <mvc:annotation-driven /> :Spring MVC 的注解驱动,配置会自动注册 RequestMappingHandlerMapping 和 RequestMappingHandlerAdapter 两个组件,为读写 JSON 数据提供支持。
  • <mvc:resources /> :静态资源访问映射,用于配置静态资源的访问路径。


<mvc:resources /> 中包含两个重要的属性:location 和 mapping,关于这两个属性的说明如下表。

属性 说明
location 该属性用于设置需要访问的本地静态资源文件的路径。
mapping 匹配静态资源全路径,其中“/**”表示文件夹及其子文文件夹下的某个具体文件。


除此之外,我们还可以在 Spring MVC 的配置文件中使用以下配置,将静态资源交给 Tomcat 提供的默认的 Servlet 进行处理,这样也可以实现 Spring MVC 项目中静态资源的访问。

  • <mvc:default-servlet-handler />

<mvc:resources /> 和 <mvc:default-servlet-handler /> 这两个标签配置都可以实现静态资源的映射,我们可以根据自身的需求自行选择。

3. 在 net.biancheng.c.bean 包下,创建一个名为 Product 的实体类,代码如下。

  1. package net.biancheng.c.bean;
  2.  
  3. import java.math.BigDecimal;
  4.  
  5. public class Product {
  6. private String productId;
  7. private String productName;
  8. private BigDecimal price;
  9. private Integer stock;
  10. private String introduction;
  11.  
  12. public String getIntroduction() {
  13. return introduction;
  14. }
  15.  
  16. public void setIntroduction(String introduction) {
  17. this.introduction = introduction;
  18. }
  19.  
  20. public String getProductId() {
  21. return productId;
  22. }
  23.  
  24. public void setProductId(String productId) {
  25. this.productId = productId;
  26. }
  27.  
  28. public String getProductName() {
  29. return productName;
  30. }
  31.  
  32. public void setProductName(String productName) {
  33. this.productName = productName;
  34. }
  35.  
  36. public BigDecimal getPrice() {
  37. return price;
  38. }
  39.  
  40. public void setPrice(BigDecimal price) {
  41. this.price = price;
  42. }
  43.  
  44. public Integer getStock() {
  45. return stock;
  46. }
  47.  
  48. public void setStock(Integer stock) {
  49. this.stock = stock;
  50. }
  51.  
  52. @Override
  53. public String toString() {
  54. return "Product{" +
  55. "productId=" + productId +
  56. ", productName='" + productName + '\'' +
  57. ", price=" + price +
  58. ", stock=" + stock +
  59. ", introduction='" + introduction + '\'' +
  60. '}';
  61. }
  62. }


4. 在 net.biancheng.c.controller 包下,创建一个名为 ProductController 的 Controller 类,代码如下。

  1. package net.biancheng.c.controller;
  2.  
  3. import net.biancheng.c.bean.Product;
  4. import net.biancheng.c.dao.ProductDao;
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.web.bind.annotation.*;
  7.  
  8. import javax.annotation.Resource;
  9. import java.util.List;
  10.  
  11. /**
  12. * @author C语言中文网
  13. */
  14. @Controller
  15. public class ProductController {
  16.  
  17. @Resource
  18. private ProductDao productDao;
  19.  
  20. /**
  21. * 查看或回显商品信息,get:查看商品信息 update:为修改页回显的商品信息
  22. */
  23. @ResponseBody
  24. @RequestMapping("/product/{productId}")
  25. public Product getProduct(@PathVariable("productId") String productId) {
  26. Product product = productDao.getProductById(productId);
  27. return product;
  28. }
  29.  
  30. /**
  31. * 新增商品
  32. *
  33. * @param product
  34. * @return
  35. */
  36. @ResponseBody
  37. @RequestMapping(value = "/product", method = RequestMethod.POST)
  38. public Product addProduct(@RequestBody Product product) {
  39. productDao.addProduct(product);
  40. return product;
  41. }
  42.  
  43. /**
  44. * 删除指定的商品
  45. *
  46. * @param productId
  47. * @return
  48. */
  49. @RequestMapping(value = "/product", method = RequestMethod.DELETE)
  50. public String deleteProduct(String productId) {
  51. productDao.deleteProduct(productId);
  52. return "redirect:/products";
  53. }
  54.  
  55. /**
  56. * 获取商品列表
  57. *
  58. * @return
  59. */
  60. @ResponseBody
  61. @RequestMapping("/getProductList1")
  62. public List<Product> getProductList1() {
  63. List productList = productDao.getProductList();
  64. return productList;
  65. }
  66.  
  67. /**
  68. * 修改商品信息
  69. *
  70. * @param product
  71. * @return
  72. */
  73. @RequestMapping(value = "/edit-product")
  74. public String updateProduct(Product product) {
  75. productDao.updateProduct(product);
  76. return "redirect:/products";
  77. }
  78. }


5. 在 net.biancheng.c.dao 包下,创建一个名为 ProductDao 的类,代码如下。

  1. package net.biancheng.c.dao;
  2.  
  3. import net.biancheng.c.bean.Product;
  4. import org.springframework.stereotype.Repository;
  5.  
  6. import java.math.BigDecimal;
  7. import java.util.*;
  8.  
  9. @Repository
  10. public class ProductDao {
  11.  
  12. private static Map<String, Product> products = null;
  13.  
  14. static {
  15. products = new HashMap<String, Product>();
  16. Product product = new Product();
  17. product.setProductId("1");
  18. product.setProductName("茅台");
  19. product.setPrice(new BigDecimal(9999));
  20. product.setStock(1000);
  21. product.setIntroduction("茅台酒是大曲酱香型酒的鼻祖。");
  22.  
  23. Product product1 = new Product();
  24. product1.setProductId("2");
  25. product1.setProductName("五粮液");
  26. product1.setPrice(new BigDecimal(8888));
  27. product1.setStock(1000);
  28. product1.setIntroduction("五粮液,四川省宜宾市特产,中国国家地理标志产品。");
  29.  
  30. Product product2 = new Product();
  31. product2.setProductId("3");
  32. product2.setProductName("信阳毛尖");
  33. product2.setPrice(new BigDecimal(7777));
  34. product2.setStock(1000);
  35. product2.setIntroduction("信阳毛尖又称豫毛峰,属绿茶类,是中国十大名茶之一,也是河南省著名特产之一;");
  36.  
  37. Product product3 = new Product();
  38. product3.setProductId("4");
  39. product3.setProductName("深州大蜜桃");
  40. product3.setPrice(new BigDecimal(6666));
  41. product3.setStock(1000);
  42. product3.setIntroduction("深州蜜桃,河北省深州市特产,中国国家地理标志产品。");
  43.  
  44. products.put(product.getProductId(), product);
  45. products.put(product1.getProductId(), product1);
  46. products.put(product2.getProductId(), product2);
  47. products.put(product3.getProductId(), product3);
  48. }
  49.  
  50. /**
  51. * 获取商品列表
  52. *
  53. * @return
  54. */
  55. public List getProductList() {
  56. List productList = new ArrayList();
  57. Set<String> keys = products.keySet();
  58. for (String key : keys) {
  59. Product product = products.get(key);
  60. productList.add(product);
  61. }
  62. return productList;
  63. }
  64.  
  65. /**
  66. * 根据商品 id 获取商品信息
  67. *
  68. * @param productId
  69. * @return
  70. */
  71. public Product getProductById(String productId) {
  72. return products.get(productId);
  73. }
  74.  
  75. /**
  76. * 新增商品
  77. *
  78. * @param product
  79. */
  80. public void addProduct(Product product) {
  81. products.put(product.getProductId(), product);
  82. }
  83.  
  84. /**
  85. * 修改商品
  86. *
  87. * @param product
  88. */
  89. public void updateProduct(Product product) {
  90. products.put(product.getProductId(), product);
  91. }
  92.  
  93. /**
  94. * 删除商品
  95. *
  96. * @param productId
  97. */
  98. public void deleteProduct(String productId) {
  99. products.remove(productId);
  100. }
  101. }


6. 在 webapp 下新建一个 js 目录,并将 jquery-3.6.0.min.js 存放到该目录下。

7. 在 webapp/WEB-INF 下新建一个 templates 目录,并在该目录下创建一个 product_list.html,代码如下。

  1. <!DOCTYPE html>
  2. <html lang="en" xmlns:th="http://www.thymeleaf.org">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <!--引入 jquery-->
  7. <script type="text/javaScript"
  8. src="../../js/jquery-3.6.0.min.js " th:src="@{/js/jquery-3.6.0.min.js}"></script>
  9. </head>
  10. <body>
  11.  
  12. <table th:border="1" th:cellspacing="0" th:cellpadding="0" style="text-align: center;">
  13. <thead>
  14. <th>商品id</th>
  15. <th>商品名</th>
  16. <th>商品价格</th>
  17. <th>商品库存</th>
  18. <th>操作</th>
  19. </thead>
  20. <tbody th:id="tb">
  21. </tbody>
  22. </table>
  23. <br>
  24.  
  25. <!-- 作用:通过超链接控制表单的提交,将post请求转换为delete请求 -->
  26. <form id="delete_form" method="post" th:action="@{/product}">
  27. <!-- HiddenHttpMethodFilter要求:必须传输_method请求参数,并且值为最终的请求方式 -->
  28. <input type="hidden" name="_method" value="delete"/>
  29. <input type="hidden" name="productId" th:id="form-id"/>
  30. </form>
  31.  
  32. <button id="btn">新增商品</button>
  33.  
  34. <div id="addWindow">
  35. <label id="x" style="position: absolute;top:2px;left: 95%;font-size: 25px;">x</label>
  36. <h4>新增商品</h4>
  37. <form th:action="@{/product}" method="post">
  38. <table id="table-box" style="margin: auto">
  39. <tr>
  40. <td>商品 ID:</td>
  41. <td><input type="text" id="productId" name="productId" required></td>
  42. </tr>
  43. <tr>
  44. <td>商品名称:</td>
  45. <td><input type="text" id="productName" name="productName" required></td>
  46. </tr>
  47. <tr>
  48. <td>商品价格:</td>
  49. <td><input type="text" id="price" name="price" required></td>
  50. </tr>
  51. <tr>
  52. <td>商品库存:</td>
  53. <td><input type="text" id="stock" name="stock" required></td>
  54. </tr>
  55. <tr>
  56. <td>商品简介:</td>
  57. <td><textarea id="introduction" name="introduction" rows="10" cols="30"></textarea><br></td>
  58. </tr>
  59. <tr>
  60. <td colspan="2" align="center"><input id="addPro" type="submit" value="新增商品">
  61. <input type="reset" id="reset" value="重置">
  62. </td>
  63. </tr>
  64. </table>
  65. </form>
  66. </div>
  67. <div id="backGround"></div>
  68.  
  69. <div id="editWindow">
  70. <label id="ex" style="position: absolute;top:2px;left: 95%;font-size: 25px;">x</label>
  71. <h4>修改商品</h4>
  72. <form th:action="@{/edit-product}" id="edit-form" method="post">
  73. <table id="edit-form-table" style="margin: auto">
  74. <tr>
  75. <td>商品 ID:</td>
  76. <td><input id="e-productId" type="text" name="productId" readonly></td>
  77. </tr>
  78. <tr>
  79. <td>商品名称:</td>
  80. <td><input id="e-productName" type="text" name="productName" required></td>
  81. </tr>
  82. <tr>
  83. <td>商品价格:</td>
  84. <td><input id="e-price" type="text" name="price" required></td>
  85. </tr>
  86. <tr>
  87. <td>商品库存:</td>
  88. <td><input id="e-stock" type="text" name="stock" required></td>
  89. </tr>
  90. <tr>
  91. <td>商品简介:</td>
  92. <td><textarea id="e-introduction" name="introduction" rows="10" cols="30"></textarea>
  93. </td>
  94. </tr>
  95. <tr>
  96. <td colspan="2" align="center"><input type="submit" value="修改商品信息"></td>
  97. </tr>
  98. </table>
  99. </form>
  100. </div>
  101. <div id="edit-backGround"></div>
  102.  
  103. <div id="lookWindow">
  104. <label id="lx" style="position: absolute;top:2px;left: 95%;font-size: 25px;">x</label>
  105. <h4>商品详情</h4>
  106. <table style="margin: auto">
  107. <tr>
  108. <td>商品 ID:</td>
  109. <td id="l-productId"></td>
  110. </tr>
  111. <tr>
  112. <td>商品名称:</td>
  113. <td id="l-productName"></td>
  114. </tr>
  115. <tr>
  116. <td>商品价格:</td>
  117. <td id="l-price"></td>
  118. </tr>
  119. <tr>
  120. <td>商品库存:</td>
  121. <td id="l-stock"></td>
  122. </tr>
  123. <tr>
  124. <td>商品简介:</td>
  125. <td id="l-introduction"></td>
  126. </tr>
  127. </table>
  128. </div>
  129.  
  130. <div id="look-backGround"></div>
  131.  
  132. <script type="text/javaScript">
  133. $(document).ready(function () {
  134. //点击新增商品,弹出新增商品弹窗
  135. $("#btn").click(function () {
  136. $("#addWindow").slideDown(300);
  137. $("#backGround").show();
  138. });
  139.  
  140. $("#x").click(function () {
  141. $("#addWindow").slideUp(300);
  142. $("#backGround").hide();
  143. $("#reset").trigger("click")
  144. });
  145.  
  146. $("#ex").click(function () {
  147. $("#editWindow").slideUp(300);
  148. $("#edit-backGround").hide();
  149. });
  150.  
  151. $("#lx").click(function () {
  152. $("#lookWindow").slideUp(300);
  153. $("#look-backGround").hide();
  154. });
  155. $("#look-close").click(function () {
  156. $("#lookWindow").slideUp(300);
  157. $("#look-backGround").hide();
  158. });
  159.  
  160. /**
  161. * 填完数据后,点击新增商品弹窗中的 新增商品 按钮,执行新增商品操作
  162. */
  163. $("#addPro").click(function () {
  164. add();
  165. $("#addWindow").slideUp(300);
  166. $("#backGround").hide();
  167. $("#reset").trigger("click")
  168. });
  169.  
  170. $("#editPro").click(function () {
  171. $("#edit-form").submit();
  172. $("#editWindow").slideUp(300);
  173. $("#edit-backGround").hide();
  174. $("#e-reset").trigger("click")
  175. });
  176. });
  177.  
  178. $(function () {
  179. $.ajax({
  180. //请求路径
  181. url: "http://localhost:8080/springmvc-json-demo/getProductList1",
  182. //请求类型
  183. type: "get",
  184. //定义发送请求的数据格式为JSON字符串
  185. contentType: "application/json;charset=utf-8",
  186. //定义回调响应的数据格式为JSON字符串,该属性可以省略
  187. dataType: "json",
  188. //成功响应的结果
  189. success: function (data) {
  190. if (data != null) {
  191. var html = "";
  192. for (var i = 0; i < data.length; i++) {
  193. var product = data[i];
  194. html += "<tr>" +
  195. "<td>" + product.productId + "</td>" +
  196. "<td>" + product.productName + "</td>" +
  197. "<td>" + product.price + "</td>" +
  198. "<td>" + product.stock + "</td>" +
  199. "<td><button onclick='lookPage(" + product.productId + ")'>查看商品</button>" +
  200. "<button onclick='editPage(" + product.productId + ")';>修改商品</button>" +
  201. "<button onclick='deletePro(" + product.productId + ")';>删除商品</button></td>" +
  202. "</tr>"
  203. }
  204. $("#tb").html(html);
  205. }
  206. }
  207. });
  208. })
  209.  
  210. function deletePro(productId) {
  211. var b = confirm("确认删除id 为" + productId + " 的商品?");
  212. if (b) {
  213. var delete_form = $("#delete_form");
  214. $("#form-id").val(productId);
  215. delete_form.submit();
  216. }
  217. }
  218.  
  219. //执行新增商品操作
  220. function add() {
  221. var productId = $("#productId").val();
  222. var productName = $("#productName").val();
  223. var price = $("#price").val();
  224. var introduction = $("#introduction").val();
  225. var stock = $("#stock").val();
  226.  
  227. $.ajax({
  228. //请求路径
  229. url: "http://localhost:8080/springmvc-json-demo/product",
  230. //请求类型
  231. type: "post",
  232. data: JSON.stringify({
  233. productId: productId,
  234. productName: productName,
  235. price: price,
  236. stock: stock,
  237. introduction: introduction
  238. }), //定义发送请求的数据格式为JSON字符串
  239. contentType: "application/json;charset=utf-8",
  240. //定义回调响应的数据格式为JSON字符串,该属性可以省略
  241. dataType: "json",
  242. //成功响应的结果
  243. success: function (data) {
  244. if (data != null) {
  245. var product = data;
  246. var html = "<tr>" +
  247. "<td>" + product.productId + "</td>" +
  248. "<td>" + product.productName + "</td>" +
  249. "<td>" + product.price + "</td>" +
  250. "<td>" + product.stock + "</td>" +
  251. "<td><button onclick='lookPage(" + product.productId + ")'>查看商品</a>" +
  252. "<button onclick='editPage(" + product.productId + ")';>修改商品</a>" +
  253. "<button onclick='deletePro(" + product.productId + ")';>删除商品</a></td>" +
  254. "</tr>";
  255.  
  256. $("#tb").append(html);
  257. }
  258. }
  259. });
  260. }
  261.  
  262. function lookPage(productId) {
  263. $("#lookWindow").slideDown(300);
  264. $("#look-backGround").show();
  265. $.ajax({
  266. //请求路径
  267. url: "http://localhost:8080/springmvc-json-demo/product/" + productId,
  268. //请求类型
  269. type: "get",
  270. //定义发送请求的数据格式为JSON字符串
  271. contentType: "application/json;charset=utf-8",
  272. //定义回调响应的数据格式为JSON字符串,该属性可以省略
  273. dataType: "json",
  274. //成功响应的结果
  275. success: function (data) {
  276. if (data != null) {
  277. $("#l-productId").html(data.productId);
  278. $("#l-productName").html(data.productName);
  279. $("#l-price").html(data.price);
  280. $("#l-stock").html(data.stock);
  281. $("#l-introduction").html(data.introduction);
  282. }
  283. }
  284. });
  285. }
  286.  
  287. // 打开商品修改页,并将商品信息回显到弹窗中
  288. function editPage(productId) {
  289. $("#editWindow").slideDown(300);
  290. $("#edit-backGround").show();
  291. $.ajax({
  292. //请求路径
  293. url: "http://localhost:8080/springmvc-json-demo/product/" + productId,
  294. //请求类型
  295. type: "get",
  296. //定义发送请求的数据格式为JSON字符串
  297. contentType: "application/json;charset=utf-8",
  298. //定义回调响应的数据格式为JSON字符串,该属性可以省略
  299. dataType: "json",
  300. //成功响应的结果
  301. success: function (data) {
  302. if (data != null) {
  303. var product = data;
  304. $("#e-productId").val(data.productId);
  305. $("#e-productName").val(data.productName);
  306. $("#e-price").val(data.price);
  307. $("#e-stock").val(data.stock);
  308. $("#e-introduction").val(data.introduction);
  309. }
  310. }
  311. });
  312. }
  313. </script>
  314.  
  315. <style type="text/css">
  316. #addWindow, #editWindow {
  317. display: none;
  318. position: absolute;
  319. top: 25%;
  320. left: 25%;
  321. width: 30%;
  322. height: 40%;
  323. padding: 20px;
  324. border: 3px solid #ccc;
  325. background-color: white;
  326. z-index: 2;
  327. overflow: auto;
  328. }
  329.  
  330. #lookWindow {
  331. display: none;
  332. position: absolute;
  333. top: 25%;
  334. left: 25%;
  335. width: 30%;
  336. height: 30%;
  337. padding: 20px;
  338. border: 3px solid #ccc;
  339. background-color: white;
  340. z-index: 2;
  341. overflow: auto;
  342. }
  343.  
  344. #backGround, #edit-backGround, #look-backGround {
  345. display: none;
  346. position: absolute;
  347. top: 0%;
  348. left: 0%;
  349. width: 100%;
  350. height: 1100px;
  351. background-color: black;
  352. z-index: 1;
  353. -moz-opacity: 0.8;
  354. opacity: .80;
  355. filter: alpha(opacity=88);
  356. }
  357.  
  358. #x:hover, #lx:hover, #ex:hover {
  359. cursor: pointer;
  360. color: rgb(55, 198, 192);
  361. }
  362. </style>
  363. </body>
  364. </html>


8. 将 springmvc-json-demo 部署到 Tomcat 服务器中,启动 Tomcat,使用浏览器访问“http://localhost:8080/springmvc-json-demo/products”,结果如下图。

商品列表-json
图1:商品列表


9. 点击下方的“新增商品”按钮,在弹出的新增商品页中填写商品信息,如下图。

新增商品页-json
图2:新增商品页


10. 在新增商品页点击“新增商品”按钮,返回商品列表页,结果如下图。

商品列表页-2
图3:商品列表页-2


11. 点击商品“衡水老白干”右侧的“查看商品”按钮,在弹出的商品详情页中查看商品详情,如下图。

商品详情-json
图4:商品详情页


12. 返回“商品列表页”点击商品右侧的“修改商品”按钮,在弹出的“修改商品页”对商品进行修改,如下图。

修改商品-json
图5:修改商品页


13. 点击下方的“修改商品信息”按钮,返回商品列表页,结果如下图。

商品列表-json2
图6:商品列表


14. 点击商品列表页的“删除商品”按钮,删除商品“衡水老白干-修改”,如下图。


图7:删除商品


15. 点击“确定”按钮,删除商品,返回查看商品列表,如下图。

商品列表-json
图8:商品列表页
posted @ 2022-07-31 14:32  随遇而安==  阅读(132)  评论(0编辑  收藏  举报