Springboot+ajax传输json数组以及单条数据的方法

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
云数据库 RDS MySQL,高可用系列 2核4GB
简介: Springboot+ajax传输json数组以及单条数据的方法下面是用ajax传输到后台单条以及多条数据的解析的Demo:结构图如下:image下面是相关的代码:pom.

Springboot+ajax传输json数组以及单条数据的方法

下面是用ajax传输到后台单条以及多条数据的解析的Demo:

结构图如下:

img_1e25647942f8c3083a8b7d4c42f0c40d.png
image

下面是相关的代码:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>springboot-ssm</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>
    <name>springboot-ssm</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <!--以下两项需要如果不配置,解析themleaft 会有问题-->
        <thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
        <thymeleaf-layout-dialect.version>2.0.5</thymeleaf-layout-dialect.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!--mybatis与mysql-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.2.0</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <!--druid依赖-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.0.25</version>
        </dependency>

        <!--添加static和templates的依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <!--解析json-->
        <dependency>
            <groupId>net.sf.json-lib</groupId>
            <artifactId>json-lib</artifactId>
            <version>2.4</version>
            <classifier>jdk15</classifier>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

StudentController:

package com.home.controller;
import com.home.entity.Student;
import com.home.service.StudentService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.List;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;


    @RequestMapping("/list")
    @ResponseBody
    public List<Student> list() {
        List<Student> studentList = studentService.getAllStu();
        return studentList;
    }


    @RequestMapping("/tableList")
    public String tableList(Model model) {
        List<Student> studentList = studentService.getAllStu();
        model.addAttribute("studentList", studentList);
        return "jsonArray";
    }


    @RequestMapping("/goToAdd")
    public String goToAdd() {
        return "add";
    }


    @RequestMapping("/add")
    public String add(Student stu) {
        studentService.insert(stu);
        return "result";
    }


    @RequestMapping("/goToAddJson")
    public String goToAddJson() {
        return "json";
    }


    @RequestMapping("/jsonArrayAdd")
    @ResponseBody
    public String jsonaAdd(@RequestParam("ids") String ids) {

        System.out.println(ids);

        JSONArray jsonArray = JSONArray.fromObject(ids);
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            System.out.println("json数组传递过来的参数为:" + "第" + i + "条:" + "\n" + jsonObject.get("id"));
        }
        return "json数组添加成功了";
    }


    //json数组传递

    @RequestMapping("/jsonAdd")
    @ResponseBody
    public String jsonArrayAdd(@RequestParam("ids") String ids) {

        JSONObject jsonObject = JSONObject.fromObject(ids);
        System.out.println("jsonObject==>" + jsonObject);
        Student stu = (Student) JSONObject.toBean(jsonObject, Student.class);
        System.out.println("stu==>" + stu);
        return "成功了!";
    }

}

Student:

package com.home.entity;
import java.io.Serializable;
public class Student implements Serializable {

    private Integer id;
    private String name;
    private Integer age;

    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 Integer getAge() {
        return age;
    }

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

    @Override
    public String  toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

StudentMapper:

package com.home.mapper;

import com.home.entity.Student;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;

@Mapper
public interface StudentMapper {
    List<Student> getAllStu();
    int deleteByPrimaryKey(Integer id);

    int insert(Student record);

    int insertSelective(Student record);

    Student selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(Student record);

    int updateByPrimaryKey(Student record);
}

StudentService:

package com.home.service;

import com.home.entity.Student;

import java.util.List;

public interface StudentService {
    List<Student> getAllStu();

    void insert(Student stu);
}

StudentServiceImpl:

package com.home.service.impl;
import com.home.entity.Student;
import com.home.mapper.StudentMapper;
import com.home.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service
public class StudentServiceImpl implements StudentService {

    @Resource
    private StudentMapper studentMapper;

    @Override
    public List<Student> getAllStu() {
        return studentMapper.getAllStu();
    }

    @Override
    public void insert(Student stu) {

     studentMapper.insert(stu);

    }
}

StudentMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.home.mapper.StudentMapper" >


    <resultMap id="BaseResultMap" type="com.home.entity.Student" >
        <id column="id" property="id" jdbcType="INTEGER" />
        <result column="name" property="name" jdbcType="VARCHAR" />
        <result column="age" property="age" jdbcType="INTEGER" />
    </resultMap>


    <sql id="Base_Column_List" >
    id, name, age
  </sql>
    <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
        select
        <include refid="Base_Column_List" />
        from student
        where id = #{id,jdbcType=INTEGER}
    </select>
    <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
    delete from student
    where id = #{id,jdbcType=INTEGER}
  </delete>
    <insert id="insert" parameterType="com.home.entity.Student" >
    insert into student (id, name, age
      )
    values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
      )
  </insert>
    <insert id="insertSelective" parameterType="com.home.entity.Student" >
        insert into student
        <trim prefix="(" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                id,
            </if>
            <if test="name != null" >
                name,
            </if>
            <if test="age != null" >
                age,
            </if>
        </trim>
        <trim prefix="values (" suffix=")" suffixOverrides="," >
            <if test="id != null" >
                #{id,jdbcType=INTEGER},
            </if>
            <if test="name != null" >
                #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null" >
                #{age,jdbcType=INTEGER},
            </if>
        </trim>
    </insert>
    <update id="updateByPrimaryKeySelective" parameterType="com.home.entity.Student" >
        update student
        <set >
            <if test="name != null" >
                name = #{name,jdbcType=VARCHAR},
            </if>
            <if test="age != null" >
                age = #{age,jdbcType=INTEGER},
            </if>
        </set>
        where id = #{id,jdbcType=INTEGER}
    </update>
    <update id="updateByPrimaryKey" parameterType="com.home.entity.Student" >
    update student
    set name = #{name,jdbcType=VARCHAR},
      age = #{age,jdbcType=INTEGER}
    where id = #{id,jdbcType=INTEGER}
  </update>


    <select id="getAllStu" resultType="com.home.entity.Student">
        select * from student
    </select>
</mapper>

SqlMapperConfig.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!-- <settings> 开启二级缓存 <setting name="cacheEnabled" value="true" /> </settings> -->
    <!-- 只需要定义个别名,这个应该有 -->
    <!-- springboot集成pageHelper(Java配置未注入的时候可以用下面配置) -->
    <!--    <plugins>
            com.github.pagehelper为PageHelper类所在包名
            <plugin interceptor="com.github.pagehelper.PageInterceptor">
                使用下面的方式配置参数,后面会有所有的参数介绍
                <property name="helperDialect" value="mysql" />
            </plugin>
        </plugins> -->
</configuration>

json.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>

    <!--<script src="${pageContxt.request.contextPath}/jquery-3.3.1/jquery-3.3.1.min.js"></script>-->
    <script type="text/javascript" th:src="@{../static/jquery-3.3.1/jquery-3.3.1.min.js}"></script>
</head>
<body>

<p>这个页面使用的是json的传输:</p>
<form th:action="@{/} " th:method="post">
    id:<input id="id" type="text" name="id"><br/>
    name:<input id="name" type="text" name="name"><br/>
    age:<input id="age" type="text" name="age"><br/>
</form>
<button onclick="tijiao()">提交json</button>
<script>

    function tijiao() {
        var id = $("#id").val().trim();
        var name = $("#name").val().trim();
        var age = $("#age").val().trim();

        console.log("id:" + id + "  name:" + name + "  age:" + age);

        var stu = {
            id:id,name:name,age:age
        }

        $.ajax({

            type:"post",
            url:"/jsonAdd",
            datatype:"json",
            data:{ids:JSON.stringify(stu)},
            success:function(data){
                alert(data) ;
            }
        });

    }

</script>
</body>
</html>

jsonArray.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script type="text/javascript" th:src="@{../static/jquery-3.3.1/jquery-3.3.1.min.js}"></script>

</head>
<body>
<table border="1" id="stuTable">
    <tr>
        <td>是否选中</td>
        <td>编号</td>
        <td>姓名</td>
        <td>年龄</td>
    </tr>

    <tr th:each="stu:${studentList}">
        <td><input th:type="checkbox" th:name="id" th:value="${stu.id}"></td>
        <td th:text="${stu.id}">编号</td>
        <td th:text="${stu.name}">姓名</td>
        <td th:text="${stu.age}">年龄</td>
    </tr>
</table>
<button id="pltj">批量提交</button>
<script>
    $("#pltj").click(
        function () {
            var checkbox = $("#stuTable").find(":checked");
            console.log(checkbox);
            if (checkbox == 0) {
                return;
            } else {
                var str = [];
                for (var i = 0; i < checkbox.length; i++) {
                    var ck = checkbox[i];
                    var a = $(ck).val().trim();
                    str.push({id: a});
                    console.log("str==>" + str);
                }
                $.ajax({

                    url: "/jsonArrayAdd",
                    datatype: "json",
                    data: {ids: JSON.stringify(str)},
                    success: function (data) {
                        alert(data);
                    }
                });
            }

        });

</script>
</body>
</html>

application.properties:

#server.port=80
logging.level.org.springframework=DEBUG
#springboot   mybatis
#jiazai mybatis peizhiwenjian
mybatis.mapper-locations = classpath:mapper/*Mapper.xml
mybatis.config-location = classpath:mybatis/sqlMapperConfig.xml
#mybatis.type-aliases-package = com.demo.bean
#shujuyuan
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8
spring.datasource.username = *******
spring.datasource.password = *******
spring.thymeleaf.prefix=classpath:/templates/

运行后选择两项,可以得到选中的那一行的id值,进行批量操作了:

img_584a59cae59be04b2c0ec6a8873c8a20.png
image
相关实践学习
如何快速连接云数据库RDS MySQL
本场景介绍如何通过阿里云数据管理服务DMS快速连接云数据库RDS MySQL,然后进行数据表的CRUD操作。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
相关文章
|
18天前
|
缓存 NoSQL Java
springboot怎么使用rides缓存方法的返回值 完整例子
通过上述步骤,我们成功地在 Spring Boot 项目中集成了 Redis 缓存,并通过注解的方式实现了方法返回值的缓存。这种方式不仅提高了系统的性能,还简化了缓存管理的复杂度。使用 Spring Boot 的缓存注解和 Redis,可以轻松地实现高效、可靠的缓存机制。
53 23
|
2月前
|
JSON 人工智能 算法
探索大型语言模型LLM推理全阶段的JSON格式输出限制方法
本篇文章详细讨论了如何确保大型语言模型(LLMs)输出结构化的JSON格式,这对于提高数据处理的自动化程度和系统的互操作性至关重要。
|
3月前
|
JSON JavaScript 前端开发
|
3月前
|
JSON 人工智能 算法
探索LLM推理全阶段的JSON格式输出限制方法
文章详细讨论了如何确保大型语言模型(LLMs)输出结构化的JSON格式,这对于提高数据处理的自动化程度和系统的互操作性至关重要。
567 12
|
4月前
|
存储 安全 Java
|
5月前
|
XML JSON JavaScript
JSON对象的stringify()和parse()方法使用
本文阐述了JSON对象的`stringify()`和`parse()`方法的用法,包括如何将JavaScript对象转换为JSON字符串,以及如何将JSON字符串解析回JavaScript对象,并讨论了转换过程中需要注意的事项。
JSON对象的stringify()和parse()方法使用
|
5月前
|
Java 应用服务中间件 Spring
IDEA 工具 启动 spring boot 的 main 方法报错。已解决
IDEA 工具 启动 spring boot 的 main 方法报错。已解决
114 4
|
6月前
|
JSON Java API
解码Spring Boot与JSON的完美融合:提升你的Web开发效率,实战技巧大公开!
【8月更文挑战第29天】Spring Boot作为Java开发的轻量级框架,通过`jackson`库提供了强大的JSON处理功能,简化了Web服务和数据交互的实现。本文通过代码示例介绍如何在Spring Boot中进行JSON序列化和反序列化操作,并展示了处理复杂JSON数据及创建RESTful API的方法,帮助开发者提高效率和应用性能。
274 0
|
6月前
|
JSON Java API
Jackson:SpringBoot中的JSON王者,优雅掌控数据之道
【8月更文挑战第29天】在Java的广阔生态中,SpringBoot以其“约定优于配置”的理念,极大地简化了企业级应用的开发流程。而在SpringBoot处理HTTP请求与响应的过程中,JSON数据的序列化和反序列化是不可或缺的一环。在众多JSON处理库中,Jackson凭借其高效、灵活和强大的特性,成为了SpringBoot中处理JSON数据的首选。今天,就让我们一起深入探讨Jackson如何在SpringBoot中优雅地控制JSON数据。
208 0
|
6月前
|
存储 JSON JavaScript