Spring+Hibernate+Struts實(shí)現(xiàn)分頁(yè)
Posted on 2008-06-12 15:45 七郎歸來(lái) 閱讀(878) 評(píng)論(0) 編輯 收藏Spring+Hibernate+Struts實(shí)現(xiàn)分頁(yè)
Spring集成Hibernate,使得SessionFactory的管理更加方便,可以方便地獲取到一個(gè)HibernateTempalte的模板實(shí)例,對(duì)數(shù)據(jù)庫(kù)的操作非常方便。
Spring集成Struts,先把Struts的Action用Spring的ActionSupport抽象出來(lái),比如定義一個(gè)名稱為SpringAction的的ActionSupport的子類,其中SpringAction中啟動(dòng)IoC容器,通過(guò)ApplicationContext獲取業(yè)務(wù)bean。這需要使用一個(gè)Struts插件來(lái)初始化IoC容器,從而獲取到一個(gè)ApplicationContext。可以通過(guò)讓每個(gè)具體的Action(每個(gè)具體的Action意思是實(shí)現(xiàn)Struts的Action的子類)都繼承自上面定義的SpringAction,實(shí)現(xiàn)對(duì)模型的調(diào)用,以及派發(fā)視圖。
下面通過(guò)實(shí)現(xiàn)分頁(yè)來(lái)說(shuō)明。
實(shí)現(xiàn)思路
Spring集成Hibernate,直接使用Hibernatede配置文件hibernate.cfg.xml,注入一個(gè)SessionFactory,從而在DAO中獲取到一個(gè)HibernateTemplate。
(注意,下面工程結(jié)構(gòu)中,實(shí)際上包org.shirdrn.spring.dao及其包org.shirdrn.spring.daoImpl中的接口和類并沒有使用到。)
org.shirdrn.spring.util.Page類是一個(gè)頁(yè)面的實(shí)體類,沒有加入任何分頁(yè)邏輯,而實(shí)現(xiàn)分頁(yè)邏輯的抽象是在org.shirdrn.spring.util.PageUtil類中,該類是對(duì)所有需要實(shí)現(xiàn)分頁(yè)的業(yè)務(wù)對(duì)象分頁(yè)邏輯的抽象,而且PageUtil類繼承自HibernateDaoSupport類,它是一個(gè)具有特殊業(yè)務(wù)需(分頁(yè))要的DAO,只是為獲取分頁(yè)結(jié)果而定義的,只要注入一個(gè)SessionFactory就可以方便地檢索數(shù)據(jù)庫(kù)了。所有的具體的業(yè)務(wù)對(duì)象如果需要分頁(yè)顯示的數(shù)據(jù)庫(kù)記錄,都可以從繼承PageUtil類。
包org.shirdrn.spring.pages中有一個(gè)MyUserPage類,該類繼承自PageUtil類,是一個(gè)具體實(shí)現(xiàn)分頁(yè)邏輯的類,只對(duì)MyUser實(shí)體(對(duì)應(yīng)數(shù)據(jù)庫(kù)中myUser表)的分頁(yè)進(jìn)行處理。
開發(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
工程結(jié)構(gòu)
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ā)過(guò)程
(1) Hibernate準(zhǔn)備
編寫Hibernate配置文件hibernate.cfg.xml:
<?xml version='1.0' encoding='UTF-8'?> <!-- Generated by MyEclipse Hibernate Tools. --> <session-factory> </session-factory> </hibernate-configuration> 實(shí)現(xiàn)Hibernate映射文件MyUser.hbm.xml,及其對(duì)應(yīng)的POJO: 這個(gè)非常容易,就省略了。 (2) Spring集成Hibernate 在/WEB-INF/目錄下面,新建一個(gè)action-servlet.xml的Spring配置文件,因?yàn)楹竺嬉蚐truts集成,所以根據(jù)格式<SERVLETNAME>-servlet.xml,應(yīng)該使用Struts的Servlet映射名稱。 Spring集成Hibernate,在action-servlet.xml中配置如下: <bean id="mySessionFactory" (3) 頁(yè)面實(shí)體及分頁(yè)邏輯實(shí)現(xiàn) Page是一個(gè)頁(yè)面實(shí)體類,如下: package org.shirdrn.spring.util; import java.util.List; public class Page { public int getCurrentPage() { public void setCurrentPage(int currentPage) { public List getList() { public void setList(List list) { public int getNextPage() { public void setNextPage(int nextPage) { public int getPageSize() { public void setPageSize(int pageSize) { public int getPrePage() { public void setPrePage(int prePage) { public int getRowCount() { public void setRowCount(int rowCount) { public int getTotalPage() { public void setTotalPage(int totalPage) { public boolean isHasNextPage() { public void setHasNextPage(boolean hasNextPage) { public boolean isHasPreviousPage() { public void setHasPreviousPage(boolean hasPreviousPage) { PageUtil類是一個(gè)分頁(yè)邏輯的抽象,需要分頁(yè)的話,只需要繼承自它便可以方便地實(shí)現(xiàn)分頁(yè),可見,PageUtil可以重用,如下所示: package org.shirdrn.spring.util; import org.shirdrn.spring.pages.MyUserPage; public class PageUtil extends HibernateDaoSupport { (4) 具體的業(yè)務(wù)對(duì)象分頁(yè)實(shí)現(xiàn) 這里,MyUser類是一個(gè)POJO,查詢出結(jié)果需要分頁(yè)顯示。 MyUser的分頁(yè)實(shí)現(xiàn)類為MyUserPage類,它應(yīng)該繼承PageUtil類。因?yàn)镻ageUtil類繼承了HibernateDaoSupport類,所以需要注入一個(gè)SessionFactory,在action-servlet.xml中配置如下所示: <bean id="myUserPage" abstract="false" 具體地,MyUserPage類實(shí)現(xiàn)如下所示: package org.shirdrn.spring.pages; import java.sql.SQLException; import org.hibernate.HibernateException; public class MyUserPage extends PageUtil { 上面實(shí)現(xiàn),使用了HQL檢索方式實(shí)現(xiàn)查詢數(shù)據(jù)庫(kù)記錄。 在MyUserPage中可以使用帶參數(shù)的構(gòu)造方法實(shí)現(xiàn)頁(yè)面的初始化,但是在使用構(gòu)造方法注入的時(shí)候,很容易出錯(cuò),而且不直觀,所以直接通過(guò)調(diào)用實(shí)現(xiàn)的一個(gè)init方法來(lái)初始化。 (6) Spring集成Struts 需要在Struts的配置文件struts-config.xml中配置一個(gè)插件,如下所示: <?xml version="1.0" encoding="UTF-8"?> <struts-config> 只要這樣配置好,Struts才能初始化Spring的IoC容器,否則Action無(wú)法工作。 (7) Action的實(shí)現(xiàn) SpringAction繼承了Spring的ActionSupport,我們將用它來(lái)替代所有繼承自Struts的Action類的Action。SpringAction的實(shí)現(xiàn)如下所示: package org.shirdrn.spring.action; import org.shirdrn.spring.pages.MyUserPage; public class SpringAction extends ActionSupport { 這里,SpringAction就實(shí)現(xiàn)了獲取一個(gè)MyUserPage的實(shí)例的功能,從而通過(guò)這個(gè)實(shí)例實(shí)現(xiàn)分頁(yè)。 然后,實(shí)現(xiàn)一個(gè)ListMyUsersAction類,它繼承自SpringAction,能夠啟動(dòng)Spring的IoC容器,并且獲取一個(gè)MyUserPage的實(shí)例。ListMyUsersAction類的實(shí)現(xiàn)如下所示: package org.shirdrn.struts.action; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionForm; public class ListMyUsersAction extends SpringAction { public ActionForward execute(ActionMapping mapping, ActionForm form, (8) 視圖的實(shí)現(xiàn) JSP頁(yè)面,使用Struts標(biāo)簽實(shí)現(xiàn)分頁(yè)頁(yè)面的顯示。 JSP頁(yè)面listmyusers.jsp如下所示: <%@ page contentType="text/html;charset=utf-8"%> (9) 部署Web應(yīng)用 配置web.xml文件,如下所示: <?xml version="1.0" encoding="UTF-8"?> 就可以看到數(shù)據(jù)的分頁(yè)顯示,效果如圖所示: OK,就這么容易。
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"
<hibernate-configuration>
<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" />
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
</bean>
private int pageSize;
private int totalPage;
private int rowCount;
private int currentPage;
private int prePage;
private int nextPage;
private boolean hasNextPage; // 是否有下一頁(yè)
private boolean hasPreviousPage; // 是否有前一頁(yè)
private List list;
public Page(){
this.pageSize = 10;
}
return currentPage;
}
this.currentPage = currentPage;
}
return list;
}
this.list = list;
}
return nextPage;
}
this.nextPage = nextPage;
}
return pageSize;
}
this.pageSize = pageSize;
}
return prePage;
}
this.prePage = prePage;
}
return rowCount;
}
this.rowCount = rowCount;
}
return totalPage;
}
this.totalPage = totalPage;
}
return hasNextPage;
}
this.hasNextPage = hasNextPage;
}
return hasPreviousPage;
}
this.hasPreviousPage = hasPreviousPage;
}
}
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.orm.hibernate3.support.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;
}
}
class="org.shirdrn.spring.pages.MyUserPage"
lazy-init="default" autowire="default" dependency-check="default">
<property name="sessionFactory">
<ref bean="mySessionFactory"/>
</property>
</bean>
</beans>
import java.util.List;
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;
private String hql;
public void init(int start,String hql){ // 通過(guò)init方法實(shí)現(xiàn)一個(gè)頁(yè)面的初始化
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;
}
}
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "
<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>
import org.springframework.web.struts.ActionSupport;
public MyUserPage getMyUserPage(){
return (MyUserPage)getWebApplicationContext().getBean("myUserPage");
}
}
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
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;
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");
}
}
<%@ 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">首頁(yè)</html:link>
<logic:equal name="myUserOnePage" property="hasPreviousPage" value="false">上一頁(yè)</logic:equal>
<logic:equal name="myUserOnePage" property="hasPreviousPage" value="true">
<a href="<%=path%>/listMyUsers.do?pno=<bean:write name="myUserOnePage" property="prePage"/>">上一頁(yè)</a>
</logic:equal>
每頁(yè)<bean:write name="myUserOnePage" property="pageSize"/>條記錄
共<bean:write name="myUserOnePage" property="rowCount"/>條記錄
當(dāng)前第(<bean:write name="myUserOnePage" property="currentPage"/>/<bean:write name="myUserOnePage" property="totalPage"/>)頁(yè)
<logic:equal name="myUserOnePage" property="hasNextPage" value="false">下一頁(yè)</logic:equal>
<logic:equal name="myUserOnePage" property="hasNextPage" value="true">
<a href="<%=path%>/listMyUsers.do?pno=<bean:write name="myUserOnePage" property="nextPage"/>">下一頁(yè)</a>
</logic:equal>
<a href="<%=path%>/listMyUsers.do?pno=<bean:write name='myUserOnePage' property='totalPage'/>">末頁(yè)</a>
</logic:present>
</td>
</tr>
</table>
</body>
</html:html>
<web-app xmlns="http://localhost:8080/SpringHibernateStrutsPage/listMyUsers.do?pno=1