Bootstrap基础知识

1 概念

前端框架:对css html js的封装
       :node.js   vue   bootstrap  easyui

2 准备项目

  • 完全参照:restful即可
  • 引入分页插件依赖的jar
<!--mybatis分页-->
<!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.10</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.github.jsqlparser/jsqlparser -->
<dependency>
    <groupId>com.github.jsqlparser</groupId>
    <artifactId>jsqlparser</artifactId>
    <version>3.1</version>
</dependency>
  • 在mybatis的核心配置文件中声明pagehelper插件
<!-- 导入pagehelper的插件-->
<plugins>
    <plugin interceptor="com.github.pagehelper.PageInterceptor"/>
</plugins>

3 创建数据库

CREATE DATABASE db_bootstrap CHARSET='utf8';
USE db_bootstrap;
CREATE TABLE tab_student(
    sid INT PRIMARY KEY AUTO_INCREMENT,
    sname VARCHAR(11),
    sex CHAR(1),
    score FLOAT(4,1),
    sclass VARCHAR(11),
    sbirthday DATE
);
DELETE FROM tab_student;
INSERT INTO tab_student VALUES(
     NULL,
     SUBSTR(UUID(),3,5),
     IF(RAND()>0.5,'男','女'),
     ROUND(RAND()*100,1),
     CONCAT('Java第',ROUND(RAND()*4+1),'期'),
     CONCAT(ROUND(RAND()*10+1980),'-',ROUND(RAND()*12+1),'-',ROUND(RAND()*30+1))     
);
SELECT * FROM tab_student;
CREATE TABLE tab_teacher(
    tid INT PRIMARY KEY AUTO_INCREMENT,
    tname VARCHAR(11),
    tpwd VARCHAR(11)
);
INSERT INTO tab_teacher VALUES(NULL,"张三","123");
INSERT INTO tab_teacher VALUES(NULL,"李四","123");
INSERT INTO tab_teacher VALUES(NULL,"王五","123");

4 准备工作

4.1实体类

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student  implements Serializable {
    private Integer sid;
    private String sname;
    private String sex;
    private Float score;
    private String sclass;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date sbirthday;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Teacher  implements Serializable {
    private Integer tid;
    private String tname;
    private String tpwd;
}

4.2工具类之图片验证码

package com.zhiyou100.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CheckImage {
	public static void getYzm(HttpServletResponse resp, HttpServletRequest req) throws Exception {
				System.out.println("==================================================");
				String message = "3456789abcdefghjkmnpqstuvwxy";
		//1 在内存中开辟空间 用于画画
				BufferedImage bin = new BufferedImage(200, 50, BufferedImage.TYPE_INT_RGB);
		//2 获取画笔
				Graphics2D g = (Graphics2D) bin.getGraphics();
		//3 涂染料 画背景
				g.setColor(Color.WHITE);
		//4 画背景:长方形
				g.fillRect(2, 2, 195, 45);
		//5 画主题
		//随机四五个字符
				String str = "";
				for (int i = 0; i < 4; i++) {
					str += message.charAt((int) (Math.random() * message.length()));
				}
		//给字符设置文字样式
				Font font = new Font(null, Font.BOLD, 34);
				g.setFont(font);
		//把字符串中的所有字符画到画布上
				for (int i = 0; i < str.length(); i++) {
					//笔蘸墨
					g.setColor(new Color((int) (Math.random() * 100 + 120), (int) (Math.random() * 100 + 120), (int) (Math.random() * 100 + 120)));
					//写字
					g.drawString(str.charAt(i) + "", i * 45 + 10, 40);
				}
		//画干扰线
				for (int i = 0; i < (int) (Math.random() * 5 + 5); i++) {
					g.setColor(new Color((int) (Math.random() * 50 + 120), (int) (Math.random() * 50 + 120), (int) (Math.random() * 50 + 120)));
					g.drawLine(2, (int) (Math.random() * 43 + 2), 195, (int) (Math.random() * 43 + 2));
				}
		//把验证码的信息装入session
				req.getSession().setAttribute("yzmSession", str);
		//把内存中图片的信息通过response的输出流 响应给客户端
				ImageIO.write(bin, "JPEG", resp.getOutputStream());
	}
}

4.3分析功能

老师:登录 登出
学生:增删改查

4.4dao和mapper

<?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.zhiyou100.dao.TeacherDao">
      <select id="getOneBySname" resultType="Teacher">
          select * from tab_teacher where tname=#{tname}
      </select>
      <select id="getOneBySid" resultType="Teacher">
          select * from tab_teacher where tid=#{tid}
      </select>
</mapper>
<?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.zhiyou100.dao.StudentDao">
    <select id="getAll" resultType="Student">
        select * from tab_student
    </select>
    <select id="getOneBySid" resultType="Student">
        select * from tab_student where sid=#{sid}
    </select>
    <delete id="deleteOne" parameterType="int">
        delete from tab_student where sid=#{sid}
    </delete>
    <insert id="addOne" parameterType="Student">
        insert into tab_student(sname,sex,score,sbirthday,sclass)
        values(#{sname},#{sex},#{score},#{sbirthday},#{sclass})
    </insert>
    <update id="updateOne" parameterType="Student">
        update  tab_student
        <set>
            <if test="sname != null">
                sname=#{sname},
            </if>
            <if test="sex != null">
                sex=#{sex},
            </if>
            <if test="score != null">
                score=#{score},
            </if>
            <if test="sclass != null">
                sclass=#{sclass},
            </if>
            <if test="sbirthday != null">
                sbirthday=#{sbirthday},
            </if>
        </set>
        where sid=#{sid}
    </update>
</mapper>

4.5创建service

package com.zhiyou100.service;
。。。
@Service
@Transactional
public class TeacherServiceImp   implements  TeacherService{
    @Autowired
    private TeacherDao teacherDao;

    @Override
    public Teacher login(String tname, String tpwd) {
        Teacher teacher=teacherDao.getOneByTname(tname);
        if(teacher==null){
            throw  new TeacherLoginException("用户名错误!");
        }
        if(!teacher.getTpwd().equals(tpwd)){
            throw  new TeacherLoginException("密码错误!");
        }
        return teacher;
    }
    @Override
    public Teacher getOneByTid(int tid) {
        return teacherDao.getOneByTid(tid);
    }
}
package com.zhiyou100.service;
...
@Service
@Transactional
public class StudentServiceImp   implements  StudentService{
    @Autowired
    private StudentDao studentDao;
    @Override
    public Student getOneBySid(int sid) {
        return studentDao.getOneBySid(sid);
    }

    @Override
    public List<Student> getAll() {
        return studentDao.getAll();
    }

    @Override
    public int addOne(Student student) {
        return studentDao.addOne(student);
    }

    @Override
    public int deleteOne(int sid) {
        return studentDao.deleteOne(sid);
    }

    @Override
    public int updateOne(Student student) {
        return studentDao.updateOne(student);
    }
}

4.6测试

package com.zhiyou100.test;

import com.zhiyou100.service.StudentService;
import com.zhiyou100.service.TeacherService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring_config.xml","classpath:springmvc_config.xml"})
public class Test01 {
    @Autowired
    private StudentService studentService;
    @Autowired
    private TeacherService teacherService;

    @Test
    public void test01(){
        System.out.println(studentService.getAll());
        System.out.println(studentService.getOneBySid(47));
        System.out.println(studentService.deleteOne(47));
    }
}

4.7 创建响应封装类

package com.zhiyou100.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

//用于给页面响应的封装体
// 添加成功  一个学生对象 一个集合  无内容  异常
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ResponseVO<T> {
      private Integer status;//状态码:200成功  4000 参数错误 5000 服务器错误
      private String message;//提示信息
      private  T  data;
}

4.8 创建action

package com.zhiyou100.action;

import com.zhiyou100.entity.ResponseVO;
import com.zhiyou100.entity.Student;
import com.zhiyou100.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

//@Controller
//@ResponseBody
@RestController
public class StudentAction {
    @Autowired
    private StudentService studentService;

    @RequestMapping(value="/student/getAll.action",method = RequestMethod.GET)
    public ResponseVO<List<Student>> getAll(){
          return new ResponseVO<List<Student>>(200,null,studentService.getAll());
    }
}

4.9 postman测试

image-20211214105634076

5 通过bootstrap实现所有页面

5.0 准备

引入bootstrap依赖的所有资源

image-20211214110040668

在页面引入基本的资源

<html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core"%>
<%@taglib prefix="fmt"  uri="http://java.sun.com/jsp/jstl/fmt"%>
<head>
        <title>学生增删改查页面</title>
        <!--1.1 引入min.css-->
        <link type="text/css" rel="stylesheet" href="<c:url value='/bootstrap-3.3.7-dist/css/bootstrap.min.css'/>"/>
        <!--1.2 引入bootstrap-theme.min.css-->
        <link type="text/css" rel="stylesheet" href="<c:url value='/bootstrap-3.3.7-dist/css/bootstrap-theme.min.css'/>"/>
</head>
        <!--1.3 引入jquery-->
        <script type="text/javascript" src="<c:url value='/js/jquery-3.3.1.min.js'/>"></script>
        <!--1.4 引入bootstrap.min.js-->
        <script type="text/javascript" src="<c:url value='/bootstrap-3.3.7-dist/js/bootstrap.min.js'/>"></script>
<body>

</body>
</html>

创建一个div

<!--定义一个div:所有的页面元素都在此div中-->
<!--1.5 bootstrap的所有页面元素必须写在一个class=container的div中-->
<div class="container">

</div>

异常处理的action

@ControllerAdvice
public class MyExceptionAction {

    @ExceptionHandler(TeacherLoginException.class)
    @ResponseBody
    public ResponseVO<String> method01(TeacherLoginException e){
        return new ResponseVO<String>(4000,e.getMessage(),null);
    }
}

5.1 实现标题

image-20211214111130042

  • 代码
<div class="container">
    <div class="page-header">
        <h1>智游集团 <small>有志之人立长志,无志之人常立志</small></h1>
    </div>
</div>
  • 效果

image-20211214111836200

5.2 创建表格:获取所有


<!--2.1 引入bootstrap-table.min.css-->
<link type="text/css" rel="stylesheet" href="<c:url value='/bootstrap-3.3.7-dist/css/bootstrap-table.min.css'/>"/>

<!--2.2 引入bootstrap-table-editable.min.js-->
<script type="text/javascript" src="<c:url value='/bootstrap-3.3.7-dist/js/bootstrap-table-editable.min.js'/>"></script>
<!--2.3 引入bootstrap-table-zh-CN.min.js-->
<script type="text/javascript" src="<c:url value='/bootstrap-3.3.7-dist/js/bootstrap-table-zh-CN.min.js'/>"></script>
<!--2.4 引入bootstrap-table.min.js-->
<script type="text/javascript" src="<c:url value='/bootstrap-3.3.7-dist/js/bootstrap-table.min.js'/>"></script>

image-20211214112452072

  • 代码
<!--带表格的面板-->
<div class="panel panel-default">
    <!-- Default panel contents -->
    <div class="panel-heading">学生学习列表</div>
    <!-- Table -->
    <table class="table" id="tab_student"></table>
</div>
  • 创建js方法 给table填充数据
<script type="text/javascript">
    var  path="<c:url value='/'/>";
//给tab_student填充数据
function setTableData(){
    $("#tab_student").bootstrapTable({
        url:path+"/student/getAll.action",
        type:"GET",
        cache:false,
        dateType:"json",
        //对响应数据进行解析
        responseHandler:function(responseVo){
            return responseVo.data;
        },
        //设置列名和列值:field指定responseVo.data的元素的属性 title指定列名
        columns:[
            {field:"sid",title:"学号"},
            {field:"sname",title:"名字"},
            {field:"sex",title:"性别"},
            {field:"score",title:"分数"},
            {field:"sbirthday",title:"生日"},
            {field:"sclass",title:"班级"}
        ]
    });
}
//文档加载成功 填充数据
$(function(){
    setTableData();
});
</script>
  • 效果

image-20211214114247687

5.3 实现分页

  • 创建分页的service
//分页
public PageInfo<Student> getAllFenYe(int pageNumber,int pageSize){
    PageHelper.startPage(pageNumber,pageSize);//必须在查询数据库之前
    PageInfo<Student> pageInfo=new PageInfo<>(studentDao.getAll());
    return pageInfo;
}
  • 分页action
@RequestMapping(value="/student/getAllFenYe.action",method = RequestMethod.GET)
public ResponseVO<PageInfo<Student>> getAllFenYeMethod(Integer pageNumber,Integer pageSize){
    return new ResponseVO<PageInfo<Student>>(200,null,studentService.getAllFenYe(pageNumber,pageSize));
}
  • postman

image-20211214121020693

  • 修改:setTableData 添加分页需要的属性
function setTableData(){
    $("#tab_student").bootstrapTable({
        //url:path+"/student/getAll.action",
        url:path+"/student/getAllFenYe.action",
        type:"GET",
        cache:false,
        dateType:"json",

        // //对响应数据进行解析
        // responseHandler:function(responseVo){
        //     return responseVo.data;
        // },

        //分页步骤1:要添加的5个属性
        pagination: true, //是否显示分页(*)
        sidePagination: "server",//分页方式:client客户端分页,server服务端分页(*)
        pageNumber: 1,//初始化加载第一页,默认第一页,并记录
        pageSize: 6,//每页的记录行数(*)
        pageList: [3, 5, 10, 15],//可供选择的每页的行数(*)
        //分页步骤2:添加属性queryParams 指定每次请求要添加的请求参数
        queryParams:function(info){//info的两个属性offset::起始索引 limit 每页记录数
            return {"pageNumber":info.offset/info.limit+1,"pageSize":info.limit};
        },
        //对相应数据进行解析
        //分页步骤3:修改responseHandler 相应结果需要指定rows(当前用要显示的行记录)和total(总记录数)
        responseHandler:function(responseVo){
            if(responseVo.status==200){
                //方法的参数responseVo是 相应对象responseVo
                //responseVo.data是PageInfo
                return {"rows":responseVo.data.list,"total":responseVo.data.total};
            }
            return null;
        },
        //设置列名和列值:field指定responseVo.data的元素的属性 title指定列名
        columns:[
            {field:"sid",title:"学号"},
            {field:"sname",title:"名字"},
            {field:"sex",title:"性别"},
            {field:"score",title:"分数"},
            {field:"sbirthday",title:"生日"},
            {field:"sclass",title:"班级"}
        ]
    });
}
  • 效果

image-20211214121241965

5.4 老师登录

  • 模态框:功能强大的弹出框

image-20211214152442745

  • 模态框代码:注意写在div id=container外面
<!--登录模态框:类似于弹出框-->
<div class="modal fade" id="loginModal" tabindex="-1" role="dialog" aria-labelledby="loginModalLabel">
    <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">&times;</span></button>
                <h4 class="modal-title" id="exampleModalLabel">老师登录</h4>
            </div>
            <div class="modal-body">
                <form id="form_login">
                    <div class="form-group">
                        <label class="control-label">老师名字:</label>
                        <input type="text" class="form-control"  name="tname">
                    </div>
                    <div class="form-group">
                        <label class="control-label">老师密码:</label>
                        <input type="text" class="form-control"  name="tpwd">
                    </div>
                    <div class="form-group">
                        <label class="control-label">验&nbsp;证&nbsp;码:</label>
                        <img src="<c:url value='/teacher/getYzmImg.action'/>"  id="img_yzm"/>
                        <input type="text" class="form-control"  name="tyzm">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">退出</button>
                <button type="button" class="btn btn-primary"  id="button_login">登录</button>
            </div>
        </div>
    </div>
</div>
  • 登录相关的js
$(function(){
    //给图片添加点击事件
    $("#img_yzm").bind("click",function(){
        $("#img_yzm").attr("src",path+"/teacher/getYzmImg.action?n="+Math.random());
    });
    //给button_login绑定点击事件
    $("#button_login").bind("click",function(){
        //获取form_login中的组件信息  发送ajax请求  判断是否登录成功
        var tname=$("#form_login input[name='tname']").val();
        var tpwd=$("#form_login input[name='tpwd']").val();
        var tyzm=$("#form_login input[name='tyzm']").val();
        $.ajax({
            cache:false,
            async:false,
            url:path+"/teacher/login.action",
            type:"GET",
            data:"tname="+tname+"&tpwd="+tpwd+"&tyzm="+tyzm,
            dataType:"json",
            success:function(responseVo){
                alert(responseVo.message);
                if(responseVo.status==200){
                    //登录模态框隐藏
                    $("#loginModal").modal("hide");
                }
            }
        });
    });
});
  • 登录相关的action
@Controller
public class TeacherAction {
    @Autowired
    private TeacherService teacherService;

    @RequestMapping(value="/teacher/getYzmImg.action",method = RequestMethod.GET)
    @ResponseBody
    public void getYzmImgMethod(HttpServletRequest req, HttpServletResponse resp){
        try {
            CheckImage.getYzm(resp,req);
        }catch(Exception e){
            throw new TeacherLoginException("图片验证码获取错误!");
        }
    }
    @RequestMapping(value="/teacher/login.action",method = RequestMethod.GET)
    @ResponseBody
    public ResponseVO<Teacher> loginMethod(String tname,String tpwd,String tyzm,HttpServletRequest req){
         String sessionYzm=(String) req.getSession().getAttribute("yzmSession");
         if(!tyzm.equals(sessionYzm)){
             throw new TeacherLoginException("验证码错误!");
         }
         Teacher teacher=teacherService.login(tname,tpwd);
         req.getSession().setAttribute("teacher",teacher);
         return new ResponseVO<Teacher>(200,"登录成功!",teacher);
    }
}
  • 测试效果

image-20211214162754689

5.5 老师登出

  • 在表格中添加按钮组
<!--添加按钮组-->
<div class="btn-group" role="group">
    <button type="button" class="btn btn-default" id="but_add">添加学生</button>
    <button type="button" class="btn btn-default" id="but_delete_add">删除选中</button>
    <button type="button" class="btn btn-default" id="but_logout">退出登录</button>
</div>
  • 与登出相关的js
//退出登录
$("#but_logout").bind("click",function(){
    //发送ajax请求 删除session
    $.get(path+"/teacher/logout.action",null,function(responseVo){
        //清空span_tname
        //弹出登录模态框
        alert(responseVo.message);
        if(responseVo.status==200){
            $("#span_tname").html("");
            $("#loginModal").modal("show");
        }
    },"json");
});
  • 与登出相关的action
@RequestMapping(value="/teacher/logout.action",method = RequestMethod.GET)
@ResponseBody
public ResponseVO<String> logoutMethod(HttpServletRequest req){
    req.getSession().invalidate();//清空session
    return new ResponseVO<String>(200,"登出成功!",null);
}
  • 效果

image-20211214164523184

5.6 添加学生

  • 添加的模态框
<!--添加模态框:类似于弹出框-->
<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel">
    <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">&times;</span></button>
                <h4 class="modal-title" id="addModalLabel">添加学生</h4>
            </div>
            <div class="modal-body">
                <form id="form_add">
                    <div class="form-group">
                        <label class="control-label">学生名字:</label>
                        <input type="text" class="form-control"  name="sname">
                    </div>
                    <div class="form-group">
                        <label class="control-label">学生分数:</label>
                        <input type="text" class="form-control"  name="score">
                    </div>
                    <div class="form-group">
                        <label class="control-label">学生性别:</label>
                        <label class="radio-inline">
                            <input type="radio" name="sex" value="男" checked> 男
                        </label>
                        <label class="radio-inline">
                            <input type="radio" name="sex"  value="女"> 女
                        </label>
                    </div>
                    <div class="form-group">
                        <label class="control-label">学生班级:</label>
                        <select class="form-control" name="sclass">
                            <option value="Java第1期">Java第1期</option>
                            <option value="Java第2期">Java第2期</option>
                            <option value="Java第3期">Java第3期</option>
                            <option value="Java第4期">Java第4期</option>
                            <option value="Java第5期">Java第5期</option>
                        </select>
                    </div>
                    <div class="form-group">
                        <label class="control-label">学生生日:</label>
                        <input type="date" class="form-control"  name="sbirthday">
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary"  id="but_add_submit">添加</button>
            </div>
        </div>
    </div>
</div>
  • 添加修改的js
//添加学生
$(function(){
    //文档加载成功给but_add添加点击事件
    $("#but_add").bind("click",function(){
        //弹出添加的模态框
        $("#addModal").modal("show");
    });

    //给but_add_submit 添加点击事件
    $("#but_add_submit").bind("click",function(){
        //获取form_add的数据  转换为josn串 传递给action
        var jsonObj=$("#form_add").serializeJSON();//获取表单数据对应的json
        var jsonStr=JSON.stringify(jsonObj);//获取jsong对象对应的字符串
        //ajax请求
        $.ajax({
            type:"POST",
            data:jsonStr,   //传递的是json串 不是json(415)
            url:path+"student/addOne.action",
            dataType:"json",
            contentType:"application/json;charset=utf-8",/*请求参数是json:必须加请求头contentType 指定请求参数的类型*/
            success:function(responseVo){
                alert(responseVo.message);
                if(responseVo.status==200){
                     //添加模态框隐藏
                    $("#addModal").modal("hide");
                    //刷新表格信息
                    $("#tab_student").bootstrapTable("refresh"); //刷新表格
                }
            }
        });
    });
});
  • 添加相关的action
@RequestMapping(value="/student/addOne.action",method = RequestMethod.POST)
public ResponseVO<String> addOneMethod(@RequestBody Student student){
    studentService.addOne(student);
    return new ResponseVO<String>(200,"添加成功",null);
}
  • 对日期显示进行改进
columns:[
    {field:"sid",title:"学号"},
    {field:"sname",title:"名字"},
    {field:"sex",title:"性别"},
    {field:"score",title:"分数"},
    {field:"sbirthday",title:"生日",formatter:function(value,row,index){
            var myDate=new Date(row.sbirthday);
            return myDate.getFullYear()+"年"+(myDate.getMonth()+1)+"月"+myDate.getDate()+"号";
        }
    },
    {field:"sclass",title:"班级"}
]

5.7 删除学生

  • 添加多选框列
columns:[
    {checkbox:true},/*删除的多选框*/
    {field:"sid",title:"学号"},
    {field:"sname",title:"名字"},
    {field:"sex",title:"性别"},
    {field:"score",title:"分数"},
    {field:"sbirthday",title:"生日",formatter:function(value,row,index){
        var myDate=new Date(row.sbirthday);
        return myDate.getFullYear()+"年"+(myDate.getMonth()+1)+"月"+myDate.getDate()+"号";
    }
    },
    {field:"sclass",title:"班级"}
]
  • 给按钮but_delete添加事件
//删除选中
$(function(){
    $("#but_delete_all").bind("click",function(){
        //获取那些行的checkbox被选中
        var coll=$("#tab_student").bootstrapTable("getSelections");
        var b=confirm("确定删除选中的学生吗?");
        if(!b){ return;}
        var sidStr="";
        //字符串拼接
        for(var i=0;i<coll.length;i++){
            sidStr+=coll[i].sid+"-";
        }
        //获取sid 进行批量删除
        $.ajax({
            type:"DELETE",
            data:null,
            dataType:"json",
            cache:false,
            async:false,
            url:path+"student/deleteSome/"+sidStr+".action",
            success:function(requestVo){
                alert(requestVo.message);
                if(requestVo.status==200){
                    //刷新表格信息
                    $("#tab_student").bootstrapTable("refresh"); //刷新表格
                }
            }
        });
    });
});
  • 批量删除的action+service+dao
@RequestMapping(value="/student/deleteSome/{sidStr}.action",method = RequestMethod.DELETE)
public ResponseVO<String> deleteSomeMethod(@PathVariable("sidStr")String sidStr){
    String[] sidArr=sidStr.split("-");
    int[] sidArrInt=new int[sidArr.length];
    for(int i=0;i<sidArr.length;i++){
        sidArrInt[i]=Integer.parseInt(sidArr[i]);
    }
    studentService.deleteSome(sidArrInt);
    return new ResponseVO<String>(200,"删除成功",null);
}
<delete id="deleteSome" parameterType="int[]">
    delete from tab_student where sid in
    <foreach collection="array" item="sid" separator="," open="(" index="i" close=")" >
        #{sid}
    </foreach>
</delete>
  • 效果

image-20211214181353819

posted @ 2021-12-25 19:47  RenVei  阅读(102)  评论(0编辑  收藏  举报