对慕课网分页教程感悟三
这一次我们是使用了hibernate这个框架进行实现,并且使用了下拉加载的形式实现了代码。
我们换一种形式来理解这一次的代码流程。
首先,我来把配置环境之类的先叙述一下。
既然,用到了hibernate,那么就不可避免的拥有hibernate的配置环境
--------------------------------------------------------hibernate.cfg.xml--------------------------------------------------
<?xml version='1.0' encoding='utf-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://127.0.0.1:3306/imooc</property> <property name="connection.username">root</property> <property name="connection.password">123456</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <mapping class="com.imooc.page.model.Student"/> </session-factory> </hibernate-configuration>
这一段代码是hibernate的一段配置,主要是连接数据库及基础配置。
hibernate的使用配置并不止有这些,还有如何让hibernate知道这些参数,如何让hibernate成为面向对象。
我们需要给实体类加上一部分的注解或配置文件,这里我们使用注解,以后我们就能直接对这些对象进行操纵了,而不用去操纵数据库里面的表
package com.imooc.page.model; import java.io.Serializable; import java.util.Map; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; @Entity @Table( name = "t_student" ) public class Student implements Serializable { private static final long serialVersionUID = -7476381137287496245L; private int id; //学生记录id private String stuName;//学生姓名 private int age; //学生年龄 private int gender; //学生性别 private String address;//学生住址 public Student() { super(); } public Student(int id, String stuName, int age, int gender, String address) { super(); this.id = id; this.stuName = stuName; this.age = age; this.gender = gender; this.address = address; } public Student(Map<String, Object> map){ this.id = (int)map.get("id"); this.stuName = (String)map.get("stu_name"); this.age = (int)map.get("age"); this.gender = (int)map.get("gender"); this.address = (String)map.get("address"); } @Id @GeneratedValue(generator="increment") @GenericGenerator(name="increment", strategy = "increment") public int getId() { return id; } public void setId(int id) { this.id = id; } @Column(name = "stu_name") public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } @Column(name = "age") public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Column(name = "gender") public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } @Column(name = "address") public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "Student [id=" + id + ", stuName=" + stuName + ", age=" + age + ", gender=" + gender + ", address=" + address + "]"; } }
其他的没有什么变化,这里就不再说明,主要看一下dao层
package com.imooc.page.dao; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.Query; import org.hibernate.Session; import com.imooc.page.Constant; import com.imooc.page.HibernateSessionFactory; import com.imooc.page.model.Pager; import com.imooc.page.model.Student; public class HibernateStudentDaoImpl implements StudentDao { @SuppressWarnings("unchecked") @Override public Pager<Student> findStudent(Student searchModel, int pageNum, int pageSize) { Pager<Student> result = null; // 存放查询参数 Map<String, Object> paramMap = new HashMap<String, Object>(); String stuName = searchModel.getStuName(); int gender = searchModel.getGender(); StringBuilder hql = new StringBuilder( "from Student where 1=1"); StringBuilder countHql = new StringBuilder( "select count(id) from Student where 1=1 "); if (stuName != null && !stuName.equals("")) { hql.append(" and stuName like :stuName "); countHql.append(" and stuName like :stuName "); paramMap.put("stuName", "%" + stuName + "%"); } if (gender == Constant.GENDER_FEMALE || gender == Constant.GENDER_MALE) { hql.append(" and gender = :gender "); countHql.append(" and gender = :gender "); paramMap.put("gender", gender); } // 起始索引 int fromIndex = pageSize * (pageNum -1); // 存放所有查询出的学生对象 List<Student> studentList = new ArrayList<Student>(); Session session = null; try { session = HibernateSessionFactory.getSession(); // 获取query对象 Query hqlQuery = session.createQuery(hql.toString()); Query countHqlQuery = session.createQuery(countHql.toString()); //设置查询参数 setQueryParams(hqlQuery, paramMap); setQueryParams(countHqlQuery, paramMap); // 从第几条记录开始查询 hqlQuery.setFirstResult(fromIndex); // 一共查询多少条记录 hqlQuery.setMaxResults(pageSize); // 获取查询的结果 studentList = hqlQuery.list(); // 获取总计条数 List<?> countResult = countHqlQuery.list(); int totalRecord = ((Number)countResult.get(0)).intValue(); //获取总页数 int totalPage = totalRecord / pageSize; if(totalRecord % pageSize !=0){ totalPage++; } // 组装pager对象 result = new Pager<Student>(pageSize, pageNum, totalRecord, totalPage, studentList); } catch (Exception e) { throw new RuntimeException("查询所有数据异常!", e); } finally { if(session != null){ HibernateSessionFactory.closeSession(); } } return result; } /** * 设置查询的参数 * @param query * @param paramMap * @return */ private Query setQueryParams(Query query, Map<String, Object> paramMap){ if(paramMap != null && !paramMap.isEmpty()){ for(Map.Entry<String, Object> param : paramMap.entrySet()){ query.setParameter(param.getKey(), param.getValue()); } } return query; } }
这里实现下拉加载主要用的是ajax和jquery的功能。
<%@ 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>学生信息</title> </head> <% // 获取请求的上下文 String context = request.getContextPath(); %> <link href="../css/pagination.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="../js/jquery-1.11.3.js"></script> <script type="text/javascript" src="../js/jquery.pagination.js"></script> <script type="text/javascript"> // 第一步:页面渲染完之后,请求后台,获取学生数据,加载学生信息 // 第二步:完成学生查询功能 // 第三步:下拉加载更多数据的功能 var url = "<%=context%>/hibernate/HibernateDataServlet"; // 请求获取数据的url var totalPage = 1; //一共有多少页数据 var pageSize = 30; // 每页显示30条数据 var currentPage = 1; // 当前第几页数据,默认为1 var isLoading = false; // 是否正在加载更多的数据 // 页面渲染完之中执行的代码 $(function(){ // 绑定事件,监听滚动条下拉的动作 bindScrollEvent(); // 请求后台,加载学生信息 queryStudent(1); }); function queryForm(){ // 绑定事件,监听滚动条下拉的动作 bindScrollEvent(); // 清空学生的数据 $("#studentDataBody").html(""); // 清空学生为空的提示信息 $("#emptyInfo").html(""); // 查询学生 queryStudent(1); } //请求后台,加载学生信息 function queryStudent(pageNum){ if(pageNum > totalPage){ $("#emptyInfo").html("没有更多的学生数据了......"); $(window).unbind("scroll"); } if(isLoading){ return; }else{ isLoading = true; // 修改状态为正在加载数据 } var stuName = $("#stu_name").val(); // 获取学生姓名 var gender = $("#gender").val(); // 获取学生的性别 // 进行post请求 $.post(url,{"pageSize":pageSize,"pageNum":pageNum, "stuName":stuName, "gender":gender},function(data){ // 加载学生信息 totalPage = data.totalPage; // 一共有多少页数据 currentPage = data.currentPage; // 获取当前第几页数据 var stuentList = data.dataList; // 学生记录信息 if(totalPage == 0){ $("#emptyInfo").html("没有更多的学生数据了......"); } //加载学生的数据 showStudentData(stuentList); isLoading = false; },"json"); } //加载学生的数据; function showStudentData(stuentList){ var studentDataHtml = ""; $.each(stuentList,function(idx, obj){ studentDataHtml += "<tr>" ; studentDataHtml += "<td>" + obj.stuName + "</td>"; // 获取学生姓名的值 if(obj.gender == 1){ studentDataHtml += "<td>男</td>"; // 获取学生性别的值 }else{ studentDataHtml += "<td>女</td>"; // 获取学生性别的值 } studentDataHtml += "<td>" + obj.age + "</td>"; // 获取学生年龄的值 studentDataHtml += "<td>" + obj.address + "</td>"; // 获取学生住址的值 studentDataHtml += "</tr>"; }); $("#studentDataBody").append(studentDataHtml); } function bindScrollEvent(){ // 添加滚动监听事件 $(window).scroll( function() { var docHeight = $(document).height(); // 获取整个页面的高度 var winHeight = $(window).height(); // 获取当前窗体的高度 var winScrollHeight = $(window).scrollTop(); // 获取滚动条滚动的距离 if(docHeight -30 <= winHeight + winScrollHeight){ // 加载更多的学生数据 queryStudent(currentPage+1); } } ); } </script> <body> <div style="margin-left: 100px; margin-top: 100px;"> <div> <font color="red">${errorMsg }</font> </div> <div> <form action="#" id="stuForm" method="post" > 姓名 <input type="text" name="stuName" id="stu_name" style="width:120px" value="${stuName }"> 性别 <select name="gender" id="gender" style="width:80px"> <option value="0" selected="selected">全部</option> <option value="1">男</option> <option value="2">女</option> </select> <input type="button" value="查询" onclick="queryForm()"> </form> </div> <br> 学生信息列表:<br> <br> <!-- 后台返回结果不为空 --> <table border="1px" cellspacing="0px" style="border-collapse: collapse" id="studentTable"> <thead> <tr height="30"> <th width="130">姓名</th> <th width="130">性别</th> <th width="130">年龄</th> <th width="190">家庭地址</th> </tr> </thead> <tbody id="studentDataBody"> </tbody> </table> <div id="emptyInfo"></div> <br> </div> </body> </html>
这一段代码个人觉得极为精彩。