七郎's JavaBlog

          草木竹石皆可為劒。至人之用人若鏡,不將不迎,應而不藏,故能勝物而不傷。
          posts - 60, comments - 14, trackbacks - 0, articles - 0

          Spring+Hibernate+Struts實現(xiàn)分頁

          Spring集成Hibernate,使得SessionFactory的管理更加方便,可以方便地獲取到一個HibernateTempalte的模板實例,對數(shù)據(jù)庫的操作非常方便。

          Spring集成Struts,先把Struts的Action用Spring的ActionSupport抽象出來,比如定義一個名稱為SpringAction的的ActionSupport的子類,其中SpringAction中啟動IoC容器,通過ApplicationContext獲取業(yè)務bean。這需要使用一個Struts插件來初始化IoC容器,從而獲取到一個ApplicationContext。可以通過讓每個具體的Action(每個具體的Action意思是實現(xiàn)Struts的Action的子類)都繼承自上面定義的SpringAction,實現(xiàn)對模型的調(diào)用,以及派發(fā)視圖。

          下面通過實現(xiàn)分頁來說明。

          實現(xiàn)思路

          Spring集成Hibernate,直接使用Hibernatede配置文件hibernate.cfg.xml,注入一個SessionFactory,從而在DAO中獲取到一個HibernateTemplate。

          (注意,下面工程結構中,實際上包org.shirdrn.spring.dao及其包org.shirdrn.spring.daoImpl中的接口和類并沒有使用到。)

          org.shirdrn.spring.util.Page類是一個頁面的實體類,沒有加入任何分頁邏輯,而實現(xiàn)分頁邏輯的抽象是在org.shirdrn.spring.util.PageUtil類中,該類是對所有需要實現(xiàn)分頁的業(yè)務對象分頁邏輯的抽象,而且PageUtil類繼承自HibernateDaoSupport類,它是一個具有特殊業(yè)務需(分頁)要的DAO,只是為獲取分頁結果而定義的,只要注入一個SessionFactory就可以方便地檢索數(shù)據(jù)庫了。所有的具體的業(yè)務對象如果需要分頁顯示的數(shù)據(jù)庫記錄,都可以從繼承PageUtil類。

          包org.shirdrn.spring.pages中有一個MyUserPage類,該類繼承自PageUtil類,是一個具體實現(xiàn)分頁邏輯的類,只對MyUser實體(對應數(shù)據(jù)庫中myUser表)的分頁進行處理。

          開發(fā)環(huán)境

          Windows 2003 SP2 + SQL Server 2000 + Eclipse 3.2 + JDK 1.5 + MyEclipse 5.0 + Tomcat 5.5.9 + Spring 2.0 + Hibernate 3.0 + Struts 1.2

          工程結構

          SpringHibernateStrutsPage
          │ .classpath
          │ .myhibernatedata
          │ .mymetadata
          │ .mystrutsdata
          │ .project
          │ .springBeans

          ├─.myeclipse
          ├─src
          │ │ hibernate.cfg.xml
          │ │
          │ └─org
          │      └─shirdrn
          │          ├─spring
          │          │ ├─action
          │          │ │      SpringAction.java
          │          │ │
          │          │ ├─dao
          │          │ │ │ MyUserDAO.java
          │          │ │ │
          │          │ │ └─impl
          │          │ │          MyUserDAOImpl.java
          │          │ │
          │          │ ├─entity
          │          │ │      MyUser.hbm.xml
          │          │ │      MyUser.java
          │          │ │
          │          │ ├─pages
          │          │ │      MyUserPage.java
          │          │ │
          │          │ └─util
          │          │          Page.java
          │          │          PageUtil.java
          │          │
          │          └─struts
          │              │ ApplicationResources.properties
          │              │
          │              └─action
          │                      ListMyUsersAction.java

          └─WebRoot
              │ listmyusers.jsp
              │
              ├─META-INF
              │      MANIFEST.MF
              │
              └─WEB-INF
                  │ .struts-config.mex
                  │ action-servlet.xml
                  │ struts-bean.tld
                  │ struts-config.xml
                  │ struts-html.tld
                  │ struts-logic.tld
                  │ validator-rules.xml
                  │ web.xml
                  │
                  ├─classes
                  │ │ hibernate.cfg.xml
                  │ │
                  │ └─org
                  │      └─shirdrn
                  │          ├─spring
                  │          │ ├─action
                  │          │ │      SpringAction.class
                  │          │ │
                  │          │ ├─dao
                  │          │ │ │ MyUserDAO.class
                  │          │ │ │
                  │          │ │ └─impl
                  │          │ │          MyUserDAOImpl.class
                  │          │ │
                  │          │ ├─entity
                  │          │ │      MyUser.class
                  │          │ │      MyUser.hbm.xml
                  │          │ │
                  │          │ ├─pages
                  │          │ │      MyUserPage$1.class
                  │          │ │      MyUserPage.class
                  │          │ │
                  │          │ └─util
                  │          │          Page.class
                  │          │          PageUtil.class
                  │          │
                  │          └─struts
                  │              │ ApplicationResources.properties
                  │              │
                  │              └─action
                  │                      ListMyUsersAction.class
                  │
                  └─lib

          開發(fā)過程

          (1) Hibernate準備

          編寫Hibernate配置文件hibernate.cfg.xml:

          <?xml version='1.0' encoding='UTF-8'?>
          <!DOCTYPE hibernate-configuration PUBLIC
                    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
                    "

          <!-- Generated by MyEclipse Hibernate Tools.                   -->
          <hibernate-configuration>

          <session-factory>
             <property name="dialect">
              org.hibernate.dialect.SQLServerDialect
             </property>
             <property name="connection.url">
              jdbc:microsoft:sqlserver://localhost:1433;databasename=shirdrn
             </property>
             <property name="connection.username">sa</property>
             <property name="connection.password">111111</property>
             <property name="connection.driver_class">
              com.microsoft.jdbc.sqlserver.SQLServerDriver
             </property>
             <property name="myeclipse.connection.profile">MSSQL</property>
             <property name="show_sql">true</property>
             <mapping resource="org/shirdrn/spring/entity/MyUser.hbm.xml" />

          </session-factory>

          </hibernate-configuration>

          實現(xiàn)Hibernate映射文件MyUser.hbm.xml,及其對應的POJO:

          這個非常容易,就省略了。

          (2) Spring集成Hibernate

          在/WEB-INF/目錄下面,新建一個action-servlet.xml的Spring配置文件,因為后面要和Struts集成,所以根據(jù)格式<SERVLETNAME>-servlet.xml,應該使用Struts的Servlet映射名稱。

          Spring集成Hibernate,在action-servlet.xml中配置如下:

          <bean id="mySessionFactory"
             class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
             <property name="configLocation">
              <value>classpath:hibernate.cfg.xml</value>
             </property>
          </bean>

          (3) 頁面實體及分頁邏輯實現(xiàn)

          Page是一個頁面實體類,如下:

          package org.shirdrn.spring.util;

          import java.util.List;

          public class Page {
          private int pageSize;
          private int totalPage;
          private int rowCount;
          private int currentPage;
          private int prePage;
          private int nextPage;
          private boolean hasNextPage;    // 是否有下一頁
          private boolean hasPreviousPage;    // 是否有前一頁
          private List list;

          public Page(){
             this.pageSize = 10;
          }

          public int getCurrentPage() {
             return currentPage;
          }

          public void setCurrentPage(int currentPage) {
             this.currentPage = currentPage;
          }

          public List getList() {
             return list;
          }

          public void setList(List list) {
             this.list = list;
          }

          public int getNextPage() {
             return nextPage;
          }

          public void setNextPage(int nextPage) {
             this.nextPage = nextPage;
          }

          public int getPageSize() {
             return pageSize;
          }

          public void setPageSize(int pageSize) {
             this.pageSize = pageSize;
          }

          public int getPrePage() {
             return prePage;
          }

          public void setPrePage(int prePage) {
             this.prePage = prePage;
          }

          public int getRowCount() {
             return rowCount;
          }

          public void setRowCount(int rowCount) {
             this.rowCount = rowCount;
          }

          public int getTotalPage() {
             return totalPage;
          }

          public void setTotalPage(int totalPage) {
             this.totalPage = totalPage;
          }

          public boolean isHasNextPage() {
             return hasNextPage;
          }

          public void setHasNextPage(boolean hasNextPage) {
             this.hasNextPage = hasNextPage;
          }

          public boolean isHasPreviousPage() {
             return hasPreviousPage;
          }

          public void setHasPreviousPage(boolean hasPreviousPage) {
             this.hasPreviousPage = hasPreviousPage;
          }
          }

          PageUtil類是一個分頁邏輯的抽象,需要分頁的話,只需要繼承自它便可以方便地實現(xiàn)分頁,可見,PageUtil可以重用,如下所示:

          package org.shirdrn.spring.util;

          import org.shirdrn.spring.pages.MyUserPage;
          import org.springframework.context.ApplicationContext;
          import org.springframework.context.support.ClassPathXmlApplicationContext;
          import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

          public class PageUtil extends HibernateDaoSupport {
          public Page page;
          public int start;

          public PageUtil(){
            
          }

          public void setPreOrNextBoolean(){
             if(page.getCurrentPage()<=1){
              page.setHasPreviousPage(false);
             }
             else{
              page.setHasPreviousPage(true);
             }
             if(page.getCurrentPage()>=page.getTotalPage()){
              page.setHasNextPage(false);
             }
             else{
              page.setHasNextPage(true);
             }
          }

          public void setCurrentPage(){
             if(start<1){
              page.setCurrentPage(1);
             }
             if(start>page.getTotalPage()){
              page.setCurrentPage(page.getTotalPage());
             }
             page.setCurrentPage(start);
          }

          public void setPrePage(){
             page.setPrePage(page.getCurrentPage()-1);
          }

          public void setNextPage(){
             page.setNextPage(page.getCurrentPage()+1);
          }

          public void setTotalPage(){
             int rowCount = getRowCount();
             int pageSize = page.getPageSize();
             if(rowCount>pageSize){
              if(rowCount%pageSize == 0){
               page.setTotalPage(rowCount/pageSize);
              }
              else{
               page.setTotalPage(1+(rowCount/pageSize));
              }
             }
             else{
              page.setTotalPage(1);
             }
          }

          public void setRowCount(){
             page.setRowCount(getRowCount());
          }


          public int getRowCount(){
             return 0;
          }

          public int getStartIndex(){
             int startIndex = 0;
             if(start<0){
              startIndex = 0;
             }
             else{
              if(start>page.getTotalPage()){
               startIndex = page.getPageSize()*(page.getTotalPage()-1);
              }
              else{
               startIndex = page.getPageSize()*(start-1);
              }
             }
             return startIndex;
          }

          public Page getPage(){
             return page;
          }
          }

          (4) 具體的業(yè)務對象分頁實現(xiàn)

          這里,MyUser類是一個POJO,查詢出結果需要分頁顯示。

          MyUser的分頁實現(xiàn)類為MyUserPage類,它應該繼承PageUtil類。因為PageUtil類繼承了HibernateDaoSupport類,所以需要注入一個SessionFactory,在action-servlet.xml中配置如下所示:

          <bean id="myUserPage" abstract="false"
             class="org.shirdrn.spring.pages.MyUserPage"
             lazy-init="default" autowire="default" dependency-check="default">
             <property name="sessionFactory">
              <ref bean="mySessionFactory"/>
             </property>
          </bean>
          </beans>

          具體地,MyUserPage類實現(xiàn)如下所示:

          package org.shirdrn.spring.pages;

          import java.sql.SQLException;
          import java.util.List;

          import org.hibernate.HibernateException;
          import org.hibernate.Query;
          import org.hibernate.Session;
          import org.shirdrn.spring.util.Page;
          import org.shirdrn.spring.util.PageUtil;
          import org.springframework.context.ApplicationContext;
          import org.springframework.context.support.ClassPathXmlApplicationContext;
          import org.springframework.orm.hibernate3.HibernateCallback;

          public class MyUserPage extends PageUtil {
          private String hql;

          public void init(int start,String hql){    // 通過init方法實現(xiàn)一個頁面的初始化
             page = new Page();
             this.hql = hql;
             this.start = start;
             setRowCount();
             setTotalPage();
             setCurrentPage();
             setPrePage();
             setNextPage();
             setPreOrNextBoolean();
          }

          @Override
          public int getRowCount(){
             List list = getHibernateTemplate().find(hql);
             if(list.isEmpty()){
              return 0;
             }
             return list.size();
          }

          @Override
          public Page getPage(){
             List list = (List)getHibernateTemplate().execute(new HibernateCallback(){
              public Object doInHibernate(Session session) throws HibernateException, SQLException {
               Query query = session.createQuery(hql);
               query.setFirstResult(getStartIndex());
               query.setMaxResults(page.getPageSize());
               return query.list();
              }   
             });
             page.setList(list);
             return page;
          }
          }

          上面實現(xiàn),使用了HQL檢索方式實現(xiàn)查詢數(shù)據(jù)庫記錄。

          在MyUserPage中可以使用帶參數(shù)的構造方法實現(xiàn)頁面的初始化,但是在使用構造方法注入的時候,很容易出錯,而且不直觀,所以直接通過調(diào)用實現(xiàn)的一個init方法來初始化。

          (6) Spring集成Struts

          需要在Struts的配置文件struts-config.xml中配置一個插件,如下所示:

          <?xml version="1.0" encoding="UTF-8"?>
          <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "

          <struts-config>
          <data-sources />
          <form-beans />
          <global-exceptions />
          <global-forwards />
          <action-mappings >
              <action path="/listMyUsers" type="org.shirdrn.struts.action.ListMyUsersAction">
                <forward
                  name="listmyusers"
                  path="/listmyusers.jsp"
                  redirect="true" />
              </action>
          </action-mappings>
          <message-resources parameter="org.shirdrn.struts.ApplicationResources" />
          <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
          <set-property property="contextConfigLocation"
             value="/WEB-INF/action-servlet.xml"/>
          </plug-in>

          </struts-config>

          只要這樣配置好,Struts才能初始化Spring的IoC容器,否則Action無法工作。

          (7) Action的實現(xiàn)

          SpringAction繼承了Spring的ActionSupport,我們將用它來替代所有繼承自Struts的Action類的Action。SpringAction的實現(xiàn)如下所示:

          package org.shirdrn.spring.action;

          import org.shirdrn.spring.pages.MyUserPage;
          import org.springframework.web.struts.ActionSupport;

          public class SpringAction extends ActionSupport {
          public MyUserPage getMyUserPage(){
             return (MyUserPage)getWebApplicationContext().getBean("myUserPage");
          }
          }

          這里,SpringAction就實現(xiàn)了獲取一個MyUserPage的實例的功能,從而通過這個實例實現(xiàn)分頁。

          然后,實現(xiàn)一個ListMyUsersAction類,它繼承自SpringAction,能夠啟動Spring的IoC容器,并且獲取一個MyUserPage的實例。ListMyUsersAction類的實現(xiàn)如下所示:

          package org.shirdrn.struts.action;

          import java.util.List;

          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;
          import javax.servlet.http.HttpSession;

          import org.apache.struts.action.ActionForm;
          import org.apache.struts.action.ActionForward;
          import org.apache.struts.action.ActionMapping;
          import org.shirdrn.spring.action.SpringAction;
          import org.shirdrn.spring.pages.MyUserPage;
          import org.shirdrn.spring.util.Page;

          public class ListMyUsersAction extends SpringAction {

          public ActionForward execute(ActionMapping mapping, ActionForm form,
              HttpServletRequest request, HttpServletResponse response) {
             int pno = (new Integer(request.getParameter("pno"))).intValue();
             String hql = "from MyUser";
             MyUserPage myUserPage = getMyUserPage();
             myUserPage.init(pno, hql);
             Page myUserOnePage = myUserPage.getPage();
             List myUserList = myUserPage.getPage().getList();
             HttpSession session = request.getSession();
             session.setAttribute("myUserOnePage", myUserOnePage);
             session.setAttribute("myUserList", myUserList);
             return mapping.findForward("listmyusers");
          }
          }

          (8) 視圖的實現(xiàn)

          JSP頁面,使用Struts標簽實現(xiàn)分頁頁面的顯示。

          JSP頁面listmyusers.jsp如下所示:

          <%@ page contentType="text/html;charset=utf-8"%>
          <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
          <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
          <%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%>
          <%
          String path = request.getContextPath();
          String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
          %>
          <html:html locale="true">
          <head>
          <base href="<%=basePath%>">
          <title>查詢記錄列表</title>
          <style type="text/css">
             body{
              background:#000000;
              font-size:12px;
              color:yellow;
             }
             a:link{
              color:yellow;
              text-decoration:none;
             }
             a:hover{
              color:red;
              text-decoration:none;
             }
             a:visited{
              color:yellow;
              text-decoration:none;
             }
          </style>
          </head>
          <body>
              <table width="60%" align="center" bgcolor="green" border="1">
                <tr>
                <th colspan="10">MyUser查詢列表</th>
                </tr>
                <tr align="center">
               <td width="20%"><b>ID</b></td>
                <td width="20%"><b>姓名</b></td>
                <td width="20%"><b>性別</b></td>
                <td width="20%"><b>年齡</b></td>
                <td width="20%"><b>住址</b></td>
                </tr>
                <logic:present name="myUserList">
                  <logic:iterate id="myUser" name="myUserList" type="org.shirdrn.spring.entity.MyUser">
                    <logic:present name="myUser">
                      <tr align="center">
                        <td width="20%" height="10"><bean:write name="myUser" property="id"/></td>
                        <td width="20%" height="10"><bean:write name="myUser" property="userName"/></td>
                        <td width="20%" height="10"><bean:write name="myUser" property="gender"/></td>
                        <td width="20%" height="10"><bean:write name="myUser" property="age"/></td>
                        <td width="20%" height="10"><bean:write name="myUser" property="addr"/></td>
                      </tr>
                    </logic:present>
                  </logic:iterate>
                </logic:present>
              </table>
              <table align="center" width="60%" bgcolor="green" border="1">
              <tr>
                 <td align="center" colspan="10">
                    <logic:present name="myUserOnePage">
                      <html:link page="/listMyUsers.do?pno=1">首頁</html:link>
                    <logic:equal name="myUserOnePage" property="hasPreviousPage" value="false">上一頁</logic:equal>
                    <logic:equal name="myUserOnePage" property="hasPreviousPage" value="true">
                     <a href="<%=path%>/listMyUsers.do?pno=<bean:write name="myUserOnePage" property="prePage"/>">上一頁</a>
                </logic:equal>
                     
                     每頁<bean:write name="myUserOnePage" property="pageSize"/>條記錄
                     共<bean:write name="myUserOnePage" property="rowCount"/>條記錄
                          當前第(<bean:write name="myUserOnePage" property="currentPage"/>/<bean:write name="myUserOnePage" property="totalPage"/>)頁
                  <logic:equal name="myUserOnePage" property="hasNextPage" value="false">下一頁</logic:equal>
                  <logic:equal name="myUserOnePage" property="hasNextPage" value="true">
                   <a href="<%=path%>/listMyUsers.do?pno=<bean:write name="myUserOnePage" property="nextPage"/>">下一頁</a>
                  </logic:equal>
                     <a href="<%=path%>/listMyUsers.do?pno=<bean:write name='myUserOnePage' property='totalPage'/>">末頁</a>
                  </logic:present>
                </td>
                </tr>
              </table>
          </body>
          </html:html>

          (9) 部署Web應用

          配置web.xml文件,如下所示:

          <?xml version="1.0" encoding="UTF-8"?>
          <web-app xmlns="
          http://localhost:8080/SpringHibernateStrutsPage/listMyUsers.do?pno=1

          就可以看到數(shù)據(jù)的分頁顯示,效果如圖所示:

           

          OK,就這么容易。


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


          網(wǎng)站導航:
           
          主站蜘蛛池模板: 扎兰屯市| 红原县| 博野县| 崇明县| 长宁县| 枞阳县| 定兴县| 沂南县| 芦山县| 辛集市| 唐海县| 旌德县| 广德县| 颍上县| 青冈县| 崇礼县| 富源县| 宁远县| 浠水县| 岱山县| 彰武县| 马公市| 谷城县| 额济纳旗| 香港 | 城市| 安乡县| 景德镇市| 肃宁县| 通城县| 石林| 福清市| 云阳县| 南汇区| 资中县| 凉山| 内丘县| 余干县| 云浮市| 边坝县| 江川县|