easyui-datagrid连接数据库实现分页查询数据

一、利用MVC思想建立底层数据库:

package com.hanqi.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;

import com.hanqi.entity.Student;

public class StudentDAO {

    ServiceRegistry sr=null;
    Configuration cfg=null;
    SessionFactory sf=null;
    Session se=null;
    Transaction tr=null;
    
    public StudentDAO()
    {
        cfg=new Configuration().configure();
        
         sr=new StandardServiceRegistryBuilder()
                .applySettings(cfg.getProperties()).build();
        
    }
    //初始化
    private void init()
    {
        
        sf=cfg.buildSessionFactory(sr);
        se=sf.openSession();
        tr=se.beginTransaction();
    }
    //提交和释放资源
    private void destory()
    {
        tr.commit();
        se.close();
        sf.close();
    }
    //获取分页的数据集合
    public List<Student> getPageList(int page,int rows)
    {
        List<Student> rtn=new ArrayList<Student>();
        init();
        int num=(page-1)*rows;
        rtn=se.createQuery("from Student").setFirstResult(num).setMaxResults(rows).list();
        destory();
        return rtn;
    }
    
    //获取数据条数
    public int getTotal()
    {
        int rtn=0;
        init();
        List<Object>lo=se.createQuery("select count(1) from Student").list();
        if(lo!=null&&lo.size()>0)
        {
            rtn=Integer.parseInt(lo.get(0).toString());
        }
        
         destory();
        return rtn;
    }
    
    
    
    
}

二、建立service层

package com.hanqi.service;

import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.hanqi.dao.StudentDAO;
import com.hanqi.entity.Student;

public class StudentService {

    //查询分页数据
    
    
    
    //返回JSON
    public String getPageJSON(int page,int rows)
    {
        String rtn="{'title':0,'rows':[]}";
        
        int total=new StudentDAO().getTotal();
        if(total>0)
        {
            List<Student>ls= new StudentDAO().getPageList(page, rows);
            
            String ls_json=JSONArray.toJSONString(ls);
            //利用转义字符转成JSON格式的语句
            rtn="{"total":"+total+","rows":"+ls_json+"}";
            
        }
        
        
        return rtn;
    }
    
}

三、建立servlet:

package com.hanqi.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.hanqi.service.StudentService;

/**
 * Servlet implementation class StudentServlet
 */
public class StudentServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public StudentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html");
        
        String spage=request.getParameter("page");
        String srows=request.getParameter("rows");
        
        if(spage!=null&& srows!=null)
        {
        int page=Integer.parseInt(spage);
        int rows=Integer.parseInt(srows);
        
        String json =new StudentService().getPageJSON(page, rows);
        
        response.getWriter().print(json);
        }
        else
        {
            response.getWriter().print( "{'title':0,'rows':[]}");
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

4、写出显示界面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<!-- 1、JQuery的js包 -->
<script type="text/javascript" src="jquery-easyui-1.4.4/jquery.min.js"></script>
<!-- 2 css资源 -->
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.4.4/themes/default/easyui.css">
<!-- 3、图标资源 -->
<link rel="stylesheet" type="text/css" href="jquery-easyui-1.4.4/themes/icon.css">
<!-- 4、easyui的js包 -->
<script type="text/javascript" src="jquery-easyui-1.4.4/jquery.easyui.min.js"></script>

<!-- 5、本地语言 -->
<script type="text/javascript" src="jquery-easyui-1.4.4/locale/easyui-lang-zh_CN.js"></script>
</head>
<body>
<script type="text/javascript">
$(function(){
    //创建data_grid
    $("#st").datagrid({
        
        url:'StudentServlet', //数据来源   
        //冻结列
    
        //列的定义
        columns:[[ 
            {field:'sno',title:'学生编号',50},    
            {field:'sname',title:'学生姓名',50},    
            {field:'ssex',title:'性别',50,align:'right'},
            {field:'sbirthday',title:'生日',50,align:'center',hidden:true},
            {field:'sclass',title:'班级',50,align:'right',sortable:true}
        ]],
        
        fitColumns:true,//列自适应宽度,不能和冻结列同时设置为true
        striped:true,//斑马线效果
        idField:'sno',//主键列
        rownumbers:true,//显示行号
        singleSelect:false,//是否单选
        pagination:true,//显示分页栏
        pageList:[10,20,50,100],//每页行数选择列表
        pageSize:10,//出事每页行数
        remoteSort:false,//是否服务器端排序,设成false,才能客户端排序
        sortName:'sclass'//设置排序列
            
                
    });
})


</script>
学生表
<br><br>
<table id="st"></table>

</body>
</html>

效果图:

 
原文地址:https://www.cnblogs.com/diaozhaojian/p/6115170.html