专栏首页Spring相关Springboot+ajax传输json数组以及单条数据的方法

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

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

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

结构图如下:

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

image

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • 并发编程中的原子类

    对多线程访问同一个变量,我们需要加锁,而锁是比较消耗性能的,JDk1.5之后, 新增的原子操作类提供了 一种用法简单、性能高效、线程安全地更新一个变量的方式,...

    Dream城堡
  • Android的相关事件

    res下新建一个Director,名为menu,在menu中建一个main的menuresourceFile(右键新建即可)

    Dream城堡
  • SharePreference存储

    Dream城堡
  • java中List对象列表去重或取出以及排序

    面试碰到几次list的去重和排序。下面介绍一种做法: 1. list去重 1.1 实体类Student List<Student>容量10k以上,要求去重复。这...

    Ryan-Miao
  • 你好MyBatis 高级篇

    MyBatis中的缓存是默认开启的无法关闭,当然只是单指MyBatis单独存在的情况下,后期涉及到MyBatis整合Spring,Spring会将一级缓存关闭掉...

    止术
  • Python:What the f*ck Python(上)

    说明: 这些行为是由于 CPython 在编译优化时,某些情况下会尝试使用已经存在的不可变对象而不是每次都创建一个新对象。这种行为被称作字符串的驻留[stri...

    丹枫无迹
  • 常用阻塞队列 BlockingQueue 有哪些?

    之前,介绍了一下 ThreadPoolExecutor 的各参数的含义(并发编程之线程池ThreadPoolExecutor),其中有一个 BlockingQu...

    烟雨星空
  • Mybatis - 动态sql

    learn from:http://www.mybatis.org/mybatis-3/dynamic-sql.html mybatis支持动态拼接sql语句。...

    Ryan-Miao
  • Linux之init.d、rc.d文件夹说明

    今天在研究mysql的安装的时候,最后一步要创建一个软连接,使得mysql服务可以自启动,代码如下:

    AsiaYe
  • SRC逻辑漏洞挖掘详解以及思路和技巧

    由于程序逻辑不严谨或逻辑太过复杂,导致一些逻辑分支不能正常处理或处理错误,统称为业务逻辑漏洞。常见的逻辑漏洞有交易支付、密码修改、密码找回、越权修改、越权查询、...

    HACK学习

扫码关注云+社区

领取腾讯云代金券