完整的Jquery-easyUI显示分页数据例子

虽然说是入门的例子,但本人尽量做的详细点,以后会继续更新,部分功能

此外,为了后继easyui的学习,做了一个简单的框架:后台采用hibernate2.5+struts2开发:数据库用mysql。红色代码标记注意。

 

model层的数据

   Student类

package org.easyui.model;

import java.util.Date;

public class Student {
 private int id;
 private int age;
 private String name;
 private Date birthday;
 private String className;
 private char sex;
 
 public char getSex() {
  return sex;
 }
 public void setSex(char sex) {
  this.sex = sex;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
 public Date getBirthday() {
  return birthday;
 }
 public void setBirthday(Date birthday) {
  this.birthday = birthday;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getName() {
  return name;
 }
 public String getClassName() {
  return className;
 }
 public void setName(String name) {
  this.name = name;
 }
 public void setClassName(String className) {
  this.className = className;
 }
 
}

 

 DAO数据库访问层

  接口EasyDao:

package org.easyui.dao;

import java.util.List;

import org.easyui.model.Student;

public interface EasyDao {
 public List<Student> getStudent(int page,int rows);
 public int getTotalPages(int rows);
}

接口实现类EasyDaoImpl:

package org.easyui.dao;

import java.util.List;

import org.easyui.model.Student;
import org.easyui.util.UtilHibernate;
import org.hibernate.HibernateException;
import org.hibernate.Session;

public class EasyDaoImpl implements EasyDao {

 @SuppressWarnings("unchecked")
 public List<Student> getStudent(int page, int rows) {
  List<Student> list = null;
  Session session = UtilHibernate.getSession();
  try {
   session.beginTransaction();
   String sql = "from Student";
   list = session.createQuery(sql)
        .setFirstResult((page-1)*rows)
        .setMaxResults(rows)
        .list();
   session.getTransaction().commit();
  } catch (HibernateException e) {
   session.getTransaction().rollback();
   e.printStackTrace();
  }finally{
   UtilHibernate.closeSession(session);
  }
  
  return list;
 }

 public int getTotalPages() {
  Session session = UtilHibernate.getSession();
  int total = 0;
  try {
   session.beginTransaction();
   String sql = "select count(*) from Student";
   int count = (Integer)session.createQuery(sql).uniqueResult();
   total =count;
   session.getTransaction().commit();
  } catch (HibernateException e) {
   session.getTransaction().rollback();
   e.printStackTrace();
  }finally{
   UtilHibernate.closeSession(session);
  }
  return total;
 }

}

 

 

 Action层:

 EasyuiAction1 代码如下

package org.easyui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.interceptor.ServletRequestAware;
import org.easyui.dao.EasyDao;
import org.easyui.dao.EasyDaoImpl;
import org.easyui.model.Student;

import com.opensymphony.xwork2.ActionSupport;

public class EasyuiAction1 extends ActionSupport implements ServletRequestAware{
 private static final long serialVersionUID = 1L;
 private  HttpServletRequest request;
 private int total;
 private List<Object> rows;
 
 public int getTotal() {
  return total;
 }
 public List<Object> getRows() {
  return rows;
 }
 public void setTotal(int total) {
  this.total = total;
 }
 public void setRows(List<Object> rows) {
  this.rows = rows;
 }
 
 @Override
 public String execute() throws Exception {
  int page =Integer.parseInt(request.getParameter("page"));
  int row = Integer.parseInt(request.getParameter("rows"));//接受参数page和rows
  EasyDao dao = new EasyDaoImpl();   //实例化dao
  this.total = dao.getTotalPages();

  this.rows = new ArrayList<Object>();
  List<Student> list = dao.getStudent(page, row);//分页,将数据保存到list中
  
  for(int i=0;i<list.size();i++){
   Student student  = list.get(i);    //最原始循环方法到到student对象
   Map<String,Object> map = new HashMap<String,Object>();
   map.put("id", student.getId());        //以键值对的形式保存到map中
   map.put("sex", student.getSex());
   map.put("name",student.getName());
   map.put("age", student.getAge());
   map.put("birthday", student.getBirthday());
   map.put("className", student.getClassName());     
   this.rows.add(map);       //循环保存map到list对象this.rows中
  }
  System.out.println(request.getParameter("page"));
  System.out.println(request.getParameter("rows"));
  return SUCCESS;
 }
 public void setServletRequest(HttpServletRequest request) {
  this.request = request;
 }
}

 

 

struts.xml配置如下:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
 <package name="jsonDemo" extends="json-default">
   <action name="easyAction" class="org.easyui.EasyuiAction1">
    <result type="json"/>
   </action>
  </package>
</struts>   

 

 

easyDemo1.jsp页面代码如下:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>easyDemo1.jsp</title>
 <link rel="stylesheet" type="text/css" href="jquery-easyui/themes/default/easyui.css">
 <link rel="stylesheet" type="text/css" href="jquery-easyui/themes/icon.css">
 <script type="text/javascript" src="jquery-easyui/jquery-1.4.2.min.js"></script>
 <script type="text/javascript" src="jquery-easyui/jquery.easyui.min.js"></script>
 
    <script type="text/javascript" src="jslib/easyDemo.js"></script>
 <script type="text/javascript">
  $(function(){
   $('#tt').datagrid({
    title:'datagrid小例子',
    iconCls:'icon-ok',
    width:500,
    height:320,
    pageSize:5,
    pageList:[5,10,15,20],
    nowrap:false,
    striped: true,
    collapsible:true,
    url:'easyAction.action',
    loadMsg:'数据装载中......',
    sortName:'code',
    sortOrder:'desc',
    remoteSort:false,
    frozenColumns:[[
     {field:'ck',checkbox:true}
    ]],
    columns:[[
     {title:'学号',field:'id',width:'50',rowspan:2,align:'center'},
     {title:'姓名',field:'name',width:'60',rowspan:2,align:'center'},
     {title:'性别',field:'sex',width:'50',rowspan:2,align:'center'},
     {title:'年龄',field:'age',width:'50',rowspan:2,align:'center'},
     {title:'出生日期',field:'birthday',width:'120',rowspan:2,align:'center'},
     {title:'班级',field:'className',width:'100',rowspan:2,align:'center'}
    ]],
    pagination:true,
    rownumbers:true
    
   });
   $('#tt').datagrid('getPager').pagination({
    displayMsg:'当前显示从{from}到{to}共{total}记录',
    onBeforeRefresh:function(pageNumber, pageSize){
     $(this).pagination('loading');
     alert('pageNumber:'+pageNumber+',pageSize:'+pageSize);
     $(this).pagination('loaded');
    },
   });
   
   //$('#tt').datagrid({url:'easyAction.action'});
  });
 </script>
  </head>
 
  <body>
    <a href="javascript:void(0)" onclick="verify()" class="easyui-linkbutton">测试josn数据</a>
    <h2><b>测试easyui的DataGrid</b></h2>
    <table id="tt">
    </table>
  </body>
</html>

 
 

 easyDemo.js代码如下:

var xmlhttp;
function verify(){
    //创建XMLHttpRequest对象
    if(window.XMLHttpRequest){
        xmlhttp = new XMLHttpRequest();
        if(xmlhttp.overrideMimeType){
            xmlhttp.overrideMimeType("text/xml");
        }
    }else if(window.ActiveXObject){
      var activerxName = ["MSXML2.XMLHTTP","Microsoft.XMLHTTP"];
        for(var i=0;i<activerxName.length;i++){
            try{
                 xmlhttp = new ActiveXObject(activerxName[i]);
              break;
            }catch(e){
            }
        }
    }
    //确认XMLHttpRequest对象是否创建成功
    if(!xmlhttp){
        alert("XMLHttpRequest对象创建失败");
        return;
    }else{
    }
    xmlhttp.onreadystatechange = callback;
    xmlhttp.open("POST","easyAction.action?page=1&rows=5","true");
    xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    xmlhttp.send();
}
function callback(){
    if(xmlhttp.readyState == 4){
        if(xmlhttp.status == 200){
          var oBook = eval_r('(' + xmlhttp.responseText + ')');
         $.messager.alert('test jsonData',xmlhttp.responseText);
   

posted @ 2015-09-05 15:38  chenxiangxiang  阅读(2526)  评论(0编辑  收藏  举报