在上一篇文章中已经创建了对应的大后台,接下来来实现对应的子页面
完整后台显示为:
单个子页面Customer.html显示为:
接下来开始说相关的内容:
1.页面主体
<table class="layui-hide" id="customer"></table>
你没看错,就这么一行,就能实现表格,但是我们接下来为它添加其他的组件,
1.1添加编辑和删除
在表格的下方加上
<table class="layui-hide" id="customer"></table>
<!--layui-btn layui-btn-normal layui-btn-sm
样式为一个按钮 样式为对应的颜色 按钮形状的大小 -->
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-sm">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">删除 </a>
</script>
接下来先说数据渲染
1.2数据表格的数据渲染
<script>
layui.use('table', function () {
var table = layui.table;
//数据渲染
table.render({
elem: '#customer'//代表的是你操作的数据表格的编号
, url: '/day01/customer/page'//数据接口
, page: { // 支持传入 laypage 组件的所有参数(某些参数除外,如:jump/elem) - 详见文档
layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'], //自定义分页布局//curr: 5,
groups: 6, //只显示 1 个连续页码
first: false, //不显示首页
last: false //不显示尾页
}
, cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
, cols: [[
{field: 'uuid', width: 180, title: 'UUID', align: 'center'}
, {field: 'username', width: 180, title: '客户账户', align: 'center'}
, {field: 'password', width: 180, title: '客户密码', align: 'center'}
, {field: 'nickname', width: 180, title: '客户昵称', align: 'center'}
, {field: 'gender', width: 180, title: '客户性别', align: 'center'} //minWidth:局部定义当前单元格的最小宽度,layui 2.2.1 新增
, {field: 'addr', width: 180, title: '客户地址', align: 'center', sort: true}
, {fixed: 'right', width: 220, align: 'center', toolbar: '#barDemo'}
]]
,
limit: 12,//页大小
limits: [10, 15, 20, 50, 100]//当前页大小的选项
});
但是这肯定是不够的,我们还需要加上模糊查询的组件,所以:
1.3条件查询的输入框
<!-- 搜索栏 -->
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">客户账户:</label>
<div class="layui-input-inline" style="width: 150px">
<input type="text" id="username" name="username" placeholder="请输入客户名称" autocomplete="off"
class="layui-input">
</div>
<label class="layui-form-label">客户昵称:</label>
<div class="layui-input-inline" style="width: 150px">
<input type="text" id="nickname" name="nickname" placeholder="请输入客户昵称" autocomplete="off"
class="layui-input">
</div>
<label class="layui-form-label">客户地址:</label>
<div class="layui-input-inline" style="width: 150px">
<input type="text" id="addr" name="addr" placeholder="请输入客户地址" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-inline">
<div class="layui-input-inline">
<button id="btn_search" type="button" class="layui-btn layui-btn-normal">
<i class="layui-icon layui-icon-search"></i>
查询
</button>
<button id="btn_reset" type="button" class="layui-btn layui-btn-normal">
重置
</button>
</div>
</div>
<div class="layui-inline">
<div class="layui-input-inline">
<button id="btn_add" type="button" class="layui-btn layui-btn-warm layui-btn-radius">
<i class="layui-icon layui-icon-add-1"></i>
新增
</button>
</div>
</div>
</div>
<!--搜索栏结束-->
<table class="layui-hide" id="customer"></table>
<!--layui-btn layui-btn-normal layui-btn-sm
样式为一个按钮 样式为对应的颜色 按钮形状的大小 -->
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-sm">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">删除 </a>
</script>
<script src="layui/layui.js" charset="utf-8"></script>
<script src="js/jquery-3.3.1.js"></script>
<!-- 注意 :如果你直接复制所有代码到本地,上述 JS 路径需要改成你本地的 -->
<script>
layui.use('table', function () {
var table = layui.table;
//数据渲染
table.render({
elem: '#customer'//代表的是你操作的数据表格的编号
, url: '/day01/customer/page'//数据接口
, page: { // 支持传入 laypage 组件的所有参数(某些参数除外,如:jump/elem) - 详见文档
layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'], //自定义分页布局//curr: 5,
groups: 6, //只显示 1 个连续页码
first: false, //不显示首页
last: false //不显示尾页
}
, cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
, cols: [[
{field: 'uuid', width: 180, title: 'UUID', align: 'center'}
, {field: 'username', width: 180, title: '客户账户', align: 'center'}
, {field: 'password', width: 180, title: '客户密码', align: 'center'}
, {field: 'nickname', width: 180, title: '客户昵称', align: 'center'}
, {field: 'gender', width: 180, title: '客户性别', align: 'center'} //minWidth:局部定义当前单元格的最小宽度,layui 2.2.1 新增
, {field: 'addr', width: 180, title: '客户地址', align: 'center', sort: true}
, {fixed: 'right', width: 220, align: 'center', toolbar: '#barDemo'}
]]
,
limit: 12,//页大小
limits: [10, 15, 20, 50, 100]//当前页大小的选项
});
});
</script>
</body>
接下来开始说关于后台servlet相关的内容
2.数据接口
第一件事就是需要明白,layui需要的数据和我们使用的json数据是不太一样的,
layui需要的数据为
{
"code": 0,
"msg": "",
"count": 1000,
"data": [{}, {}],
}
只有data中才是我们平时使用的json,当code返回值为0等同于页面响应码的200,msg的值为返回的消息内容,count为总数据的条数,因为layui会直接帮我们分页,那么我们就可以设置一个继承自HashMap的数据的工具类
package util;
import java.util.HashMap;
public class ToLayuiData extends HashMap {
public ToLayuiData addData(String key, Object value) {
this.put(key, value);
return this;
}
public static ToLayuiData error(int code, String msg) {
ToLayuiData r = new ToLayuiData();
r.addData("success", false).addData("code", code).addData("msg", msg);
return r;
}
public static ToLayuiData success(int code, String msg,long count,Object data) {
ToLayuiData r = new ToLayuiData();
r.addData("success", true).addData("code", code).addData("msg", msg).addData("count", count).addData("data", data);
return r;
}
public static ToLayuiData success(int code, String msg, Object data) {
ToLayuiData r = new ToLayuiData();
r.addData("success", true).addData("code", code).addData("msg", msg).addData("data", data);
return r;
}
@Override
public String toString() {
return "{"+"\"code\":"+this.get("code").toString()+","
+"\"msg\":"+"\""+this.get("msg").toString()+"\""+","
+"\"count\":"+this.get("count").toString()+","
+"\"data\":"+this.get("data").toString()
+"}";
}
}
如上所述,我已经重写了toString方法,这样的话,我们就可以通过toString直接拿到对应的参数,而静态方法success可以直接赋值json类型的data。
接下来就是数据的查询:
3.数据库与mybatis的查询
如果是jdbc也是类似的,就不再说明了
3.1数据库的表与实体类
表Customer
CREATE TABLE `customer` (
`uuid` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(16) NOT NULL,
`password` varchar(16) NOT NULL DEFAULT '123456789',
`nickname` varchar(15) NOT NULL DEFAULT '张三的一家' COMMENT '昵称',
`gender` varchar(1) NOT NULL DEFAULT '男',
`addr` varchar(100) NOT NULL DEFAULT '中国长沙',
PRIMARY KEY (`uuid`)
) ENGINE=InnoDB AUTO_INCREMENT=1000524 DEFAULT CHARSET=gbk;
实体类:
package pojo;
public class Customer {
int uuid;
String username;
String password;
String nickname;
String gender;
String addr;
public Customer() {
}
public Customer(String username, String password, String nickname) {
this.username = username;
this.password = password;
this.nickname = nickname;
}
public Customer(String username, String password) {
this.username = username;
this.password = password;
}
public Customer(int uuid, String username, String password, String nickname, String gender, String addr) {
this.uuid = uuid;
this.username = username;
this.password = password;
this.nickname = nickname;
this.gender = gender;
this.addr = addr;
}
public Customer(String username, String password, String nickname, String gender, String addr) {
this.username = username;
this.password = password;
this.nickname = nickname;
this.gender = gender;
this.addr = addr;
}
public Customer(int uuid, String nickname, String gender, String addr) {
this.uuid = uuid;
this.nickname = nickname;
this.gender = gender;
this.addr = addr;
}
public int getUuid() {
return uuid;
}
public void setUuid(int uuid) {
this.uuid = uuid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getAddr() {
return addr;
}
public void setAddr(String addr) {
this.addr = addr;
}
@Override
public String toString() {
return "Customer{" +
"uuid=" + uuid +
", username='" + username + '\'' +
", password='" + password + '\'' +
", nickname='" + nickname + '\'' +
", gender='" + gender + '\'' +
", addr='" + addr + '\'' +
'}';
}
}
3.2mybatis的 sqlSession工具类与查询语句与xml配置文件
sqlSession工具类:
package util;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
public class GetSqlSession {
public static SqlSession getSqlSession() throws IOException {
/*Resources配置文件的数据*/
String resource = "mybatis-config.xml";
//通过资源文件类去获取文件中的流
InputStream inputStream = Resources.getResourceAsStream(resource);
/*通过sql会话工厂构建器 SqlSessionFactoryBuilder 去构建一个sql会话工厂的对象*/
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//从 SqlSessionFactory 中获取 SqlSession {操作mapper中的这些sql的方法}
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}
mybatis的配置文件:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!--类的别名-->
<typeAliases>
<typeAlias alias="customer" type="pojo.Customer"/>
</typeAliases>
<!--
environments:配置数据库连接环境信息。可以配置多个environment,通过default属性切换不同的environment
-->
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<!--数据库连接信息-->
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql:///shop?useSSL=false&userUnicode=true&characterEncoding=utf-8&serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="123"/>
</dataSource>
</environment>
</environments>
<!--此处填写你需要引入的mapper的包的位置-->
<mappers>
<package name="mapper"/>
</mappers>
</configuration>
CustomerMapper:
由于这里sql比较简单,直接使用注解开发
//分页查询全部的客户信息
@Select("select * from customer limit #{startIndex} ,#{pageSize}")
List<Customer> selectPage(@Param("startIndex") int startIndex,@Param("pageSize") int pageSize);
@Select("select count(*) from customer")
int selectCount();
最后重点:servlet
3.servlet
我这里使用的是继承BaseServlet
31.BaseServlet
package util;
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.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
@WebServlet("/BaseServlet")
public class BaseServlet extends HttpServlet {
@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//完成方法的分发
//1.获取请求路径
String url = request.getRequestURI(); //返回的是 /travel/user/add等
System.out.println("请求url:" + url); // /travel/user/add
//2.获取方法名称
String methodName = url.substring(url.lastIndexOf('/') + 1);
System.out.println("方法名称:" + methodName);
//3.获取方法对象Method this:谁调用我?我代表谁
// System.out.println(this); //对应的Servlet的对象
try {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//getDeclaredMethod方法是忽略访问权限修饰符,获取方法,包括私有的方法都可以获取到
Method method = this.getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
//4.执行方法
method.invoke(this, request, response);
} catch (NoSuchMethodException e) {
System.out.println("没有此方法");
e.printStackTrace();
} catch (InvocationTargetException e) {
System.out.println("反射出错");
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
然后再是CustomerServlet
import mapper.CustomerMapper;
import pojo.Customer;
import util.BaseServlet;
import util.GetSqlSession;
import util.ToLayuiData;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet("/customer/*")
public class CustomerServlet extends BaseServlet {
public void page(HttpServletRequest request, HttpServletResponse response) {
try {
//拿到页面传过来的两个参数 page当前页 limit页大小
int page = Integer.parseInt(request.getParameter("page"));
int limit = Integer.parseInt(request.getParameter("limit"));
//获取代理对象
CustomerMapper mapper = GetSqlSession.getSqlSession().getMapper(CustomerMapper.class);
//分页查询 select * from customer limit ?, ? 代表起始下标 页大小 10
// 起始下标=(当前页大小-1)*页大小
List<Customer> customers = mapper.selectPage((page - 1) * limit, limit);
//查询总条数
int count = mapper.selectCount();
//将查出来的数据转换为json格式
ObjectMapper objectMapper = new ObjectMapper();
String data = objectMapper.writeValueAsString(customers);
//需要四个值code msg count data
ToLayuiData layuiData = ToLayuiData.success(0, "成功", count, data);
//将这个数据返回给页面进行渲染
response.getWriter().write(layuiData.toString());
System.out.println(layuiData);
} catch (IOException e) {
e.printStackTrace();
}
}
}
数据渲染的url是:url: ‘/day01/customer/page’//数据接口
与servlet的方法对应
然后是最后的完正的页面代码:
4.页面全部内容
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Layui</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="stylesheet" href="layui/css/layui.css" tppabs="http://res.layui.com/layui/dist/css/layui.css"
media="all">
<!-- 注意:如果你直接复制所有代码到本地,上述css路径需要改成你本地的 -->
</head>
<body>
<!-- 搜索栏 -->
<div class="layui-form-item">
<div class="layui-inline">
<label class="layui-form-label">客户账户:</label>
<div class="layui-input-inline" style="width: 150px">
<input type="text" id="username" name="username" placeholder="请输入客户名称" autocomplete="off"
class="layui-input">
</div>
<label class="layui-form-label">客户昵称:</label>
<div class="layui-input-inline" style="width: 150px">
<input type="text" id="nickname" name="nickname" placeholder="请输入客户昵称" autocomplete="off"
class="layui-input">
</div>
<label class="layui-form-label">客户地址:</label>
<div class="layui-input-inline" style="width: 150px">
<input type="text" id="addr" name="addr" placeholder="请输入客户地址" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-inline">
<div class="layui-input-inline">
<button id="btn_search" type="button" class="layui-btn layui-btn-normal">
<i class="layui-icon layui-icon-search"></i>
查询
</button>
<button id="btn_reset" type="button" class="layui-btn layui-btn-normal">
重置
</button>
</div>
</div>
<div class="layui-inline">
<div class="layui-input-inline">
<button id="btn_add" type="button" class="layui-btn layui-btn-warm layui-btn-radius">
<i class="layui-icon layui-icon-add-1"></i>
新增
</button>
</div>
</div>
</div>
<!--搜索栏结束-->
<table class="layui-hide" id="customer"></table>
<!--layui-btn layui-btn-normal layui-btn-sm
样式为一个按钮 样式为对应的颜色 按钮形状的大小 -->
<script type="text/html" id="barDemo">
<a class="layui-btn layui-btn-sm">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-sm" lay-event="del">删除 </a>
</script>
<script src="layui/layui.js" charset="utf-8"></script>
<script src="js/jquery-3.3.1.js"></script>
<!-- 注意 :如果你直接复制所有代码到本地,上述 JS 路径需要改成你本地的 -->
<script>
layui.use('table', function () {
var table = layui.table;
//数据渲染
table.render({
elem: '#customer'//代表的是你操作的数据表格的编号
, url: '/day01/customer/page'//数据接口
, page: { // 支持传入 laypage 组件的所有参数(某些参数除外,如:jump/elem) - 详见文档
layout: ['limit', 'count', 'prev', 'page', 'next', 'skip'], //自定义分页布局//curr: 5,
groups: 6, //只显示 1 个连续页码
first: false, //不显示首页
last: false //不显示尾页
}
, cellMinWidth: 80 //全局定义常规单元格的最小宽度,layui 2.2.1 新增
, cols: [[
{field: 'uuid', width: 180, title: 'UUID', align: 'center'}
, {field: 'username', width: 180, title: '客户账户', align: 'center'}
, {field: 'password', width: 180, title: '客户密码', align: 'center'}
, {field: 'nickname', width: 180, title: '客户昵称', align: 'center'}
, {field: 'gender', width: 180, title: '客户性别', align: 'center'} //minWidth:局部定义当前单元格的最小宽度,layui 2.2.1 新增
, {field: 'addr', width: 180, title: '客户地址', align: 'center', sort: true}
, {fixed: 'right', width: 220, align: 'center', toolbar: '#barDemo'}
]]
,
limit: 12,//页大小
limits: [10, 15, 20, 50, 100]//当前页大小的选项
});
});
</script>
</body>
</html>