Bootstrap+spring+springmvc+mybatis实现基本的增删改查(源码)

做个小列子,首先我这里先将spring+springmvc+mybatis整合好:

首先,给大家看一下我项目的构造:


1.第一步:我先将我项目中要是用的所有依赖导入:

 <!--Junit-->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>
    <!--MyBatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.4.5</version>
    </dependency>
    <!--MySQL-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.43</version>
    </dependency>
<!--spring-webmvc包括核心包,所以只要导入这一个就好了-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.3.3.RELEASE</version>
    </dependency>
    <!--C3p0-->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.1</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>4.3.10.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.1</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.1</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-core</artifactId>
      <version>2.9.1</version>
    </dependency>

    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-annotations</artifactId>
      <version>2.9.1</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>4.0.0</version>
      <scope>provided</scope>
    </dependency>

    <!-- json数据 使springMVC可以返回json值 ,视情况添加-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.30</version>
    </dependency>

2.关于ssm的整合我这里就不细说了,之前的博客就讲了关于 spring+springmvc+mybatis的整合(http://blog.csdn.net/desert568/article/details/79082067)

,所以我这里就直接上代码:

我的数据库连接池:db.properties:

uname=root
upass=root
url=jdbc:mysql://localhost:3306/test
driver_Class=com.mysql.jdbc.Driver

initPoolSize=5
maxPoolSize=20

3.ApplicationContext.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

    <!--加载db.properties-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>

    <!--c3p0-数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="user" value="${uname}"></property>
        <property name="password" value="${upass}"></property>
        <property name="jdbcUrl" value="${url}"></property>
        <property name="driverClass" value="${driver_Class}"></property>
        <property name="initialPoolSize" value="${initPoolSize}"></property>
        <property name="maxPoolSize" value="${maxPoolSize}"></property>
    </bean>

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

    <bean id="scannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.desert.dao"></property>
    </bean>

</beans>

4.然后再是我的springmvc配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <!--配置扫描器-->
    <context:component-scan base-package="com.desert.controller"></context:component-scan>

    <!--视图解析器-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/"></property>
        <!--后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <mvc:annotation-driven></mvc:annotation-driven>

</beans>

5.web.xml:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  <servlet>
    <servlet-name>springMVC</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
  
  </servlet>
   
  
  <servlet-mapping>
    <servlet-name>springMVC</servlet-name>
    <url-pattern>*.action</url-pattern>
  </servlet-mapping>

</web-app>

6.person实体类:
private String pname;
private int pid;
private int page;
 
7.我的PersonDao接口:
 
public interface IPerson01 {

    public List<Person> getallPerson(Map map);

    public List<Person> getallPersonByPname(Map map);

    public Person getPersonById(int pid);

    public void delperson(int pid);

    public void addperson(Person person);

    public void updateperson(Person person);

}


8.Person.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.desert.dao.IPerson01">
    <select id="getPersonById" parameterType="int" resultType="com.desert.entity.Person">
        select * from person where pid=#{pid}
    </select>

    <select id="getallPerson" resultType="com.desert.entity.Person" parameterType="map">
        select * from person limit #{offset},#{pageSize}
    </select>


    <select id="getallPersonByPname" resultType="com.desert.entity.Person" parameterType="map">
        select * from person p
        <where>
            <if test="pname != null">
                and p.pname like '%${pname}%'
            </if>
            <if test="page != null">
                and p.page =#{page}
            </if>
        </where>
        limit #{offset},#{pageSize}
    </select>

    <delete id="delperson" parameterType="int">
        delete from person where pid=#{pid}
    </delete>

    <insert id="addperson" parameterType="com.desert.entity.Person">
        insert into person(pname,page)
        values(#{pname},#{page})
    </insert>

    <update id="updateperson" parameterType="com.desert.entity.Person">
        update person set pname =#{pname}, page =#{page} where pid=#{pid}
    </update>
    
</mapper>

9.然后再是我的PersonController:

@Controller
public class PersonController {

    @Autowired
    private IPerson01 iPerson01;

    @RequestMapping("getPerson")
    public String getPerson(){

        Person person=iPerson01.getPersonById(1);
        System.out.println(person);
        return "success";
    }
    

    @RequestMapping("getsecondall")
    public void getsecondall(HttpServletResponse resp, HttpServletRequest request) throws IOException {


        //得到客户端传递的页码和每页记录数,并转换成int类型
        int pageSize = Integer.parseInt(request.getParameter("pageSize"));
        int pageNumber = Integer.parseInt(request.getParameter("pageNumber"));
        //查询参数
        String pname = request.getParameter("orderNum");
        String age=request.getParameter("page");

        int offset=(pageNumber-1)*pageSize;  //当前起始页
        //定义map集合:
        Map mp=new HashMap();
        //分页:
        mp.put("offset",offset);
        mp.put("pageSize",pageSize);

        if(age.length()>0){
             int page=Integer.parseInt(age);
            mp.put("page",page);
        }
        if(pname.length()>0){
            mp.put("pname",pname);
        }
      //分页:
        List<Person> la = iPerson01.getallPersonByPname(mp);
       // System.out.println(mp.get("page")+","+mp.get("pname"));
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("total",la.size());
        map.put("rows",la);
        PrintWriter out=resp.getWriter();
        String s= JSON.toJSONString(map);
       // System.out.println(s);
        out.write(s);
        out.flush();
        out.close();

    }

    //删除:
    @RequestMapping("delPerson")
    public void delPerson(HttpServletResponse resp, HttpServletRequest request) throws IOException {

        //得到传过来的字符串:
        String str=request.getParameter("str");
        //将字符串转化为数组:
        JSONArray jsons=JSONArray.parseArray(str);
        for (Object object : jsons) {
            int id=Integer.parseInt(object.toString());
            System.out.println(id);
            iPerson01.delperson(id);
        }
        //返回:
        PrintWriter out=resp.getWriter();
        out.write("1");
        out.flush();
        out.close();

    }

    //添加:
    @RequestMapping("addPerson")
    public void addPerson(HttpServletResponse resp, HttpServletRequest request) throws IOException {

        //得到传过来的字符串:
        String str=request.getParameter("str");
        //将字符串转化为数组:
        //将str转化为Area对象:
        Person person=JSON.parseObject(str, Person.class);
        System.out.println(person);
        //添加:
        iPerson01.addperson(person);
        //返回:
        PrintWriter out=resp.getWriter();
        out.write("1");
        out.flush();
        out.close();

    }

    //修改:
    @RequestMapping("updatePerson")
    public void updatePerson(HttpServletResponse resp, HttpServletRequest request) throws IOException {

        //得到传过来的字符串:
        String str=request.getParameter("str");
        //将字符串转化为数组:
        //将str转化为Area对象:
        Person person=JSON.parseObject(str, Person.class);
        //添加:
        iPerson01.updateperson(person);
        //返回:
        PrintWriter out=resp.getWriter();
        out.write("1");
        out.flush();
        out.close();

    }

}
10.最后,就是我的界面,second.jsp:
我这里的css和js都是直接用网上的,所以联网就可以,不用去下载什么js文件了:
 
<!-- 引入bootstrap样式 -->
<link href="https://cdn.bootcss.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<!-- 引入bootstrap-table样式 -->
<link href="https://cdn.bootcss.com/bootstrap-table/1.11.1/bootstrap-table.min.css" rel="stylesheet">

<!-- jquery -->
<script src="https://cdn.bootcss.com/jquery/2.2.3/jquery.min.js"></script>
<script src="https://cdn.bootcss.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>

<!-- bootstrap-table.min.js -->
<script src="https://cdn.bootcss.com/bootstrap-table/1.11.1/bootstrap-table.min.js"></script>
<!-- 引入中文语言包 -->
<script src="https://cdn.bootcss.com/bootstrap-table/1.11.1/locale/bootstrap-table-zh-CN.min.js"></script>

<html>
<head>
    <title>Title</title>
</head>
<body>
<script type="text/javascript">
    function initTable() {
        //初始化表格,动态从服务器加载数据
        $("#cusTable").bootstrapTable({
            method: "get",  //使用get请求到服务器获取数据
            url: "/getsecondall.action", //获取数据的Servlet地址
            toolbar: '#toolbar',                //工具按钮用哪个容器
            pagination: true, //启动分页
            pageSize: 10,  //每页显示的记录数
            pageNumber:1, //当前第几页
            pageList: [5, 10, 15, 20, 25],  //记录数可选列表
            search: false,  //是否启用查询
            showColumns: true,  //显示下拉框勾选要显示的列
            showRefresh: true,  //显示刷新按钮
            sidePagination: "server", //表示服务端请求
            height: 500,                        //行高,如果没有设置height属性,表格自动根据记录条数觉得表格高度
            uniqueId: "pid",                     //每一行的唯一标识,一般为主键列
            showToggle:true,                    //是否显示详细视图和列表视图的切换按钮
            cardView: false,                    //是否显示详细视图
            detailView: false,                   //是否显示父子表
            minimumCountColumns: 2,             //最少允许的列数
            clickToSelect: true,                //是否启用点击选中行
            //设置为undefined可以获取pageNumber,pageSize,searchText,sortName,sortOrder
            //设置为limit可以获取limit, offset, search, sort, order
            queryParamsType : "undefined",
            queryParams: function queryParams(params) {   //设置查询参数
                var param = {
                    pageNumber: params.pageNumber,
                    pageSize: params.pageSize,
                    orderNum : $("#txt_search_departmentname").val(),
                    page:$("#txt_search_statu").val()
                };
                return param;
            },
            columns: [{
                checkbox: true
            }, {
                field: 'pname',
                title: '名称'
            }, {
                field: 'page',
                title: '年龄'
            }, {
                field: 'pid',
                title: 'id'
            }, ]

        });
    }

    $(document).ready(function () {
        //调用函数,初始化表格
        initTable();

        //当点击查询按钮的时候执行
        $("#btn_query").bind("click", initTable);

        //删除
        $('#btn_delete').on("click", function () {
            var row=$.map($("#cusTable").bootstrapTable('getSelections'),function(row){
                return row ;
            });
            var ids=[];
            for (var i = 0; i < row.length; i++) {
                //获取自定义table 的中的checkbox值
                var id=row[i].pid;   //OTRECORDID这个是你要在列表中取的单个id
                ids.push(id); //然后把单个id循环放到ids的数组中
            }
            var str=JSON.stringify(ids);
             //批量删除:
            $.ajax({
                type:"POST",
                url:"/delPerson.action",
                data:"str="+str,
                success:function(msg){
                    // alert("返回的是:"+msg);
                    if(msg==1){
                       // alert("删除成功!");
                        $('#cusTable').bootstrapTable('refresh');
                    }else{
                        alert("删除失败!");
                    }
                }
            });
        });

        //添加:
        $('#btn_add').on("click", function () {
            $('#myModal').modal();
        });

        //修改
        $('#btn_edit').on("click", function () {

            var row=$.map($("#cusTable").bootstrapTable('getSelections'),function(row){
                return row ;
            });
            if(row.length==1){
                for (var i = 0; i < row.length; i++) {
                    alert(row[i].pid);
                    //打开弹出框:
                    $('#updatemyModal').modal();
                    $('#updatepname').val(row[i].pname);
                    $('#updatepage').val(row[i].page);
                }
            }
        });


    })

//提交添加:
    function mya(){
        var addpname=$('#addpname').val();
        var addpage=$('#addpage').val();
        //实例化一个对象:
        var person={"pname":addpname,"page":addpage};
        //将对象转换成字符串
        var str=JSON.stringify(person);
        alert(str);
        $.ajax({
            type:"POST" ,
            url:"/addPerson.action",
            data:"str="+str,
            success:function(msg){
                if(msg==1){
                    $('#cusTable').bootstrapTable('refresh');
                    $('#ff_p').form('clear');
                }else{
                    alert('添加失败');
                }

            }
        });
    }

    //修改提交:
    function myb(){
        var addpname=$('#updatepname').val();
        var addpage=$('#updatepage').val();
        //实例化一个对象:
        var person={"pname":addpname,"page":addpage};
        //将对象转换成字符串
        var str=JSON.stringify(person);
        $.ajax({
            type:"POST" ,
            url:"/addPerson.action",
            data:"str="+str,
            success:function(msg){
                if(msg==1){
                    $('#cusTable').bootstrapTable('refresh');
                }else{
                    alert('修改失败');
                }

            }
        });
    }

</script>

<div class="panel-body" style="padding-bottom:0px;">
    <div class="panel panel-default">
        <div class="panel-heading">查询条件</div>
        <div class="panel-body">
            <form id="formSearch" class="form-horizontal">
                <div class="form-group" style="margin-top:15px">
                    <label class="control-label col-sm-1" for="txt_search_departmentname">姓名</label>
                    <div class="col-sm-3">
                        <input type="text" class="form-control" id="txt_search_departmentname">
                    </div>
                    <label class="control-label col-sm-1" for="txt_search_statu">年龄</label>
                    <div class="col-sm-3">
                        <input type="text" class="form-control" id="txt_search_statu">
                    </div>
                    <div class="col-sm-4" style="text-align:left;">
                        <button type="button" οnclick="mya()" id="btn_query" class="btn btn-primary">查询</button>
                    </div>
                </div>
            </form>
        </div>
    </div>

    <div id="toolbar" class="btn-group">
        <button id="btn_add" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
        </button>
        <button id="btn_edit" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
        </button>
        <button id="btn_delete" type="button" class="btn btn-default">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
        </button>
    </div>

    <table class="table table-hover" id="cusTable">
    </table>
</div>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title" id="myModalLabel">新增</h4>
            </div>
            <div class="modal-body">
                <form id="ff_p" method="post">
                    <div class="form-group">
                        <label for="addpname">姓名</label>
                        <input type="text" name="namepname" class="form-control" id="addpname" placeholder="姓名">
                    </div>

                    <div class="form-group">
                        <label for="addpage">年龄</label>
                        <input type="text" name="namepid" class="form-control" id="addpage" placeholder="年龄">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭</button>
                        <button type="button" id="btn_submit" class="btn btn-primary" data-dismiss="modal" οnclick="mya()"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true" ></span>保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="updatemyModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                <h4 class="modal-title" id="updatemyModalLabel">修改</h4>
            </div>
            <div class="modal-body">
                <form id="updateff_p" method="post">
                    <div class="form-group">
                        <label for="updatepname">姓名</label>
                        <input type="text" name="namepname" class="form-control" id="updatepname" placeholder="姓名">
                    </div>

                    <div class="form-group">
                        <label for="updatepage">年龄</label>
                        <input type="text" name="namepid" class="form-control" id="updatepage" placeholder="年龄">
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-default" data-dismiss="modal"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span>关闭</button>
                        <button type="button" id="btn_update" class="btn btn-primary" data-dismiss="modal" οnclick="myb()"><span class="glyphicon glyphicon-floppy-disk" aria-hidden="true" ></span>保存</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

</body>
</html>

最后,附上一个完整截图:



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值