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;
}
}

EasyUI表格DataGrid前端分页和后端分页的总结的更多相关文章

  1. vue2.0+Element UI 表格前端分页和后端分页

    之前写过一篇博客,当时对element ui框架还不太了解,分页组件用 html + css 自己写的,比较麻烦,而且只提到了后端分页 (见 https://www.cnblogs.com/zdd20 ...

  2. django项目一 分页器(前端分页和后端分页区别)

    1. 客户信息展示 1. 母版和继承 {% extends 'layout'%} {% load static%} {% static '文件路径' %} block css js content 2 ...

  3. jQuery--dataTable 前端分页与后端分页 及遇到的问题

    (1)区别 前端分页:一次性把所有数据全都放在前端,由前端进行处理:适合请求的数据量不大的情况 后端分页:服务器模式,所有的分页,搜索,排序等操作在服务器端完成,然后前端去请求数据:适合量大的情况 ( ...

  4. Easyui的datagrid结合hibernate实现数据分页

    最近在学习easyui的使用,在学到datagrid的时候遇到了一些问题,终于抽点时间整理了一下,分享出来,请各位前辈高手多多指教! 1.先来看看效果,二话不说,上图直观! 2.easyui的data ...

  5. 运用EasyUI中datagrid读取数据库数据实现分页

    1dao层 package com.hanqi.dao; import java.util.ArrayList; import java.util.List; import org.hibernate ...

  6. C#的WebApi 与 EasyUi的DataGrid结合生成的可分页界面

    1.从数据库每次取出的数据为当前分页的数据. 2.分页用的是EasyUI 的 Pagination控件,与DataGrid是相对独立的. 3.后台数据获取是通过WebApi去获取. 4.传入参数是:p ...

  7. EasyUI表格DataGrid格式化formatter用法

    1.通过HTML标签创建数据表格时使用formatter <!DOCTYPE html> <html> <head> <meta charset=" ...

  8. EasyUI表格DataGrid获取数据的方式

       第一种方式:直接返回JSON数据 package com.easyuijson.util; import java.text.SimpleDateFormat; import net.sf.js ...

  9. 利用EasyUI 数据网格(DataGrid)的loader属性实现后端分页

    该属性在easyui官方文档中并没有详细阐述,通过简单的资料查询和摸索,实现了easyUI数据网格的后端分页功能. 在官网文档中这样阐述loader属性: 定义如何从远程服务器加载数据.返回false ...

随机推荐

  1. ORACLE network environment

    监听程序 建立网络连接 要建立客户机或中间层连接,Oracle Net要求客户机 下列事项: 运行监听程序的主机 监听程序监视的端口 监听程序使用的协议 监听程序处理的服务名 Hostname/ip ...

  2. LeetCode 784 Letter Case Permutation 解题报告

    题目要求 Given a string S, we can transform every letter individually to be lowercase or uppercase to cr ...

  3. LeetCode 575 Distribute Candies 解题报告

    题目要求 Given an integer array with even length, where different numbers in this array represent differ ...

  4. JQuery is()与hasClass()方法的对比

    is()和hasClass()方法都可以用以检查匹配的所有元素里是否含有指定类名,虽说hasClass(className)函数等价于is(“.className”) 但is()方法比hasClass ...

  5. 函数 call、apply、bind的使用

    [优雅代码]深入浅出 妙用Javascript中apply.call.bind (转载而来)   这篇文章实在是很难下笔,因为网上相关文章不胜枚举. 巧合的是前些天看到阮老师的一篇文章的一句话: “对 ...

  6. 快速安装elkstack

    一.介绍 The Elastic Stack - 它不是一个软件,而是Elasticsearch,Logstash,Kibana 开源软件的集合,对外是作为一个日志管理系统的开源方案.它可以从任何来源 ...

  7. MSSQL2008 部署及开启远程连接

    最近不少用户在windows2003 server 32位操作系统上安装SQL Server2008总是失败,出现大量错误.今天经过通过我反复测试安装,找出了一个便捷的安装方法,节省大家宝贵时间,具体 ...

  8. python基础数据类型考试题

    Python基础数据类型考试题 考试时间:两个半小时                      满分100分(80分以上包含80分及格) 一,基础题. 1,简述变量命名规范(3分) 2,字节和位的关系 ...

  9. 【托业】【新托业TOEIC新题型真题】学习笔记8-题库五->P7

    ———————————————————单词———————————————————— minister 部长 construction contractor 施工方 commence 开始:着手 bac ...

  10. springboot + mybatis配置分页插件

    一:使用pagehelper配置分页插件 1:首先配置springboot +mybatis框架  参考:http://www.cnblogs.com/liyafei/p/7911549.html 2 ...