SpringMVC使用AJAX向后台传送对象数组

废话就不多说了直接上代码吧

1、我们配置好自动生成代码和mapper文件的.xml文件

见上一篇MyBatis-Generator 基本使用方法博客。

2、配置mybatis-config.xml文件

jdbc.properties文件代码如下:

driver = org.mariadb.jdbc.Driver
url = jdbc:mariadb://localhost:3306/EmployeeDB
username = root
password = root

mybatis-config.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>
    <!-- 定义可以复用的变量 -->
    <!--<properties resource="jdbc.properties"/>-->

    <!--配置文件-->
    <settings>
        <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true" />
        <!-- 使用列别名替换列名 默认:true -->
        <setting name="useColumnLabel" value="true" />
        <!-- 开启驼峰命名转换:Table {create_time} -> Entity {createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
    
    <!-- 给类设置别名,简化xml文件 -->
    <!--<typeAliases>-->
        <!--<typeAlias alias="entity" type="com.xiaobai.entity.CustomerEntity"/>-->
        <!--扫描该包下的所有类-->
        <!--<package name="com.xiaobai.entity"/>-->
    <!--</typeAliases>-->

    <!-- 类型转换器 -->
    <!--<typeHandlers>-->
        <!--<typeHandler handler="com.xiaobai.dao.InvoiceDAO"/>-->
        <!--<package name="com.xiaobai.dao"/>-->
    <!--</typeHandlers>-->

    <!--<plugins>-->
        <!--<plugin interceptor="com.github.pagehelper.PageInterceptor">-->
            <!--<property name="param1" value="value1"/>-->
        <!--</plugin>-->
    <!--</plugins>-->
    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor" />
    </plugins>

    <!--<environments default="development">-->
        <!--<environment id="development">-->
            <!--<transactionManager type="JDBC"></transactionManager>-->
            <!--<dataSource type="POOLED">-->
                <!--<property name="driver" value="${driver}"/>-->
                <!--<property name="url" value="${url}"/>-->
                <!--<property name="username" value="${username}"/>-->
                <!--<property name="password" value="${password}"/>-->
            <!--</dataSource>-->
        <!--</environment>-->
    <!--</environments>-->

    <!-- 指定映射器 -->
    <!--<mappers>-->
        <!--<mapper resource="mapper/PersonMapper.xml"/>-->
    <!--</mappers>-->

</configuration>

3、配置需要的Spring配置文件

spring-web.xml文件代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:contxt="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--扫描包下面所有的 @Controller 注解的类,并将其实例化,放入容器-->
    <contxt:component-scan base-package="com.xiaobai.controller" />

    <!-- 启用mvc 的常用注解 -->
    <mvc:annotation-driven />

    <!-- 将所有的静态资源,交给 Servlet处理 -->
    <mvc:default-servlet-handler />

    <!-- 配置 jsp -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>

</beans>

spring-dao.xml文件代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--使用外部文件-->
    <context:property-placeholder location="classpath:jdbc.properties" />

    <!--创建数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="org.mariadb.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mariadb://localhost:3306/EmployeeDB" />
        <property name="user" value="root" />
        <property name="password" value="Qi1007.." />

        <property name="maxPoolSize" value="30" />
        <property name="minPoolSize" value="10" />
        <property name="autoCommitOnClose" value="false" />
        <property name="checkoutTimeout" value="10000" />
        <property name="acquireRetryAttempts" value="2" />
    </bean>

    <!--配置 mybatis-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.xiaobai.model" />
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>

    <!--自动注入 Mapper-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <property name="basePackage" value="com.xiaobai.dao" />
    </bean>

    <!--配置声明式事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>
    <tx:annotation-driven proxy-target-class="true" />

</beans>

spring-service.xml文件代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">

    <!--启用注解 @Component-->
    <context:component-scan base-package="com.xiaobai" />

    <!-- 启用 aspectj 方式 AOP-->
    <aop:aspectj-autoproxy proxy-target-class="true" />

</beans>

4、配置日志文件log4j.properties

# 全局配置: 只显示错误级别的日志,输出为名字为 stdou 的日志
log4j.rootLogger=ERROR, stdout

# MyBatis 的日志配置,只输出 com.nf147.bookstore_ssm.dao 包下产生 INFO 以及以上级别的日志
#TRACE为日志级别,可进行修改
log4j.logger.com.nf147.bookstore_ssm.dao=TRACE

# 定义名字为 stdout 的日志,将日志输出到控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

#log4j.appender.database=org.apache.log4j.jdbc.JDBCAppender
#log4j.appender.database.layout=org.apache.log4j.PatternLayout
#log4j.appender.database.driver=org.mariadb.jdbc.Driver
#log4j.appender.database.Threshold=TRACE
#log4j.appender.database.BufferSize=1
#log4j.appender.database.URL=jdbc:mariadb://localhost:3306/lagou
#log4j.appender.database.user=root
#log4j.appender.database.password=Qi1007..
#log4j.appender.database.sql=insert into log (class,method,createtime,loglevel,msg) VALUES ('%C','%M','%d{yyyy-MM-dd hh:mm:ss}','%p','%m')

5、编写controller类

EmployeeController类代码如下:

package com.xiaobai.controller;

import com.google.gson.Gson;
import com.xiaobai.dao.EmployeeMapper;
import com.xiaobai.entity.Employee;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
//初次访问的路径
@RequestMapping("/")
public class EmployeeController {
    @Autowired
    private EmployeeMapper employeeMapper;

    //映射路径
    @RequestMapping(method = RequestMethod.GET)
    public String home (Model model) {
        return "home";
    }

    //@ResponseBody 返回json对象
    @ResponseBody
    //produces 设置返回对象的格式
    @RequestMapping(value = "/findAll", method = RequestMethod.GET,produces = "application/json;charset=utf-8")
    public String findAll (Model model) {
        List<Employee> employeeList = employeeMapper.selectAll();
        return new Gson().toJson(employeeList);
    }


    @RequestMapping("/insert")
    @ResponseBody
    public String insertAll (@RequestBody List<Employee> employeeList) {
        //循环调用插入事件
        for (Employee employee : employeeList) {
            employeeMapper.insert(employee);
        }
        return "{\"msg\":\"成功\"}";
    }

}

6、编写返回的页面home.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page isELIgnored="false" %>
<html>
<head>
    <title>Title</title>
</head>
<style>
    #employeeList th, #employeeList td {
        width: 150px;
    }
</style>
<body>

<table border="0" cellspacing="0" cellpadding="8" style="text-align: center" id="table">
    <th>员工编号</th>
    <th>姓名</th>
    <th>性别</th>
    <th>学历</th>
    <th>月薪</th>
    <th>添加</th>
    <th>移除</th>

<tbody id="tbody">
    <tr>
        <td><input type="text" name="employeeId" id="employeeId"></td>
        <td><input type="text" name="employeeName" id="employeeName"></td>
        <td>
            <select name="employeeSex" id="employeeSex">
                <option value="">请选择</option>
                <option value="1">男</option>
                <option value="0">女</option>
            </select>
        </td>
        <td>
            <select name="educationId">
                <option value="">请选择</option>
            </select>
        </td>
        <td><input type="number" name="employeeMoney" id="employeeMoney"></td>
        <td><input type="button" value="+" class = "addBtn"></td>
        <td><input type="button" value="-" onclick="subButton(this)"></td>
    </tr>
</tbody>

    <tr>
        <td colspan="7"><input type="button" value="批量提交" id="insertAll"></td>
    </tr>

</table>
<br/><br/><br/><br/>


<table border="1" cellspacing="0" cellpadding="1" id="employeeList" style="text-align: center">
    <tr>
        <th>员工编号</th>
        <th>姓名</th>
        <th>性别</th>
        <th>学历</th>
        <th>月薪</th>
    </tr>
</table>


<script src="js/jquery-3.3.1.min.js"></script>
<script>

    // ajax 获取学历列表
    var education = function () {
        $("select[name='educationId'] option").remove();
        $("select[name='educationId']").append("<option value=''>请选择</option>")
        $.ajax({
            url:"/educationFindAll",
            type:"get",
            success:function(data){
                $.each(data,function(index,val){
                    $("select[name='educationId']").append("<option value="+val.educationId+">"+val.educationName+"</option>")
                })
            }
        })
    }

    //ajax 获取employee所有信息
    var list = function () {
        $.ajax({
            url:"/findAll",
            type:"get",
            success:function(data){
                $.each(data,function(index,value){
                    if(value.employeeSex == 1)
                        $("#employeeList").append("<tr><td>"+value.employeeId+"</td><td>"+value.employeeName+"</td><td>男</td><td>"+value.educationInfo.educationName+"</td><td>"+value.employeeMoney+"</td></tr>");
                    else
                        $("#employeeList").append("<tr><td>"+value.employeeId+"</td><td>"+value.employeeName+"</td><td>女</td><td>"+value.educationInfo.educationName+"</td><td>"+value.employeeMoney+"</td></tr>");
                })
            }
        })
        education();
    }
    list();

    // 克隆节点
    // function addButton() {
        // $("#tbody").append("<tr>\n" +
        //     "        <td><input type=\"text\" name=\"employeeId\" id=\"employeeId\"></td>\n" +
        //     "        <td><input type=\"text\" name=\"employeeName\" id=\"employeeName\"></td>\n" +
        //     "        <td>\n" +
        //     "            <select name=\"employeeSex\" id=\"employeeSex\">\n" +
        //     "                <option value=\"\">请选择</option>\n" +
        //     "                <option value=\"1\">男</option>\n" +
        //     "                <option value=\"0\">女</option>\n" +
        //     "            </select>\n" +
        //     "        </td>\n" +
        //     "        <td>\n" +
        //     "            <select name=\"educationId\">\n" +
        //     "                <option value=\"\">请选择</option>\n" +
        //     "            </select>\n" +
        //     "        </td>\n" +
        //     "        <td><input type=\"number\" name=\"employeeMoney\" id=\"employeeMoney\"></td>\n" +
        //     "        <td><input type=\"button\" value=\"+\" onclick=\"addButton(this)\"></td>\n" +
        //     "        <td><input type=\"button\" value=\"-\" onclick=\"subButton(this)\"></td>\n" +
        //     "    </tr>")
        // education();
    // }
    $("#tbody").on("click",".addBtn",function(){
        $(this).parents("tr").clone().appendTo($("#tbody"));
    })

    //删除节点
    function subButton(sub) {
        var parent = $(sub).parent().parent("tr");
        var length = $("#table tr").length;
        if (length != 3) {
            parent.remove();
        } else {
            alert("就只有一行了,再删你怎么添加")
        }
    }

    // 批量添加
    //使用ajax向后台提交对象数组
    $("#insertAll").click(function () {
        // 定义一个数组
        var employeeList = new Array();
        //获取所有tr
        var tr = $("#tbody tr");
        //循环遍历所有tr对象
        $.each(tr,function(index,obj){
            //添加到数组中
            employeeList.push({
                "employeeId": $("input[name='employeeId']",obj).val(),
                "employeeName": $("input[name='employeeName']",obj).val(),
                "employeeSex": $("select[name='employeeSex']",obj).val(),
                "educationId": $("select[name='educationId']",obj).val(),
                "employeeMoney": $("input[name='employeeMoney']",obj).val()
            });
        })

        $.ajax({
            type: "POST",
            url: "/insert",
            //设置传送后台的数据格式
            contentType:"application/json;charset=utf-8",
            //转json对象
            data: JSON.stringify(employeeList),
            success: function (data) {
                //刷新页面
                window.location.reload();
                list();
            }
        });
    })
</script>
</body>
</html>

 

posted @ 2018-10-30 09:13  xiaobai1007  阅读(824)  评论(0编辑  收藏  举报