用 MyEclipse 开发的 Hibernate + JSP 分页代码
2007-10-06 10:22
671 查看
下载后导入项目到 MyEclipse , 然后修改数据库连接参数即可测试. 我这用的是 MySQL 数据库. 用 JSP 是因为 Hibernate 可以配合各种框架, 因此在代码里我已经尽量的把页面和后台的直接变量耦合分隔开了.
hibernate_page.zip 432KB
部分代码显示:
相关 SQL:
前台 JSP 代码:
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
%>
<%
%>
<!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>
<%
%>
总用户:${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}页
<%
%>
<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>
<%
%>
转到
<script>
</script>
<!-- 输出 HTML SELECT 元素, 并选中当前页面编码 -->
<select onchange='jumpPage(this);'>
<c:forEach var="i" begin="0" end="${totalPage - 1}">
<option value="${i}" <c:if test="${currentPage == i+1}">
selected
</c:if> >${i+1}页</option>
</c:forEach>
</select>
</body>
</html>
后台 DAO:
后台 Manager:
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}" <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 分页代码
- jsp hibernate的分页代码第1/3页
- Myeclipse开发JSP 代码和配置文件位置
- jsp hibernate的分页代码第1/3页
- 求助hibernate单表分页查询jsp和servlet的传值代码 实在写不出来了
- 开发日志:使用MyEclipse开发JavaWeb,无论怎么改Java代码都不生效,Tomcat报ClassNotFoundException错误
- MyEclipse开发SSH(Struts+Spring+Hibernate)入门
- myeclipse2015(shh整合)hibernate逆向工程生成代码(mysql)
- 一个实用的JSP分页代码
- MyEclipse+Tomcat+JSP开发环境配置
- 怎样在MyEclipse中运用hibernate来开发j2ee程序
- JSP 页面分页代码示例-1
- MyEclipse+struts+Hibernate配置开发
- Myeclipse配置servlet和jsp模板代码
- MyEclipse+struts+Hibernate配置开发
- MyEclipse开发javaweb项目时遇到的异常java.lang.NoSuchMethodError: javax.servlet.JSP.PageContext.getELContext()L
- [原]Java web学习系列之 Java web开发中的Hibernate结合Servlet做分页
- MyEclipse 5.5 开发 Spring + Struts + Hibernate 的详解视频(长1.5小时)
- jsp servlet javaBean后台分页实例代码解析
- MyEclipse打开JSP页面无任何代码提示