EasyUI异步分页

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ya_1249463314/article/details/69345035

1.使用技术

EasyUI+servlet+c3p0+mysql

2.搭建环境

<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>
导入EasyUI的样式表和js文件:


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操作数据库:

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);  
	          }  
	     }  
	 }
}
PageUtil.java分页工具:

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>
结果:






展开阅读全文

jquery easyui分页问题

10-28

最近学习jquery easyui,使用datagrid以及分页,第一页数据显示出来了,但是总的页数不对,因此也不能点击下一页。总的记录数29条,10条一页,应该显示3页,但是只显示了第一页10条数据。选择每页20条,能看到20条。rn前台代码应该没问题,从网上复制的。我刚觉应该是rn[code=javascript]rn $('#tt').datagrid(rn width:810,rn height:400,rn idField: 'EmployeeID',rn url: 'EmployeHandler.ashx',rn singleSelect:true,rn columns:[[rn field: 'EmployeeID', title: '编号', width: 30 ,rn field: 'LastName', title: '姓氏', width: 60 ,rn field: 'FirstName', title: '名字', width: 60 ,rn field: 'City', title: '城市', width: 60 ,rn field: 'Country', title: '国家', width: 60 rn ]],rn pagination:truern );rn[/code]rn url: 'EmployeHandler.ashx',这里面处理json转换的时候出的问题。rn是不是返回的json数据中应该有数据集的总行数的信息呢?rn返回的json是rn["EmployeeID":1,"LastName":"Davolio","FirstName":"Nancy","City":"Seattle","Country":"USA","EmployeeID":2,"LastName":"Fuller","FirstName":"Andrew","City":"Tacoma","Country":"USA","EmployeeID":3,"LastName":"Leverling","FirstName":"Janet","City":"Kirkland","Country":"USA","EmployeeID":4,"LastName":"Peacock","FirstName":"Margaret","City":"Redmond","Country":"USA","EmployeeID":5,"LastName":"Buchanan","FirstName":"Steven","City":"London","Country":"UK","EmployeeID":6,"LastName":"Suyama","FirstName":"Michael","City":"London","Country":"UK","EmployeeID":7,"LastName":"King","FirstName":"Robert","City":"London","Country":"UK","EmployeeID":8,"LastName":"Callahan","FirstName":"Laura","City":"Seattle","Country":"USA","EmployeeID":9,"LastName":"Dodsworth","FirstName":"Anne","City":"London","Country":"UK","EmployeeID":10,"LastName":"Smith20","FirstName":"Bill20","City":"London","Country":"UK"]rnrn有哪位大神指点一下是哪里除了问题,搞了好久没有弄好,网上也没见json具体格式,都是封装的取数,直接一个dataset2json,郁闷啊!!!rn 论坛

没有更多推荐了,返回首页