Demo简介
Demo使用Java、Servlet为后台代码(数据库已添加数据),前端使用EasyUI框架,后台直接返回JSON数据给页面
1.配置Web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>easyui_pagination_demo</display-name>
<welcome-file-list>
<welcome-file>backend.jsp</welcome-file>
</welcome-file-list> <!-- 前端分页Servlet -->
<servlet>
<servlet-name>studentServletFront</servlet-name>
<servlet-class>com.servlets.StudentServletFrontEnd</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>studentServletFront</servlet-name>
<url-pattern>/stuDatagridDataFront.do</url-pattern>
</servlet-mapping> <!-- 后端分页Servlet -->
<servlet>
<servlet-name>studentServletBack</servlet-name>
<servlet-class>com.servlets.StudentServletBackEnd</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>studentServletBack</servlet-name>
<url-pattern>/stuDatagridDataBack.do</url-pattern>
</servlet-mapping>
</web-app>
2.创建实体类Student
package com.models; /**
* 学生类
*
* @author yyx 2019年1月8日
*/
public class Student {
private String stuId;
private String stuSno;
private String stuName;
private Integer stuSex;
private Integer stuAge;
private String stuEmail;
private String stuQQ;
private String stuAddress; public String getStuId() {
return stuId;
} public void setStuId(String stuId) {
this.stuId = stuId;
} public String getStuSno() {
return stuSno;
} public void setStuSno(String stuSno) {
this.stuSno = stuSno;
} public String getStuName() {
return stuName;
} public void setStuName(String stuName) {
this.stuName = stuName;
} public Integer getStuSex() {
return stuSex;
} public void setStuSex(Integer stuSex) {
this.stuSex = stuSex;
} public Integer getStuAge() {
return stuAge;
} public void setStuAge(Integer stuAge) {
this.stuAge = stuAge;
} public String getStuEmail() {
return stuEmail;
} public void setStuEmail(String stuEmail) {
this.stuEmail = stuEmail;
} public String getStuQQ() {
return stuQQ;
} public void setStuQQ(String stuQQ) {
this.stuQQ = stuQQ;
} public String getStuAddress() {
return stuAddress;
} public void setStuAddress(String stuAddress) {
this.stuAddress = stuAddress;
} }
3.创建工具类
package com.utils; import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties; /**
* 读取jdbc.properties文件
*
* @author yyx 2019年1月8日
*/
public class JdbcUtil {
private static String driver;
private static String url;
private static String user;
private static String password; private JdbcUtil() {
} static {
try {
/**
* 使用properties集合读取配置信息
*/
InputStream inputStream = JdbcUtil.class.getClassLoader().getResourceAsStream("jdbc.properties");
Properties properties = new Properties();
properties.load(inputStream); driver = properties.getProperty("driver");
url = properties.getProperty("jdbcUrl");
user = properties.getProperty("user");
password = properties.getProperty("password"); if (driver != null) {
Class.forName(driver);
}
} catch (Exception ex) {
ex.printStackTrace();
}
} /**
* 获取Connection
*
* @return
*/
public static Connection getConnection() {
Connection connection = null;
try {
if (url != null && user != null && password != null) {
connection = DriverManager.getConnection(url, user, password);
return connection;
}
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
} /**
* 释放资源 Connection conn, PreparedStatement pst, ResultSet rs
* 在方法内判断空
* @param conn
* @param pst
* @param rs
*/
public static void colseResource(Connection conn, PreparedStatement pst, ResultSet rs) {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
} if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package com.utils; import java.sql.ResultSet;
import java.sql.ResultSetMetaData; import com.google.gson.JsonArray;
import com.google.gson.JsonObject; /**
* JSON转换工具类
*
* @author yyx 2019年1月8日
*/
public class JsonUtil {
/**
* 使用Gson将ResultSet结果集转换成JsonArray 调用方法前判断空
*
* @param rs
* @return
*/
public static JsonArray fromResultSetToJson(ResultSet rs) {
try {
// json数组
JsonArray jsonArray = new JsonArray();
// 获取列数
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount(); // 遍历ResultSet中的每条数据
while (rs.next()) {
JsonObject jsonObj = new JsonObject(); // 遍历每一列
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnLabel(i);
String value = rs.getString(columnName);
jsonObj.addProperty(columnName, value);
}
jsonArray.add(jsonObj);
} return jsonArray;
} catch (Exception ex) { }
return null;
}
}
package com.utils; import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse; /**
* 用于将后台处理相关业务逻辑后得到的最终结果返回到前端, 可以是页面,也可以是js异步调用的结果
*
* @author yyx 2019年1月8日
*/
public class ResponseUtil { public static void write(HttpServletResponse response, Object o) throws Exception {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
out.println(o.toString());
out.flush();
out.close();
}
}
4.创建数据库配置文件jdbc.properties
driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/db_pagination
user=root
password=iytb890214
前端分页(即假分页)
前端分页就是将所有要显示的数据全部查询出来后,进行前台的分页,适合数据量较小的Web项目
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>前端分页</title>
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/jquery-easyui-1.5.1/themes/default/easyui.css">
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/jquery-easyui-1.5.1/themes/icon.css">
<script type="text/javascript"
src="${pageContext.request.contextPath}/jquery-easyui-1.5.1/jquery.min.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath}/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath}/jquery-easyui-1.5.1/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#studatagrid").datagrid({
title : "基本数据表格",
singleSelect : true,
collapsible : true,
fitColumns : true,
rownumbers : true,
fit : true,
pagination : true,
pageSize : 10,
pageList : [ 10, 20, 40 ],
loadFilter : partPurchasePagerFilter,
url : '${pageContext.request.contextPath}/stuDatagridData.do',
})
}) //通用分页
function partPurchasePagerFilter(data) {
if (typeof data.length == 'number' && typeof data.splice == 'function') {
data = {
total : data.length,
rows : data
}
}
var dg = $(this);
var opts = dg.datagrid('options');
var pager = dg.datagrid('getPager');
pager.pagination({
onSelectPage : function(pageNum, pageSize) {
opts.pageNumber = pageNum;
opts.pageSize = pageSize;
pager.pagination('refresh', {
pageNumber : pageNum,
pageSize : pageSize
});
dg.datagrid('loadData', data);
}
});
if (!data.originalRows) {
data.originalRows = (data.rows);
}
var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
var end = start + parseInt(opts.pageSize);
data.rows = (data.originalRows.slice(start, end));
return data;
}
</script>
</head>
<body class="easyui-layout">
<div data-options="region:'center',title:'center title'"
style="padding: 5px; background: #eee;">
<table id="studatagrid" class="easyui-datagrid"
style="width: 100%; height: 100%">
<thead data-options="frozen:true">
<tr>
<th data-options="field:'stuId',hidden:true"></th>
<th data-options="field:'stuSno',width:150,align:'center'">学生学号</th>
<th data-options="field:'stuName',width:150,align:'center'">学生姓名</th>
</tr>
</thead>
<thead>
<tr>
<th data-options="field:'stuSex',width:100,align:'center'">学生性别</th>
<th data-options="field:'stuAge',width:100,align:'center'">学生年龄</th>
<th data-options="field:'stuEmail',width:100,align:'center'">学生邮箱</th>
<th data-options="field:'stuQQ',width:100,align:'center'">学生QQ</th>
<th data-options="field:'stuAddress',width:200,align:'center'">学生地址</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
package com.servlets; import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.utils.JdbcUtil;
import com.utils.JsonUtil;
import com.utils.ResponseUtil; public class StudentServletFrontEnd extends HttpServlet {
private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = JdbcUtil.getConnection();
String sql = "select * from easyui_pagination_stu";
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery(); JsonObject jsonObject = new JsonObject();
if (resultSet != null) {
JsonArray jsonArray = JsonUtil.fromResultSetToJson(resultSet); //Json对象赋值
jsonObject.addProperty("total", jsonArray.size());
jsonObject.add("rows", jsonArray); ResponseUtil.write(resp, jsonObject.toString());
}
} catch (Exception e) { } finally {
JdbcUtil.colseResource(connection, preparedStatement, resultSet);
}
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
} }
后端分页(即真分页)
后端分页就是将分页参数[第几页](pageIndex)和[一页多少数据](pageSize)传递给后台,快速的查询数据,适合数据量大的项目
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>后端分页</title>
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/jquery-easyui-1.5.1/themes/default/easyui.css">
<link rel="stylesheet" type="text/css"
href="${pageContext.request.contextPath}/jquery-easyui-1.5.1/themes/icon.css">
<script type="text/javascript"
src="${pageContext.request.contextPath}/jquery-easyui-1.5.1/jquery.min.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath}/jquery-easyui-1.5.1/jquery.easyui.min.js"></script>
<script type="text/javascript"
src="${pageContext.request.contextPath}/jquery-easyui-1.5.1/locale/easyui-lang-zh_CN.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#studatagrid").datagrid({
title : "基本数据表格",
singleSelect : true,
collapsible : true,
fitColumns : true,
rownumbers : true,
fit : true,
pagination : true,
pageSize : 10,
pageList : [ 10, 20, 40 ],
url : '${pageContext.request.contextPath}/stuDatagridDataBack.do',
})
})
</script>
</head>
<body class="easyui-layout">
<div data-options="region:'center',title:'center title'"
style="padding: 5px; background: #eee;">
<table id="studatagrid" class="easyui-datagrid"
style="width: 100%; height: 100%">
<thead data-options="frozen:true">
<tr>
<th data-options="field:'stuId',hidden:true"></th>
<th data-options="field:'stuSno',width:150,align:'center'">学生学号</th>
<th data-options="field:'stuName',width:150,align:'center'">学生姓名</th>
</tr>
</thead>
<thead>
<tr>
<th data-options="field:'stuSex',width:100,align:'center'">学生性别</th>
<th data-options="field:'stuAge',width:100,align:'center'">学生年龄</th>
<th data-options="field:'stuEmail',width:100,align:'center'">学生邮箱</th>
<th data-options="field:'stuQQ',width:100,align:'center'">学生QQ</th>
<th data-options="field:'stuAddress',width:200,align:'center'">学生地址</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
package com.servlets; import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.utils.JdbcUtil;
import com.utils.JsonUtil;
import com.utils.ResponseUtil; public class StudentServletBackEnd extends HttpServlet {
private static final long serialVersionUID = 1L; @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
int pageNo = Integer.parseInt(req.getParameter("page"));
int pageSize = Integer.parseInt(req.getParameter("rows"));
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// 这里可以使用缓存,从缓存中获取结果;
// 如果为空,则重新获取并存入缓存,缓存需要设置过期时间
int total = getCount();
String sql = "select * from easyui_pagination_stu limit " + (pageNo - 1) * pageSize + "," + pageSize;
connection = JdbcUtil.getConnection();
preparedStatement = connection.prepareStatement(sql);
resultSet = preparedStatement.executeQuery();
JsonObject jsonObject = new JsonObject();
if (resultSet != null) {
JsonArray jsonArray = JsonUtil.fromResultSetToJson(resultSet);
jsonObject.addProperty("total", total);
jsonObject.add("rows", jsonArray);
System.out.println(jsonObject.toString());
ResponseUtil.write(resp, jsonObject.toString());
}
} catch (Exception ex) { } finally {
JdbcUtil.colseResource(connection, preparedStatement, resultSet);
}
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
} protected int getCount() {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
int total = 0;
try {
connection = JdbcUtil.getConnection();
String countStr = "select count(*) from easyui_pagination_stu";
preparedStatement = connection.prepareStatement(countStr);
resultSet = preparedStatement.executeQuery();
if (resultSet != null) {
while (resultSet.next()) {
total = resultSet.getInt(1);
}
System.out.println(total);
return total;
}
} catch (Exception ex) { } finally {
JdbcUtil.colseResource(connection, preparedStatement, resultSet);
}
return total;
}
}