用 MyEclipse 开发的 Hibernate + JSP 分页代码

原创 2007年10月06日 10:22:00

下载后导入项目到 MyEclipse , 然后修改数据库连接参数即可测试. 我这用的是 MySQL 数据库. 用 JSP 是因为 Hibernate 可以配合各种框架, 因此在代码里我已经尽量的把页面和后台的直接变量耦合分隔开了.

hibernate_page.zip 432KB

部分代码显示:

 

相关 SQL:

CREATE TABLE `user` (
  `id` int(11) NOT NULL,
  `username` varchar(200) NOT NULL,
  `password` varchar(20) NOT NULL,
   `age` int,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=GBK;

-- JDBC Driver Name: com.mysql.jdbc.Driver
-- JDBC Driver URL: jdbc:mysql://hostname/dbname?useUnicode=true&characterEncoding=GBK
insert into user values(1, '中文', 'beansoft', 1);
insert into user values(2, 'BeanSoft', 'beansoft', 2);
insert into user values(3, '张三', 'beansoft', 3);
insert into user values(4, '李四', 'beansoft', 4);
insert into user values(5, '王五', 'beansoft', 5);
insert into user values(6, '马六', 'beansoft', 6);
insert into user values(7, '黑七', 'beansoft', 7);
insert into user values(8, '腊八', 'beansoft', 8);
insert into user values(9, '陆九', 'beansoft', 9);
insert into user values(10, '茅十八', 'beansoft', 10);

 

前台 JSP 代码:

<%@ page language="java" import="manager.*,java.util.*" pageEncoding="GBK"%>
<%@ page contentType="text/html;charset=GBK"%>
<%
   1: -- 我们使用 JSTL 来访问数据 --
%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%
   1:  
   2: String path = request.getContextPath();
   3: String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <%
   1:  
   2: // 以下代码为业务逻辑代码, 应该放在 Servlet 或者 Struts 的 Action 或者其它框架的业务代码部分, 这些代码和当前页面是独立的
   3: // {{{
   4:  
   5: // 分析当前页
   6: String pageString=request.getParameter("page");
   7: if(pageString == null || pageString.length() == 0) {
   8:     pageString = "1";
   9: }
  10: int currentPage=Integer.parseInt(pageString);// 当前页码
  11: if(currentPage == 0) {
  12:     currentPage = 1;
  13: }
  14:  
  15: int pageSize = 2;//每页显示的数据数
  16: // 读取数据
  17: UserManager manager = new UserManager();
  18: List users = manager.findPagedAll(currentPage, pageSize);
  19:  
  20: request.setAttribute("users",users);// 保存用户列表
  21:  
  22: request.setAttribute("totalPage", manager.getTotalPage(pageSize));// 保存总页数
  23: request.setAttribute("totalCount", manager.getUserTotalCount());// 保存记录总数
  24: request.setAttribute("currentPage", currentPage);// 保存当前页码
  25: // }}}
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>用户列表页面</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> </head> <body>用户列表<br> <%
   1: -- 输出用户列表 --
%> 总用户:${totalCount}个用户<br> <table width="80%" border="0"> <tr> <td><b>用户ID</b></td> <td><b>用户名</b></td> </tr> <c:forEach items="${users}" var="user" > <tr> <td>${user.id}</td> <td>${user.username}</td> </tr> </c:forEach> </table> 第${currentPage}页/共${totalPage}页 <%
   1: -- 输出页面跳转代码, 分链接和静态文字两种 --
%> <c:if test="${currentPage > 1}"> [ <a href="${pageContext.request.contextPath}/index.jsp?page=${currentPage-1}">上一页</a> ] </c:if> <c:if test="${currentPage <= 1}"> [ 上一页 ] </c:if> <c:if test="${currentPage < totalPage}"> [ <a href="${pageContext.request.contextPath}/index.jsp?page=${currentPage+1}">下一页</a> ] </c:if> <c:if test="${currentPage >= totalPage}"> [ 下一页 ] </c:if> <%
   1: -- 输出 JavaScript 跳转代码 --
%> 转到 <script>
   1:  
   2:     // 页面跳转函数
   3:     // 参数: 包含网址的选择框(SELECT元素)
   4:     function jumpPage(select) {
   5:         var newUrl = "${pageContext.request.contextPath}/index.jsp?page=" + select.value;
   6:         //alert(newUrl);
   7:         document.location = newUrl;
   8:     }
   9:     
</script> <!-- 输出 HTML SELECT 元素, 并选中当前页面编码 --> <select onchange='jumpPage(this);'> <c:forEach var="i" begin="0" end="${totalPage - 1}"> <option value="${i}" &lt;c:if test="${currentPage == i+1}"> selected </c:if> >${i+1}页</option> </c:forEach> </select> </body> </html>

后台 DAO:

package dao;

import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.criterion.Example;

import util.HibernateSessionFactory;

/**
 * Data access object (DAO) for domain model class User.
 * 
 * @see dao.User
 * @author MyEclipse Persistence Tools
 */

public class UserDAO {
    private static final Log log = LogFactory.getLog(UserDAO.class);

    // property constants
    public static final String USERNAME = "username";

    public static final String PASSWORD = "password";

    public static final String AGE = "age";

    public Session getSession() {
        return HibernateSessionFactory.getSession();
    }

    /**
     * 得到用户总数
     * 
     * @return 用户记录总数
     */
    public int getUserTotalCount() {
        Query q = getSession().createQuery("select count(*) from User");

        List cc = q.list();

        Integer a = (Integer) cc.get(0);
        return a.intValue();
    }

    /**
     * 分页显示用户数据.
     * 
     * @param currentPage
     *            当前页码, 从 1 开始
     * @param pageSize
     *            每页显示数据量
     * @return 用户数据
     */
    public List findPagedAll(int currentPage, int pageSize) {
        log.debug("分页查找");
        try {

            if (currentPage == 0) {
                currentPage = 1;
            }
            String queryString = "from User";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setFirstResult((currentPage - 1) * pageSize);
            queryObject.setMaxResults(pageSize);
            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public void save(User transientInstance) {
        log.debug("saving User instance");
        try {
            getSession().save(transientInstance);
            log.debug("save successful");
        } catch (RuntimeException re) {
            log.error("save failed", re);
            throw re;
        }
    }

    public void delete(User persistentInstance) {
        log.debug("deleting User instance");
        try {
            getSession().delete(persistentInstance);
            log.debug("delete successful");
        } catch (RuntimeException re) {
            log.error("delete failed", re);
            throw re;
        }
    }

    public User findById(java.lang.Integer id) {
        log.debug("getting User instance with id: " + id);
        try {
            User instance = (User) getSession().get("dao.User", id);
            return instance;
        } catch (RuntimeException re) {
            log.error("get failed", re);
            throw re;
        }
    }

    public List findByExample(User instance) {
        log.debug("finding User instance by example");
        try {
            List results = getSession().createCriteria("dao.User").add(
                    Example.create(instance)).list();
            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        } catch (RuntimeException re) {
            log.error("find by example failed", re);
            throw re;
        }
    }

    public List findByProperty(String propertyName, Object value) {
        log.debug("finding User instance with property: " + propertyName
                + ", value: " + value);
        try {
            String queryString = "from User as model where model."
                    + propertyName + "= ?";
            Query queryObject = getSession().createQuery(queryString);
            queryObject.setParameter(0, value);
            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find by property name failed", re);
            throw re;
        }
    }

    public List findByUsername(Object username) {
        return findByProperty(USERNAME, username);
    }

    public List findByPassword(Object password) {
        return findByProperty(PASSWORD, password);
    }

    public List findByAge(Object age) {
        return findByProperty(AGE, age);
    }

    public List findAll() {
        log.debug("finding all User instances");
        try {
            String queryString = "from User";
            Query queryObject = getSession().createQuery(queryString);
            return queryObject.list();
        } catch (RuntimeException re) {
            log.error("find all failed", re);
            throw re;
        }
    }

    public User merge(User detachedInstance) {
        log.debug("merging User instance");
        try {
            User result = (User) getSession().merge(detachedInstance);
            log.debug("merge successful");
            return result;
        } catch (RuntimeException re) {
            log.error("merge failed", re);
            throw re;
        }
    }

    public void attachDirty(User instance) {
        log.debug("attaching dirty User instance");
        try {
            getSession().saveOrUpdate(instance);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }

    public void attachClean(User instance) {
        log.debug("attaching clean User instance");
        try {
            getSession().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        } catch (RuntimeException re) {
            log.error("attach failed", re);
            throw re;
        }
    }
}

 

后台 Manager:

/**
 * 
 */
package manager;

import java.util.List;

/**
 * 用户管理类
 * 
 * @author Administrator
 * 
 */
public class UserManager {
    /** 用户管理 DAO */
    private dao.UserDAO userDAO = new dao.UserDAO();

    
    /**
     * 得到用户总数
     * @return 用户记录总数
     */
    public int getUserTotalCount(){
        return userDAO.getUserTotalCount();
    }
    /**
     * 获取总页面数.
     * 
     * @param pageSize
     *            一页显示数据量
     * @return 页面总数
     */
    public int getTotalPage(int pageSize) {
        int totalCount = userDAO.getUserTotalCount();

        // 得到页面总数
        int totalPageCount = ((totalCount + pageSize) - 1) / pageSize;

        return totalPageCount;
    }
    
    /**
     * 分页显示用户数据.
     * @param currentPage 当前页码, 从 1 开始
     * @param pageSize 每页显示数据量
     * @return 用户数据
     */
    public List findPagedAll(int currentPage, int pageSize) {
        return userDAO.findPagedAll(currentPage, pageSize);
    }
}
 

Hibernate中的分页(从jsp页面到Action以及后台的HQL)

话不多说了,直接上源码: function frontPageCheck() { if(${page > 1}) { return true; }...

Delphi7高级应用开发随书源码

  • 2003年04月30日 00:00
  • 676KB
  • 下载

hibernate+jsp分页第三版

改进了一下分页 不用session和数组来传递动态查询参数优化了下 join查询的问题Page.java  和以前一样 接口 package cn.loen.platform.util.page;im...

Hibernate + JSP 分页代码

部分代码显示: 相关 SQL:CREATE TABLE `user` ( `id` int(11) NOT NULL, `username` varchar(200) NOT NULL, `pa...

Hibernate 1、获取一天中数据的总条数

private static long getOrderIdForOneDay(String day) { long ret=0; String start =...

MyEclipse Hibernate 快速入门中文版

HTML完整版本下载地址: http://beansoft.java-cn.org/download/MyEclipse_Hibernate_Quickstart_zh_CN.zip 719KB不带图...

网页开发中的jsp分页代码

  • 2009年07月31日 09:29
  • 33KB
  • 下载

Hibernate分页应用层和jsp页面技术

/*  * Generated by MyEclipse Struts  * Template path: templates/java/JavaClass.vtl  */ package c...
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:用 MyEclipse 开发的 Hibernate + JSP 分页代码
举报原因:
原因补充:

(最多只允许输入30个字)