layui实现数据的展示(查找)和分页
数据库/表:
运行效果展示:
整体代码布局:
代码:
创建数据库:
#创建数据库
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 javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.sql.*;
import java.util.*;
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 + '\'' +
'}';
}
}
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 CommonResult(String msg, Integer count, Object data) {
this.msg = msg;
this.count = count;
this.data = data;
}
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 +
'}';
}
}
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 +
'}';
}
}
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 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);
}
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 {
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);
}
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;
}
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();//关闭流对象
}
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.mysql.cj.xdevapi.JsonString;
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;
@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) {
return classInfoService.listAll();
}
}
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" %>
<html>
<head>
<title>Title</title>
<!-- 引入 layui.css -->
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/assets/plugins/layui-v2.6.8/layui/css/layui.css">
</head>
<body>
<!--要渲染的数据表格-->
<table id="stu"></table>
<!--弹出表单-->
<!-- 引入 layui.js -->
<script type="text/javascript" src="${pageContext.request.contextPath}/assets/plugins/layui-v2.6.8/layui/layui.js"></script>
<script>
layui.use('table', function(){
var table = layui.table;
//渲染表格数据
table.render({
elem: '#stu' //渲染的目标元素
,url: '${pageContext.request.contextPath}/StudentServlet/queryForLayUI' //发送请求获取数据
,cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
,page:true //启用分页
,cols: [[ //表格列的定义
{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%', minWidth: 100} //minWidth:局部定义当前单元格的最小宽度,layui 2.2.1 新增
,{field:'classId', title: '班级编号', hidden:true}
,{field:'className', title: '班级名字', sort: true}
]]
});
});
</script>
</body>
</html>
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
// A code block
var foo = 'bar';
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/118065.html