创建的数据库/表:
运行效果展示:
查询
添加:
点击添加按钮:
添加成功!
修改:
点击编辑按钮:
修改信息数据,点击提交:
修改数据成功!
删除:
点击删除按钮:
点击确定,删除成功!
分页:
由于数据有限,选择5条/页,进行分页:
批量删除:
首先勾选想要删除的行,点击批量删除:
删除成功:
控制台输出:
操作后的数据库/表:
文章来源:https://www.toymoban.com/news/detail-408708.html
项目代码整体布局:
补充:(展开查看assers目录的layui-v2.6.8)
文章来源地址https://www.toymoban.com/news/detail-408708.html
代码部分:
创建数据库:
#创建数据库
create database 70806_db
default character set utf8mb4 #设置字符集
default collate utf8mb4_general_ci #设置排序规则
创建数据表:
#创建班级表
create table classInfo
(
classId int primary key auto_increment,
className varchar(20)
);
select * from classInfo;
insert into classInfo
(className)
values
('AAA01'),
('AAA02');
#创建学生表
create table studentInfo
(
studentId int primary key auto_increment,
name varchar(20) not null,
sex char(1) not null,
birthday date,
province varchar(20) default '河南',
classId int,
foreign key (classId)
references classInfo(classId)
);
select * from studentInfo;
insert into studentInfo
(name,sex,birthday,province,classId)
values
('张三','男','2002-01-01','湖北',1),
('李四','女','2003-01-05','河南',2),
('王五','男','2010-03-01','湖北',1),
('赵六','男','2009-01-08','河南',2),
('孙琪','女','2001-09-01','湖北',1);
util:
BaseDAO:
package com.util;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class BaseDAO {
//四大金刚
//驱动类
private static final String DRIVER="com.mysql.cj.jdbc.Driver";
//连接地址
private static final String URL="jdbc:mysql://localhost:3306/70806_db?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai";
//用户名
private static final String USER="root";
//密码
private static final String PASSWORD="123456";
//获取连接
public static Connection getConnection(){
Connection con = null;
try{
//加载驱动类
Class.forName(DRIVER);
//获取连接
con = DriverManager.getConnection(URL,USER,PASSWORD);
}catch(Exception ex){
ex.printStackTrace();
}
return con;
}
//关闭数据库对象
public static void closeAll(Connection con,Statement st,ResultSet rs){
if(rs!=null){
try{
rs.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
if(st!=null){
try{
st.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
if(con!=null){
try{
con.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
//通用设置参数方法
public static void setParams(PreparedStatement pst,Object[] params){
if(params==null){
return;
}
for(int i=0;i<params.length;i++){
try{
pst.setObject(i+1,params[i]);
}catch(Exception ex){
ex.printStackTrace();
}
}
}
//通用增删改
public static int executeUpdate(String sql,Object[] params){
Connection con = null;
PreparedStatement pst = null;
int res = -1;
try{
//获取连接
con = getConnection();
//创建预编译命令执行对象
pst = con.prepareStatement(sql);
//设置参数
setParams(pst,params);
//执行
System.out.println(pst);
res = pst.executeUpdate();
}catch(Exception ex){
ex.printStackTrace();
}finally{
closeAll(con,pst,null);
}
return res;
}
//获取总记录数的查询:select count(*) from ..
public static int getTotal(String sql,Object[] params){
int total = 0;
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
con = getConnection();
pst = con.prepareStatement(sql);
setParams(pst,params);
rs = pst.executeQuery();
//判断是否查询除了一个记录
if(rs.next()){
total = rs.getInt(1);
}
}catch (Exception ex){
ex.printStackTrace();
}finally {
closeAll(con,pst,rs);
}
return total;
}
//通用查询
public static List<Map<String,Object>> executeQuery(String sql,Object[] params) {
List<Map<String,Object>> rows = new ArrayList<>();
Connection con = null;
PreparedStatement pst = null;
ResultSet rs = null;
try{
//获取连接
con = getConnection();
//获取命令对象
pst = con.prepareStatement(sql);
//设置参数
setParams(pst,params);
//执行查询
rs = pst.executeQuery();
//通过rs获取结果集的结构信息
ResultSetMetaData rsmd = rs.getMetaData();
//获取结果集的列数
int colCount = rsmd.getColumnCount();
//遍历查询结果,并封装到List<Map>中
while(rs.next()){
//用Map存储当前行的各个列数据
Map<String,Object> map = new HashMap<>();
//循环获取每一列的信息
for(int i=1;i<=colCount;i++){
//获取列名(使用rsmd)
String colName = rsmd.getColumnLabel(i);
//获取列值(使用rs)
Object colVal = rs.getObject(i);
//将当前列存储到map中
map.put(colName,colVal);
}
//将遍历的当前行的数据存储到List中
rows.add(map);
}
}catch(Exception ex){
ex.printStackTrace();
}finally{
closeAll(con,pst,rs);
}
return rows;
}
}
entity:
Student :
package com.entity;
import java.util.Date;
public class Student {
private Integer studentId;
private String name;
private String sex;
private Date birthday;
private String province;
private Integer classId;
public Student() {
}
public Student(Integer studentId, String name, String sex, Date birthday, String province, Integer classId) {
this.studentId = studentId;
this.name = name;
this.sex = sex;
this.birthday = birthday;
this.province = province;
this.classId = classId;
}
public Student(String name, String sex, Date birthday, String province, Integer classId) {
this.name = name;
this.sex = sex;
this.birthday = birthday;
this.province = province;
this.classId = classId;
}
public Integer getStudentId() {
return studentId;
}
public void setStudentId(Integer studentId) {
this.studentId = studentId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getProvince() {
return province;
}
public void setProvince(String province) {
this.province = province;
}
public Integer getClassId() {
return classId;
}
public void setClassId(Integer classId) {
this.classId = classId;
}
@Override
public String toString() {
return "Student{" +
"studentId=" + studentId +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", birthday=" + birthday +
", province='" + province + '\'' +
", classId=" + classId +
'}';
}
}
ClassInfo:
package com.entity;
public class ClassInfo {
private Integer classId;
private String className;
public ClassInfo() {
}
public ClassInfo(String className) {
this.className = className;
}
public ClassInfo(Integer classId, String className) {
this.classId = classId;
this.className = className;
}
public Integer getClassId() {
return classId;
}
public void setClassId(Integer classId) {
this.classId = classId;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
@Override
public String toString() {
return "ClassInfo{" +
"classId=" + classId +
", className='" + className + '\'' +
'}';
}
}
PageData:
package com.entity;
public class PageData {
//当前页码
private Integer pageNo;
//每页记录数
private Integer pageSize;
//总记录数
private Integer totalCount;
//总页数
private Integer totalPage;
//当前页记录
private Object data;
public PageData() {
}
public Integer getPageNo() {
return pageNo;
}
public void setPageNo(Integer pageNo) {
this.pageNo = pageNo;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public Integer getTotalCount() {
return totalCount;
}
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
public Integer getTotalPage() {
return totalPage;
}
public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "PageData{" +
"pageNo=" + pageNo +
", pageSize=" + pageSize +
", totalCount=" + totalCount +
", totalPage=" + totalPage +
", data=" + data +
'}';
}
}
CommonResult:
package com.entity;
public class CommonResult {
//编码:0成功,1失败
private Integer code;
//提示消息
private String msg;
//记录数
private Integer count;
//记录数据
private Object data;
public CommonResult() {
}
public CommonResult(Integer code, String msg, Integer count, Object data) {
this.code = code;
this.msg = msg;
this.count = count;
this.data = data;
}
//返回查询结果的成功信息:
public static CommonResult success(Integer count,Object data){
return new CommonResult(0,"success",count,data);
}
//返回增删改的成功信息
public static CommonResult success(){
return new CommonResult(0,"success",null,null);
}
//返回失败信息
public static CommonResult fail(){
return new CommonResult(1,"fail",null,null);
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
@Override
public String toString() {
return "CommonResult{" +
"code=" + code +
", msg='" + msg + '\'' +
", count=" + count +
", data=" + data +
'}';
}
}
dao:
impl:
StudentDAOImpl:
package com.dao.impl;
import com.dao.IStudentDAO;
import com.entity.PageData;
import com.entity.Student;
import com.util.BaseDAO;
import java.util.List;
import java.util.Map;
public class StudentDAOImpl implements IStudentDAO {
@Override
public int delete(String ids) {
System.out.println("=======StudentDAOImpl delete===============");
String sql = "delete from studentInfo where studentId in ("+ids +") ";
return BaseDAO.executeUpdate(sql,null);
}
@Override
public List<Map<String, Object>> listAll() {
System.out.println("=======StudentDAOImpl listAll===============");
String sql = "select s.studentId,s.name,s.sex,s.birthday,s.province," +
" c.classId,c.className " +
" from studentInfo s " +
" join classInfo c " +
" on s.classId = c.classId ";
System.out.println(sql);
return BaseDAO.executeQuery(sql,null);
}
@Override
public int insert(Student student) {
String sql="insert into studentInfo "+
" (name,sex,birthday,province,classId)"+
" values"+
" (?,?,?,?,?)";
Object[] params={
student.getName(),
student.getSex(),
student.getBirthday(),
student.getProvince(),
student.getClassId()
};
return BaseDAO.executeUpdate(sql,params);
}
@Override
public int update(Student student) {
String sql = "update studentInfo" +
" set name = ?," +
" sex = ?," +
" birthday = ?," +
" province = ?," +
" classId = ? " +
" where studentId = ? ";
Object[] params = {
student.getName(),
student.getSex(),
student.getBirthday(),
student.getProvince(),
student.getClassId(),
student.getStudentId()
};
return BaseDAO.executeUpdate(sql,params);
}
@Override
public PageData queryByPage(Integer pageNo, Integer pageSize) {
//获取总记录数
String totalSql = "select count(*) from studentInfo ";
//总记录数
Integer totalCount = BaseDAO.getTotal(totalSql,null);
//总页数
Integer totalPage = totalCount%pageSize==0?totalCount/pageSize:totalCount/pageSize+1;
//分页查询
String pageSql = "select s.studentId,s.name,s.sex,s.birthday,s.province," +
" c.classId,c.className " +
" from studentInfo s " +
" join classInfo c " +
" on s.classId = c.classId " +
" order by s.studentId " +
" limit ?,? ";
int start = (pageNo-1)*pageSize;
Object[] params = {start,pageSize};
List<Map<String,Object>> rows = BaseDAO.executeQuery(pageSql,params);
//封装分页数据对象
PageData pd = new PageData();
pd.setPageNo(pageNo);
pd.setPageSize(pageSize);
pd.setTotalPage(totalPage);
pd.setTotalCount(totalCount);
pd.setData(rows);
return pd;
}
}
ClassInfoDAOImpl:
package com.dao.impl;
import com.dao.IClassInfoDAO;
import com.util.BaseDAO;
import java.util.List;
import java.util.Map;
public class ClassInfoDAOImpl implements IClassInfoDAO {
@Override
public List<Map<String, Object>> listAll() {
String sql="select classId,className from classInfo";
return BaseDAO.executeQuery(sql,null);
}
}
IStudentDAO:
package com.dao;
import com.entity.PageData;
import com.entity.Student;
import java.util.List;
import java.util.Map;
public interface IStudentDAO {
List<Map<String,Object>> listAll();
//插入方法
int insert(Student student);
//修改
int update(Student student);
PageData queryByPage(Integer pageNo, Integer pageSize);
//删除:1 2,3,4 delete from student where studentId in ()
int delete(String ids);
}
IClassInfoDAO:
package com.dao;
import java.util.List;
import java.util.Map;
public interface IClassInfoDAO {
List<Map<String ,Object>> listAll();
}
service:
impl:
StudentServiceImpl:
package com.service.impl;
import com.dao.IStudentDAO;
import com.dao.impl.StudentDAOImpl;
import com.entity.PageData;
import com.entity.Student;
import com.service.IStudentService;
import com.util.BaseDAO;
import java.util.List;
import java.util.Map;
public class StudentServiceImpl implements IStudentService {
@Override
public int delete(String ids) {
return studentDAO.delete(ids);
}
private IStudentDAO studentDAO=new StudentDAOImpl();
@Override
public int update(Student student) {
return studentDAO.update(student);
}
@Override
public PageData queryByPage(Integer pageNo, Integer pageSize) {
return studentDAO.queryByPage(pageNo,pageSize);
}
@Override
public int add(Student student) {
return studentDAO.insert(student);
}
@Override
public List<Map<String, Object>> listAll() {
return studentDAO.listAll();
}
}
ClassInfoServiceImpl:
package com.service.impl;
import com.dao.IClassInfoDAO;
import com.dao.impl.ClassInfoDAOImpl;
import com.service.IClassInfoService;
import java.util.List;
import java.util.Map;
public class ClassInfoServiceImpl implements IClassInfoService {
private IClassInfoDAO classInfoDAO=new ClassInfoDAOImpl();
@Override
public List<Map<String, Object>> listAll() {
return classInfoDAO.listAll();
}
}
IStudentService:
package com.service;
import com.entity.PageData;
import com.entity.Student;
import java.util.List;
import java.util.Map;
public interface IStudentService {
List<Map<String,Object>> listAll();
//添加学生
int add(Student student);
int update(Student student);
PageData queryByPage(Integer pageNo, Integer pageSize);
//删除:单个删除和批量删除
int delete(String ids);
}
IClassInfoService:
package com.service;
import java.util.List;
import java.util.Map;
public interface IClassInfoService {
List<Map<String,Object>> listAll();
}
servlet:
StudentServlet:
package com.servlet;
import com.alibaba.fastjson.JSONObject;
import com.entity.CommonResult;
import com.entity.PageData;
import com.entity.Student;
import com.mysql.cj.util.StringUtils;
import com.service.IStudentService;
import com.service.impl.StudentServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
@WebServlet(urlPatterns = "/StudentServlet/*")
public class StudentServlet extends HttpServlet {
private IStudentService studentService = new StudentServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取请求方法
String uri = req.getRequestURI();
String process = uri.substring(uri.lastIndexOf("/")+1);
System.out.println("proccess:"+process);
// //设置响应编码
// resp.setContentType("text/html;charset=utf-8");
//定义处理之后返回的数据对象
Object data = null;
switch (process){
case "query":
data = this.query(req,resp);
break;
case "queryByPage":
data = this.queryByPage(req,resp);
break;
case "queryForLayUI":
data = this.queryForLayUI(req,resp);
break;
case "add":
data=this.add(req,resp);
break;
case "update":
data = this.update(req,resp);
break;
case "del":
data = this.del(req,resp);
break;
}
System.out.println("data:"+data);
//将数据转为json字符串
String jsonStr = JSONObject.toJSONStringWithDateFormat(data,"yyyy-MM-dd");
System.out.println(jsonStr);
PrintWriter out = resp.getWriter(); //获取输出流对象
out.println(jsonStr); //输出json字符串给浏览器
out.flush(); //清空缓存
out.close();//关闭流对象
}
//根据id删除
private Object del(HttpServletRequest req, HttpServletResponse resp) {
String ids = req.getParameter("ids");
int count = studentService.delete(ids);
if (count>0){
return CommonResult.success();
}else{
return CommonResult.fail();
}
}
private Object queryForLayUI(HttpServletRequest req, HttpServletResponse resp) {
//获取前端传入的分页参数
String pageNo = req.getParameter("page");
String pageSize = req.getParameter("limit");
//判断参数是否有效
Integer pn = StringUtils.isNullOrEmpty(pageNo)?1:Integer.parseInt(pageNo);
Integer ps = StringUtils.isNullOrEmpty(pageSize)?3:Integer.parseInt(pageSize);
PageData pd = studentService.queryByPage(pn,ps);
return new CommonResult(0,"success",pd.getTotalCount(),pd.getData());
}
private Object queryByPage(HttpServletRequest req, HttpServletResponse resp) {
//获取前端传入的分页参数
String pageNo = req.getParameter("pageNo");
String pageSize = req.getParameter("pageSize");
//判断参数是否有效
Integer pn = StringUtils.isNullOrEmpty(pageNo)?1:Integer.parseInt(pageNo);
Integer ps = StringUtils.isNullOrEmpty(pageSize)?3:Integer.parseInt(pageSize);
return studentService.queryByPage(pn,ps);
}
private Object update(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("111");
//获取传入的数据
Integer studentId = Integer.parseInt(req.getParameter("studentId"));
String name = req.getParameter("name");
String sex = req.getParameter("sex");
Date birthday = java.sql.Date.valueOf(req.getParameter("birthday"));
String province = req.getParameter("province");
Integer classId = Integer.parseInt(req.getParameter("classId"));
//封装实体对象
Student student = new Student(
studentId,name,sex,birthday,province,classId
);
//调用业务层保存数据
int count = studentService.update(student);
System.out.println("count:"+count);
//定义结果数据
Map<String,Object> res = new HashMap<>();
//添加成功
if(count==1){
//code为0说明处理成功
res.put("code",0);
}else{
//code为1处理失败
res.put("code",1);
}
System.out.println("res:"+res);
return res;
}
//添加
private Object add(HttpServletRequest req, HttpServletResponse resp) {
//获取传入的数据
String name=req.getParameter("name");
String sex=req.getParameter("sex");
Date birthday=java.sql.Date.valueOf(req.getParameter("birthday"));
String province=req.getParameter("province");
Integer classId=Integer.parseInt(req.getParameter("classId"));
//封装实体对象
Student student=new Student(
name,sex,birthday,province,classId
);
//调用业务层保存数据
int count= studentService.add(student);
//定义数据结果
Map<String,Object> res=new HashMap<>();
//添加成功
if(count==1){
//code为0说明处理成功
res.put("code",0);
}else{
//code为1处理失败x`
res.put("code",1);
}
return res;
}
/**
* 执行查询
* @param req
* @param resp
* @return
*/
private Object query(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("=====StudentServlet query=======");
return studentService.listAll();
}
}
ClassInfoServlet:
package com.servlet;
import com.alibaba.fastjson.JSONObject;
import com.entity.CommonResult;
import com.service.IClassInfoService;
import com.service.impl.ClassInfoServiceImpl;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Map;
@WebServlet("/ClassInfoServlet/*")
public class ClassInfoServlet extends HttpServlet {
//业务层对象
private IClassInfoService classInfoService=new ClassInfoServiceImpl();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String uri=req.getRequestURI();
String process=uri.substring(uri.lastIndexOf("/")+1);
//定义结果对象
Object date=null;
switch (process){
case "query":
date=query(req,resp);
break;
}
//输出json字符串
String jsonStr= JSONObject.toJSONString(date);
PrintWriter out=resp.getWriter();
out.println(jsonStr);
out.flush();
out.close();
}
//查询
private Object query(HttpServletRequest req, HttpServletResponse resp) {
List<Map<String,Object>> clsList = classInfoService.listAll();
return CommonResult.success(clsList.size(), clsList);
}
}
AjaxServlet :
package com.servlet;
import com.alibaba.fastjson.JSONArray;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@WebServlet(urlPatterns = "/AjaxServlet")
public class AjaxServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String method = req.getMethod();
System.out.println("method:"+method);
String name = req.getParameter("name");
String sex = req.getParameter("sex");
System.out.println(name+" "+sex);
//String locaDateTime = LocalDateTime.now().toString();
Map<String,Object> map1 = new HashMap<String,Object>();
map1.put("id",1001);
map1.put("name","张三");
map1.put("sex","男");
Map<String,Object> map2 = new HashMap<>();
map2.put("id",1002);
map2.put("name","李四");
map2.put("sex","女");
List<Map<String,Object>> stuList = new ArrayList<>();
stuList.add(map1);
stuList.add(map2);
//String jsonStr = "{\"name\":\"张三\",\"sex\":\"男\"}";
//将java对象转为json字符串:jackson,Gson,fastjson
System.out.println(stuList);
//将数据转为json字符串
String jsonStr = JSONArray.toJSONString(stuList); //实体对象,map
System.out.println(jsonStr);
resp.setContentType("text/html;charset=utf-8");
//获取输出流对象
PrintWriter out = resp.getWriter();
out.println(jsonStr);
out.flush();
out.close();
}
}
filter:
CharacterEncodingFilter:
package com.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import java.io.IOException;
@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
//设置编码
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=utf-8");
//向后传递请求
filterChain.doFilter(servletRequest,servletResponse);
}
}
web:
lay6.jsp:
<%--
Created by IntelliJ IDEA.
User: 33154
Date: 2022/8/9
Time: 8:52
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>开始使用 layui</title>
<!-- 引入 layui.css -->
<%-- <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/assets/plugins/layui-v2.6.8/layui/css/layui.css?t=<%=Math.random()%>"/>--%>
<!-- 引入 layui.css -->
<link rel="stylesheet" href="//unpkg.com/layui@2.6.8/dist/css/layui.css">
</head>
<body>
<!--要渲染的数据表格-->
<table id="stu" lay-filter="stu"></table>
<!--弹出表单-->
<form class="layui-form" action="" style="display: none;margin:10px" id="stuFrm" lay-filter="stuFrm">
<!--学生编号,修改的时候,需要传这个值-->
<input type="hidden" id="studentId" name="studentId"/>
<!--设置提交的地址-->
<input type="hidden" id="action" name="action">
<div class="layui-form-item">
<label class="layui-form-label">姓名</label>
<div class="layui-input-block">
<input type="text" name="name" lay-verify="required" placeholder="请输入姓名" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">单选框</label>
<div class="layui-input-block">
<input type="radio" name="sex" value="男" title="男">
<input type="radio" name="sex" value="女" title="女" checked>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">班级</label>
<div class="layui-input-block">
<select name="classId" id="classId" lay-verify="required">
<option value=""></option>
</select>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">省份</label>
<div class="layui-input-block">
<select name="province" lay-verify="required">
<option value="">请选择</option>
<option value="河南">河南</option>
<option value="河北">河北</option>
<option value="山东">山东</option>
<option value="湖北">湖北</option>
</select>
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">生日</label>
<div class="layui-input-block">
<input type="text" name="birthday" id="birthday" lay-verify="required" placeholder="请输入生日" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button type="button" class="layui-btn" lay-submit lay-filter="stuBtnSubmit">立即提交</button>
<button type="reset" class="layui-btn layui-btn-primary">重置</button>
</div>
</div>
</form>
<!--定义表格工具条-->
<script type="text/html" id="stuBar">
<div class="layui-btn-container">
<!--lay-event:用于设置一个按钮的特定事件,事件名字自己定义-->
<button type="button" class="layui-btn" lay-event="stuAdd">添加</button>
<button type="button" class="layui-btn layui-btn-danger" lay-event="stuBatchDel">批量删除</button>
</div>
</script>
<script type="text/html" id="stuRowBar">
<div class="layui-btn-container">
<!--lay-event:用于设置一个按钮的特定事件,事件名字自己定义-->
<button type="button" class="layui-btn layui-btn-sm" lay-event="stuEdit">编辑</button>
<button type="button" class="layui-btn layui-btn-sm layui-btn-danger" lay-event="stuDel">删除</button>
</div>
</script>
<%--<script type="text/javascript" src="${pageContext.request.contextPath}/assets/plugins/layui-v2.6.8/layui/layui.js?t=<%=Math.random()%>"></script>--%>
<!-- 引入 layui.js -->
<script src="//unpkg.com/layui@2.6.8/dist/layui.js"></script>
<script>
layui.use(['table','layer','laydate','form'], function(){
var table = layui.table //表格组件
,layer=layui.layer //弹出层
,laydate=layui.laydate //日期
,form=layui.form //表单
,$ = layui.$; //jq
//渲染日期框
laydate.render({
elem: "#birthday"
})
//加载班级下拉框
loadClassInfo();
//渲染表格数据
table.render({
elem: '#stu' //渲染的目标元素
,url: '${pageContext.request.contextPath}/StudentServlet/queryForLayUI' //发送请求获取数据
,cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
,toolbar:"#stuBar" //设置表格工具条
,defaultToolbar: ['filter']
,width:1000
,page:true //启用分页
,limit:20 //每页条数
,limits:[5,10,20,30] //可选条数
,cols: [[ //表格列的定义
{title:"全选",type:"checkbox"}
,{field:'studentId', width:80, title: '学号', sort: true}
,{field:'name', width:80, title: '姓名'}
,{field:'sex', width:80, title: '性别', sort: true,templet:function (d){
//console.log(d);
if(d.sex=="男")
return "<font color='blue'>男</font>";
else
return "<font color='red'>女</font>";
}}
,{field:'province', width:80, title: '省份'}
,{field:'birthday', title: '生日', width: '30%', width: 120} //minWidth:局部定义当前单元格的最小宽度,layui 2.2.1 新增
,{field:'classId', title: '班级编号', hide:true}
,{field:'className', title: '班级名字',with:80, sort: true}
,{title:"操作",fixed:"right",toolbar:"#stuRowBar"}
]]
});
//通过table组件监听表格头部工具条触发的事件
//toolbar(stu):表示table组件要监听stu(lay-filter)这个表格的工具条事件
//obj:当工具条中的按钮,触发事件时,layui会将事件信息封装为对象,传入到这个参数中
table.on("toolbar(stu)",function (obj){
console.log(obj);
//根据触发的事件做特定处理
switch (obj.event){
case "stuAdd":
//弹出表单
$("#action").val("${pageContext.request.contextPath}/StudentServlet/add");
showStuFrm();
break;
case "stuBatchDel":
//点击批量删除,获取当前选中行的信息
var checkStatus = table.checkStatus('stu'); //idTest 即为基础参数 id 对应的值
//输出选中行对象属性
//console.log(checkStatus);
//console.log(checkStatus.data) //获取选中行的数据
//console.log(checkStatus.data.length) //获取选中行数量,可作为是否有选中行的条件
//console.log(checkStatus.isAll ) //表格是否全选
//判断当前是否有选中行
if(checkStatus.data.length==0){
layer.msg("请先选中一行");
return;
}
var ids = [];
for(var i=0;i<checkStatus.data.length;i++){
ids.push(checkStatus.data[i].studentId);
}
//拼接数组中的id: 3,4,5,6
ids = ids.join(",");
delStu(ids);
break;
}
})
//通过table组件,监听行工具条事件
table.on("tool(stu)",function (obj){
console.log(obj);
//判断点击按钮的事件
switch (obj.event){
case "stuEdit":
//弹出表单
$("#action").val("${pageContext.request.contextPath}/StudentServlet/update");
showStuFrm();
//为表单设值
form.val("stuFrm",obj.data);
break;
case "stuDel":
layer.confirm("确定要删除么?",function (index){
var ids = obj.data.studentId;
delStu(ids);
//关闭确认框
layer.close(index);
})
break;
}
})
//绑定表单中,提交按钮的提交事件
form.on("submit(stuBtnSubmit)",function (obj){
console.log(obj);
$.ajax({
url:$("#action").val(),
type:"post",
data:obj.field, //表单数据
dataType:"json",
success:function (res){
if(res.code==0){
layer.msg("添加成功",{icon:6});
//关闭表单
layer.close(stuFrmIndex);
//表单重置
$("#stuFrm")[0].reset();
//刷新表格
table.reload('stu', {
page: {
curr: 1 //重新从第 1 页开始
}
});
}else{
layer.msg("添加失败",{icon:5});
}
}
})
})
//删除学生
function delStu(ids){
$.ajax({
url:"${pageContext.request.contextPath}/StudentServlet/del",
data:{ids:ids},
type:"post",
dataType:"json",
success:function (res){
if(res.code==0){
layer.msg("删除成功!",{icon:6});
//重新加载表格
//刷新表格
table.reload('stu', {
page: {
curr: 1 //重新从第 1 页开始
}
});
}else{
layer.msg("删除失败!",{icon:5})
}
}
})
}
//加载班级数据
function loadClassInfo(){
$.ajax({
url:"${pageContext.request.contextPath}/ClassInfoServlet/query",
type: "get",
dataType:"json",
success:function (res){
console.log(res);
//循环数据,将班级添加到下拉框中
for(var i=0;i<res.data.length;i++){
var cls = res.data[i];
$("#classId").append("<option value='"+cls.classId+"'>"+cls.className+"</option>")
}
//重新渲染下拉框
form.render('select')
}
})
}
var stuFrmIndex;
//定义函数弹出学生表单
function showStuFrm(){
//页面层
stuFrmIndex=layer.open({
type: 1,
area: ['600px',"400px"],
content: $('#stuFrm') //弹出页面元素
});
}
});
</script>
</body>
</html>
到了这里,关于layui实现(学生)数据的增删改查的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!