EasyUI非同步分頁
阿新 • • 發佈:2019-01-06
1.使用技術
EasyUI+servlet+c3p0+mysql
2.搭建環境
匯入EasyUI的樣式表和js檔案:<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.7.0</version> </dependency> <dependency> <groupId>commons-collections</groupId> <artifactId>commons-collections</artifactId> <version>3.1</version> </dependency> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.4</version> </dependency> <dependency> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> <version>1.1.1</version> </dependency> <dependency> <groupId>net.sf.ezmorph</groupId> <artifactId>ezmorph</artifactId> <version>1.0.4</version> </dependency> <dependency> <groupId>net.sf.json-lib</groupId> <artifactId>json-lib</artifactId> <classifier>jdk15</classifier> <version>2.4</version> </dependency> <dependency> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.2.1</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.22</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies>
c3p0配置檔案:
c3p0-config.xml:
<c3p0-config> <!-- 預設配置 --> <default-config> <property name="jdbcUrl">jdbc:mysql://localhost:3306/basicjdbc?characterEncoding=utf-8</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="user">root</property> <property name="password"></property> <property name="initialPoolSize">3</property> <property name="maxPoolSize">6</property> <property name="maxIdleTime">1000</property> </default-config> <!-- 以下的配置用於個人需要再配置 --> <name-config name="my_config"> <property name="jdbcUrl">jdbc:mysql://localhost:3306/basicjdbc?characterEncoding=utf-8</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="user">root</property> <property name="password"></property> <property name="initialPoolSize">3</property> <property name="maxPoolSize">6</property> <property name="maxIdleTime">1000</property> </name-config> </c3p0-config>
3.實現
工具類:
DbUtil.java操作資料庫:
PageUtil.java分頁工具:public class DbUtil { private static DataSource dataSource=null; static{ dataSource=new ComboPooledDataSource(); } public static Connection getConnection(){ try{ return dataSource.getConnection(); }catch(SQLException e){ throw new RuntimeException(e); } } //釋放物件的連線 public static void close(Connection conn,Statement stmt,ResultSet rs){ if(rs !=null){ try{ rs.close(); }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(e); } } if(stmt !=null){ try{ stmt.close(); }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(e); } } if(conn !=null){ try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); throw new RuntimeException(e); } } } }
public class PageUtil {
/*引數需要頁面傳入*/
private Integer pageSize=10;//每頁顯式多少條記錄
private Integer currentPage=1;//當前頁號
/*引數需要從資料查詢*/
private Integer allRowsAmount=0;//總記錄數
private List<?> items;//記錄集合
/*這些引數由計算得出*/
private Integer allPageAmount;//總頁數
private Integer currentPageStartRow=1;//當前頁面的開始行
private Integer currentPageEndRow;//當前頁面的結束行
private Integer firstPage=1;//首頁的頁號
private Integer lastPage;//末頁的頁號
private Integer prevPage;//上一頁頁號
private Integer nextPage;//下一頁頁號
private Integer startPageNum;//導航開始頁號
private Integer endPageNum;//導航結束頁號
private Integer maxPageAmount =10;//最多顯示多少頁
public List<Integer> showPageNums =new ArrayList<Integer>();//要顯示的頁號
public PageUtil() {
super();
// TODO Auto-generated constructor stub
}
/*設定當前頁*/
public void setCurrentPage(int currentPage){
if(currentPage <1){
this.currentPage=1;
}else{
this.currentPage=currentPage;
}
}
/*設定每頁記錄數,預設10條*/
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
/*設定總記錄數*/
public void setAllRowsAmount(int allRowsAmount) {
this.allRowsAmount = allRowsAmount;
}
/*設定分頁內容*/
public void setItems(List<?> items) {
this.items = items;
}
/*設定導航頁數量*/
public void setMaxPageAmount(int maxPageAmount) {
this.maxPageAmount = maxPageAmount;
}
public void calculatePage(){
//計算總頁數
if(this.allRowsAmount % this.pageSize ==0){
this.allPageAmount=this.allRowsAmount/this.pageSize;
}else{
this.allPageAmount=this.allRowsAmount/this.pageSize+1;
}
//設定首頁
this.firstPage=1;
//設定末頁
this.lastPage=this.allPageAmount;
if(this.currentPage *pageSize <allRowsAmount){
this.currentPageEndRow =this.currentPage*pageSize;
this.currentPageStartRow =(this.currentPage-1)*pageSize+1;
}else{
this.currentPageEndRow =this.allRowsAmount;
this.currentPageStartRow =(this.allPageAmount-1)*pageSize+1;
if(this.currentPageStartRow <0){
this.currentPageStartRow=0;
}
}
//設定前一頁
if(this.currentPage >1){
this.prevPage=this.currentPage-1;
}else{
this.prevPage=this.currentPage;
}
//設定下一頁
if(this.currentPage <this.lastPage){
this.nextPage=this.currentPage+1;
}else{
this.nextPage=this.lastPage;
}
//計算數字導航頁
startPageNum =Math.max(this.currentPage-maxPageAmount/2, firstPage);
endPageNum =Math.min(startPageNum+maxPageAmount, lastPage);
if(endPageNum-startPageNum <maxPageAmount){
startPageNum =Math.max(endPageNum -maxPageAmount , 1);
}
for(int i=startPageNum ;i<=endPageNum;i++){
showPageNums.add(i);
}
}
//以下get方法是對外提供的方法用來獲取引數值
public Integer getPageSize() {
return pageSize;
}
public Integer getCurrentPage() {
return currentPage;
}
public Integer getAllRowsAmount() {
return allRowsAmount;
}
public List<?> getItems() {
return items;
}
public Integer getAllPageAmount() {
return allPageAmount;
}
public Integer getCurrentPageStartRow() {
return currentPageStartRow;
}
public Integer getCurrentPageEndRow() {
return currentPageEndRow;
}
public Integer getFirstPage() {
return firstPage;
}
public Integer getLastPage() {
return lastPage;
}
public Integer getPrevPage() {
return prevPage;
}
public Integer getNextPage() {
return nextPage;
}
public Integer getStartPageNum() {
return startPageNum;
}
public Integer getEndPageNum() {
return endPageNum;
}
public Integer getMaxPageAmount() {
return maxPageAmount;
}
public List<Integer> getShowPageNums() {
return showPageNums;
}
@Override
public String toString() {
return "PageUtil [pageSize=" + pageSize + ", currentPage="
+ currentPage + ", allRowsAmount=" + allRowsAmount + ", 每頁內容items="
+ items + ", allPageAmount=" + allPageAmount
+ ", currentPageStartRow=" + currentPageStartRow
+ ", currentPageEndRow=" + currentPageEndRow + ", firstPage="
+ firstPage + ", lastPage=" + lastPage + ", prevPage="
+ prevPage + ", nextPage=" + nextPage + ", startPageNum="
+ startPageNum + ", endPageNum=" + endPageNum + ", maxPageAmount="
+ maxPageAmount + ", 頁號list=" + showPageNums + "]";
}
public static void main(String[] args) {
List<String> items =new ArrayList<String>();
for(int i=0;i<10;i++){
items.add("str"+i);
}
PageUtil pageUtil =new PageUtil();
pageUtil.setCurrentPage(1);
//pageUtil.setItems(items);
pageUtil.setAllRowsAmount(33);
pageUtil.calculatePage();
System.out.println(pageUtil);
}
}
Model模型:
User:
public class User {
private String id;
private String name;
private Integer sal;
private String gender;
public User(){}
public User(String id, String name, Integer sal, String gender) {
this.id = id;
this.name = name;
this.sal = sal;
this.gender = gender;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSal() {
return sal;
}
public void setSal(Integer sal) {
this.sal = sal;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
Page模型:
public class Page {
private String allRowsAmount;
private List<User> showUsers =new ArrayList<User>();
public String getAllRowsAmount() {
return allRowsAmount;
}
public void setAllRowsAmount(String allRowsAmount) {
this.allRowsAmount = allRowsAmount;
}
public List<User> getShowUsers() {
return showUsers;
}
public void setShowUsers(List<User> showUsers) {
this.showUsers = showUsers;
}
}
dao層實現類:
public class UserDaoImpl implements IUserDao{
//從資料庫查詢記錄的總條數
public Integer getAllRowsAmount() throws Exception{
String sql="select count(*) from user";
Connection conn =DbUtil.getConnection();
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet rs =pstmt.executeQuery();
Integer allRowsAmount=0;
if(rs.next()){
allRowsAmount =rs.getInt("count(*)");
}
DbUtil.close(conn, pstmt, rs);
return allRowsAmount;
}
//通過當前頁號查詢條件記錄
public List<User> getUserByCurrentPage(Integer currentPageStartRow, Integer pageSize) throws Exception{
String sql="select id,name,gender,sal from user limit "+(currentPageStartRow-1)+","+pageSize;
Connection conn =DbUtil.getConnection();
PreparedStatement pstmt =conn.prepareStatement(sql);
ResultSet rs =pstmt.executeQuery();
List<User> list =new ArrayList<User>();
while(rs.next()){
User user =new User();
user.setId(rs.getString("id"));
user.setName(rs.getString("name"));
user.setGender(rs.getString("gender"));
user.setSal(rs.getInt("sal"));
list.add(user);
}
DbUtil.close(conn, pstmt, rs);
return list;
}
}
dao層介面:
public interface IUserDao {
public Integer getAllRowsAmount() throws Exception;
public List<User> getUserByCurrentPage(Integer currentPageStartRow, Integer pageSize) throws Exception;
}
service層實現類:
public class UserServiceImpl implements IUserService{
private IUserDao userDao =new UserDaoImpl();
public Page pageUsers(String currentPage,String pageSize) throws Exception{
int allRowsAmount =userDao.getAllRowsAmount();
PageUtil pageUtil =new PageUtil();
pageUtil.setAllRowsAmount(allRowsAmount);
if(currentPage !=null){
pageUtil.setCurrentPage(Integer.parseInt(currentPage));
}
if(pageSize !=null){
pageUtil.setPageSize(Integer.parseInt(pageSize));
}
pageUtil.calculatePage();
List<User> list =userDao.getUserByCurrentPage(pageUtil.getCurrentPageStartRow(), pageUtil.getPageSize());
Page page =new Page();
page.setShowUsers(list);
page.setAllRowsAmount(String.valueOf(allRowsAmount));
return page;
}
}
service層介面:
public interface IUserService {
public Page pageUsers(String currentPage,String pageSize) throws Exception;
}
控制層UserServlet:
public class UserServlet extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
private IUserService userService =new UserServiceImpl();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String currentPage =req.getParameter("page");//當前頁號
String pageSize =req.getParameter("rows");//當前需要顯示的記錄數
Page page=null;
try {
page = userService.pageUsers(currentPage, pageSize);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String,Object> map =new HashMap<String, Object>();
map.put("total", page.getAllRowsAmount());
map.put("rows", page.getShowUsers());
JSONArray jsonArray =JSONArray.fromObject(map);
String json =jsonArray.toString();
resp.setContentType("text/html;charset=UTF-8");
PrintWriter pw =resp.getWriter();
pw.write(json.substring(1, json.length()-1));
pw.flush();
pw.close();
}
}
頁面:
:true,
singleSelect:true,
pagination:true,
pageSize:2,
pageList:[1<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用servlet返回JSON文字動態建立DataGrid</title>
<!-- 引入css檔案 -->
<link rel="stylesheet" href="themes/default/easyui.css" type="text/css"></link>
<link rel="stylesheet" href="themes/icon.css" type="text/css"></link>
<!-- 引入js檔案 -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.easyui.min.js"></script>
<script type="text/javascript" src="js/easyui-lang-zh_CN.js"></script>
</head>
<body>
<table id="dg"></table>
</body>
<script type="text/javascript">
$("#dg").datagrid({
url :"${pageContext.request.contextPath}/UserServlet?time="+new Date().getTime(),
columns:[[
{field:'id',title:'編號',width:100},
{field:'name',title:'姓名',width:100},
{field:'sal',title:'薪水',width:100},
{field:'gender',title:'性別',width:100}
]],
fitColumns:true,
singleSelect:true,
pagination:true,
pageSize:2,
pageList:[1,2,4,5,6]
});
</script>
</html>
結果: