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

Posted 城南少年与猫

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot+ajax传输json数组以及单条数据的方法相关的知识,希望对你有一定的参考价值。

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

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

结构图如下:

下面是相关的代码:

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值,进行批量操作了:

以上是关于Springboot+ajax传输json数组以及单条数据的方法的主要内容,如果未能解决你的问题,请参考以下文章

Springboot与HTML交互问题

ajax传输数组

JQuery实现AJAX异步请求实现省市联动(数据传输格式为json)

ajax传输数组类型的参数

java如何接收ajax传递的json类型的数据

ajax使用json数组------前端往后台发送json数组及后台往前端发送json数组