1. 程式人生 > >Springboot+ajax傳輸json數組以及單條數據的方法

Springboot+ajax傳輸json數組以及單條數據的方法

script pri 選中 aps ring ont image autowire ids

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數組以及單條數據的方法