fossil

鸟在笼中,恨关羽不能张飞 人处世上,要八戒更须悟空
posts - 40, comments - 0, trackbacks - 0, articles - 0
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

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

hibernate_page.zip 433KB

部分代码显示:

 

相关 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"%>
<%-- 我们使用 JSTL 来访问数据 --%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<%
// 以下代码为业务逻辑代码, 应该放在 Servlet 或者 Struts 的 Action 或者其它框架的业务代码部分, 这些代码和当前页面是独立的
// {{{

// 分析当前页码
String pageString=request.getParameter("page");
if(pageString == null || pageString.length() == 0) {
    pageString = "1";
}
int currentPage= 0 ;
try {
    currentPage = Integer.parseInt(pageString);// 当前页码
} catch(Exception e) {}

if(currentPage == 0) {
    currentPage = 1;
}

int pageSize = 3;//每页显示的数据数
// 读取数据
UserManager manager = new UserManager();
List users = manager.findPagedAll(currentPage, pageSize);

request.setAttribute("users",users);// 保存用户列表

request.setAttribute("totalPage", manager.getTotalPage(pageSize));// 保存总页数
request.setAttribute("totalCount", manager.getUserTotalCount());// 保存记录总数
request.setAttribute("currentPage", currentPage);// 保存当前页码
// }}}
%>

<!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>
  <td><b>操作</b></td>
  </tr>
  <c:forEach items="${users}" var="user" >
  <tr>
  <td>${user.id}</td>
  <td>${user.username}</td>
  <td><a href="edit.jsp?id=${user.id}">修改</a></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>
    <%-- 输出 JavaScript 跳转代码 --%>
    转到
    <script>
    // 页面跳转函数
    // 参数: 包含页码的选择框(SELECT元素)
    function jumpPage(select) {
        var newUrl = "${pageContext.request.contextPath}/index.jsp?page=" + select.value;
        //alert(newUrl);
        document.location = newUrl;
    }
    </script>

      <!-- 输出 HTML SELECT 元素, 并选中当前页面编码 -->
      <select onchange='jumpPage(this);'>
      
      <c:forEach var="i" begin="1" end="${totalPage}">
        <option value="${i}"
        
        <c:if test="${currentPage == i}">
        selected
        </c:if>

    >第${i}页</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);
    }
}


BeanSoft 2007-10-05 17:41 发表评论

文章来源:http://www.blogjava.net/beansoft/archive/2007/10/05/150583.html

只有注册用户登录后才能发表评论。


网站导航: