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.aygfsteel.com/beansoft/archive/2007/10/05/150583.html

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 阳曲县| 裕民县| 伊通| 齐河县| 锡林浩特市| 汉沽区| 毕节市| 通渭县| 湾仔区| 达日县| 手游| 古交市| 达尔| 中方县| 南康市| 二手房| 禄丰县| 壤塘县| 昭平县| 安远县| 兴隆县| 天全县| 齐齐哈尔市| 曲阳县| 长垣县| 张家港市| 柯坪县| 东宁县| 遂宁市| 卢龙县| 团风县| 巧家县| 南开区| 江阴市| 湘潭县| 犍为县| 大埔县| 宾阳县| 揭东县| 泸溪县| 阜南县|