第一篇 struts與spring的融合
第一步:配置環(huán)境與技術(shù)支持
1、環(huán)境:tomcat5.0 + eclipse3.2.2 + myEclipse5.5 + jdk1.5
2、技術(shù):struts1.1+spring2.0
分析:經(jīng)過多次實驗,(初建struts+spring)項目中出現(xiàn)的問題和工具及技術(shù)版本沒有根本關(guān)系,只要在(其他項目運行)已經(jīng)配置成功的環(huán)境下運行就好。這里要注意的是:myEclipse5.0以下的版本不支持spring2.0。小小提示:本人初次在該環(huán)境下操作時,多次不成功,最后從新安裝配置環(huán)境后,struts+spring項目才正常運行,疑與myEclipse有關(guān)。
第二步:新建工程SSHProject
1、新建工程
分析:不同版本的eclipse新建項目對話框不同,3.2.2以下版本沒有java EE 5.0。這里我們選擇J2EE1.4!
2、導(dǎo)入struts包
3、導(dǎo)入spring包
分析:這里我們使用的是spring2.0,如果你的版本不支持2.0,就使用spring1.2版本。spring1.2與struts1.1同樣兼容,但spring1.2只支持hibernate3.0以下的版本。如果你選擇spring1.2,就不得不使用hibernate3.0或者2.1。小小提示:對于初學(xué)者來說,最好把所有的spring包導(dǎo)入項目。提醒:applicationContext.xml我們放在src下,但我們要知道編譯部署后,默認在classes文件夾,所以我們在以后的配置中,一定要注意路徑問題。
3、新建com.ssh.beans.po和com.ssh.beans.dao兩個包已做備用。
好了,工程框架已經(jīng)搭好,現(xiàn)在我們就可以往里面放東西了。
第三步 創(chuàng)建action和bean
1、在com.ssh.beans.po中創(chuàng)建Customer.java。內(nèi)容如下:
package com.ssh.beans.po;
public class Customer {
String custId;
String custName;
public Customer(){
}
public Customer(String custId,String custName){
this.custId=custId;
this.custName=custName;
}
public void setCustId(String custId){
this.custId=custId;
}
public String getCustId(){
return this.custId;
}
public void setCustName(String custName){
this.custName=custName;
}
public String getCustName(){
return this.custName;
}
}
2、在com.ssh.beans.dao中創(chuàng)建CustomerDAO.java及其接口ICustomerDAO.java。內(nèi)容如下:
package com.ssh.beans.dao;
import java.util.ArrayList;
import java.util.List;
import com.ssh.beans.po.Customer;
public class CustomerDAO implements ICustomerDAO {
public List getALLCustomer(){
List list=new ArrayList();
Customer c1=new Customer("1","zhang");
Customer c2=new Customer("2","xiaoling");
list.add(c1);
list.add(c2);
return list;
}
}
package com.ssh.beans.dao;
import java.util.List;
public interface ICustomerDAO {
public List getALLCustomer();
}
3、創(chuàng)建CustomerAction.java
分析:這里action的創(chuàng)建與我們以前創(chuàng)建action一樣,但我們要注意的是,你導(dǎo)入什么版本的struts就要生成什么版本的action,這里是struts1.1。
接下來我們看看struts-config.xml里面的內(nèi)容:
<?xml version="1.0" encoding="UTF-8"?> <struts-config> </action-mappings> <message-resources parameter="com.ssh.struts.ApplicationResources" /> 沒錯,內(nèi)容和我們以前的東東一樣。 我們再給CustomerAction.java一些內(nèi)容: package com.ssh.struts.action; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import com.ssh.beans.dao.CustomerDAO; public class CustomerAction extends Action { 好的,我們現(xiàn)在測試一下!如果訪問http://localhost:8080/SSHProject/customer.do能順利進入index.jsp頁面,并輸出用戶custName值,說明以上我們的工作是正確的! 第四步 配置stuts-config.xml和applicationContext.xml文件 看到這里,大家可能會認為,這和以前的web工程的創(chuàng)建沒有什么兩樣,和struts與spring融合沒有什么關(guān)系,不用著急,奧妙就在sturts-config.xml與applicationContext.xml文件配置中。 1、配置stuts-config.xml文件 在這里,我們要做兩個工作:第一,將CustomerAction替換成DelegatingActionProxy代理。第二,添加代理插件ContextLoaderPlugIn。修改后的內(nèi)容如下: <?xml version="1.0" encoding="UTF-8"?> <struts-config> <message-resources parameter="com.ssh.struts.ApplicationResources" /> 注:粗體字為修改的內(nèi)容 分析:你一定要做到:1、確保spring-struts.jar導(dǎo)入項目。2、保證applicationContext.xml文件路徑正確。我們在導(dǎo)入spring包時就提到,applicationContext.xml文件放在src下,編譯部署后,文件默認存放在WEB-INF/classes下。所以上面的配置為:value="/WEB-INF/classes/applicationContext.xml"/>。 2、配置applicationContext.xml 在這個文件中,我們的任務(wù)是加入我們需要的bean。到目前為止,我們要加入兩個bean,即:CustomerDAO與CustomerAction。修改后的內(nèi)容為: <?xml version="1.0" encoding="UTF-8"?> </beans> 注:粗體字為添加的內(nèi)容 分析:在這個文件中你要確保:第一,CustomerAction bean中<bean>標簽的屬性name值(name="/customer")一定與struts-config.xml中屬性path的值(path="/customer")一致。第二、<property>標簽的屬性name值在CustomerAction中一定有對應(yīng)的屬性。第三、<ref>標簽的屬性bean值一定與CustomerDAO bean的<bean>標簽的屬性name值一致(注:這就是注入目標對象)。第四、CustomerDAO bean中<bean>標簽的屬性class值一定是一個實現(xiàn)類(不能為接口)。
3、修改CustomerAction.java 這一步很簡單,只要把setCustomerDAO(new CustomerDAO());這條語句去掉就好。因為我們已經(jīng)在applicationContext.xml給customerDAO進行了setter注入。(呵呵,至于什么是setter注入,不了解的朋友先看看spring的IOC)。 好的,到現(xiàn)在為止,我們已經(jīng)對struts和spring進行了融合。再來測試一下,如果輸入同樣的內(nèi)容,就OK! 如果以上操作大家都沒有問題,我們就向下看。來吧,一起融合spring與hibernate 第二篇 Spring與Hibernate的融合 有的朋友可能只希望知道spring與hibernate的融合。所以在講struts+spring+hibernate之前,我們跳過使用stuts,先說一下spring+hibernate的融合。如果仍然用SSHProject這個項目,需要把po和dao包下面的類刪除,因為我們在生成影射文件和DAO時可能會出現(xiàn)重名文件。還有applicationContext.xml中的bean同樣刪除。 第一步 配置數(shù)據(jù)環(huán)境 既然我們用到hibernate,就要給他配置數(shù)據(jù)庫,這里我們使用的是mysql5.0。eclipse3.2.2一下的版本與3.2.2版本數(shù)據(jù)庫的配置是不同的,這里我們只講3.2.2的配置。 1、打開DB Brower 2、新建數(shù)據(jù)庫連接 在DB Brower中右鍵>新建打開下面對話框,選擇輸入正確的配置。提示:注意你的數(shù)據(jù)庫名、密碼、和驅(qū)動器。 單擊“完成”,測試如果連接到數(shù)據(jù)庫,就OK。 第二步 選擇hibernate與包的導(dǎo)入 1、hibernate的選擇 上面我們已經(jīng)提到,spring1.2只支持hibernate3.0以下的版本,所以如果你選擇的是spring1.2一定要注意這個問題。這里我使用的是hibernate3.1 2、包的導(dǎo)入 單擊“完成”OK。 分析:在導(dǎo)入包時出現(xiàn)幾個問題:1、在找spring建好的applicationContext.xml文件時沒有找到路徑,被迫把其他項目的數(shù)據(jù)庫連接bean考到該文件內(nèi)((注:僅僅是我存在的問題)。2、把自動生成的sessionFactory刪除。3、最后可能會出現(xiàn)找不到包,所以你要手動添加幾個包。 現(xiàn)在我們看看applicationContext.xml文件內(nèi)容有什么變化,內(nèi)容如下: <?xml version="1.0" encoding="UTF-8"?> </beans> 注:粗體字為自動加入的內(nèi)容。 第三步 創(chuàng)建影射文件po及dao 1、創(chuàng)建影射文件 首先你要確定所需要的包都導(dǎo)入classpath路徑中,否則在創(chuàng)建影射文件中會出現(xiàn)一些不能操作的對象。如果出現(xiàn)問題,建議大家多重復(fù)做幾次。 單擊"完成",就OK。 在包資源管理器中我們可以看到,自動生成四個文件,包括CustomerDAO。 為了方便操作我們包CustomerDAO放在dao包下。如果你沒有刪除ICustomerDAO接口,那我們就使用它了(因為spring是面對接口的,所以我們的操作都應(yīng)該經(jīng)過接口)。 接下來,我們再看看applicationContext.xml有什么變化。內(nèi)容如下: <?xml version="1.0" encoding="UTF-8"?> 注:粗體字為新內(nèi)容。提醒:如果你沒有改CustomerDAO的路徑,它應(yīng)該在po包下。 2、創(chuàng)建dao。 CustomerDAO.java我們使用hibernate自動生成,ICustomerDAO.java接口使用我們以前建好的。 3、創(chuàng)建測試類 既然我們不使用action,那么我們就新建一個類Test.java用于測試。內(nèi)容如下: package com.ssh.struts.action; import java.util.List; import org.springframework.context.ApplicationContext; import com.ssh.beans.dao.CustomerDAO; public class Test{ 分析:在測試中可能出現(xiàn)兩個異常: 異常一、java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool。如果出現(xiàn)這個異常說明缺少commons-pool-1.2.jar包。 異常二、org.apache.commons.dbcp.SQLNestedException: Cannot load JDBC driver class 'com.mysql.jdbc.Driver';;;Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver。如果出現(xiàn)這個異常,說明在構(gòu)建路徑中沒有驅(qū)動包。 好的,我們現(xiàn)在測試一下,如果System.out.println("list.size():"+list.size());執(zhí)行,說明我們對spring與hibernate的融合成功了。 第三篇 整合struts+spring+hibernate 我們在上兩篇的基礎(chǔ)只要再對applicationContext.xml文件進行修改,就可以達到我們整合的目地。 第一步 完善applicationContext.xml內(nèi)容 1、添加事務(wù)處理。內(nèi)容如下: <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 2、CustomerAction Bean注入事務(wù)處理。內(nèi)容如下: <bean name="/customer" class="com.ssh.struts.action.CustomerAction" > 3、最終applicationContext.xml文件,內(nèi)容如下: <?xml version="1.0" encoding="UTF-8"?> 第二步,修改CustomerAction 最后內(nèi)容如下: import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import com.ssh.beans.dao.ICustomerDAO; 第三步 解決找不到Action問題 初學(xué)者會經(jīng)常遇到下面這個問題: type Status report message Servlet action is not available description The requested resource (Servlet action is not available) is not available. 就是找不到我們的action。 當你努力去解決這個問題時,會發(fā)現(xiàn)去掉applicationContext.xml下面這個<property>標簽,一切正常: <property name="mappingResources"> 那是什么原因呢?我想大家都會首先想到下面兩個問題: 1、路徑是否正確:即com/ssh/beans/po/Customer.hbm.xml的路徑正確么? 2、文件是否正確:即Customer.hbm.xml的文件內(nèi)容對么? 當你費了一身力氣發(fā)現(xiàn)一切OK,到底什么原因??? 問題在于構(gòu)件路徑(lib)內(nèi)的包重疊(提示:前提是你要保證這個問題出現(xiàn)之前都正常),所以你要確定構(gòu)建路徑里的包不能重復(fù)! 建議:大家在導(dǎo)入包時,按照默認導(dǎo)入,不要把所有的包都導(dǎo)進工程,在操作中在把需要的jar包導(dǎo)進去(最好不要把整個liberaries導(dǎo)進去),這樣即可以減小工程的大小,又能確保struts\spring\hibernate之間的包不會重疊或者被替換。 好了,我的任務(wù)完成了,大家刪包去吧!祝你好運!
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "
<data-sources />
<form-beans />
<global-exceptions />
<global-forwards />
<action-mappings >
<action path="/customer" type="com.ssh.struts.action.CustomerAction">
<forward name="success" path="/index.jsp" />
</action>
</struts-config>
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.ssh.beans.dao.ICustomerDAO;
import com.ssh.beans.po.Customer;
ICustomerDAO customerDAO=null;
public void setCustomerDAO(ICustomerDAO customerDAO){
this.customerDAO=customerDAO;
}
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
List list=new ArrayList();
Customer customer=null;
setCustomerDAO(new CustomerDAO());
if(customerDAO!=null){
list=customerDAO.getALLCustomer();
for(int i=0;i<list.size();i++){
customer=(Customer)list.get(i);
System.out.println("OK:"+customer.getCustName());
}
}else{
System.out.println("ERROR or NULL");
}
return mapping.findForward("success");
}
}
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "
<data-sources />
<form-beans />
<global-exceptions />
<global-forwards />
<action-mappings >
<action path="/customer" type="org.springframework.web.struts.DelegatingActionProxy">
<forward name="success" path="/index.jsp" />
</action>
</action-mappings>
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/classes/applicationContext.xml"/>
</plug-in>
</struts-config>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean name="/customer" class="com.ssh.struts.action.CustomerAction" >
<property name="customerDAO"><ref bean="customerDAO"/></property>
</bean>
<bean name="customerDAO" class="com.ssh.beans.dao.CustomerDAO" />
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://localhost:3306/pullhand">
</property>
<property name="username" value="root"></property>
<property name="password" value="815241"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
</bean>
<beans
xmlns="
xmlns:xsi="
xsi:schemaLocation="http://www.springframework.org/schema/beans
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://localhost:3306/pullhand">
</property>
<property name="username" value="root"></property>
<property name="password" value="815241"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/ssh/beans/po/Customer.hbm.xml</value></list>
</property>
</bean>
<bean id="CustomerDAO" class="com.ssh.beans.dao.CustomerDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
</beans>
import org.springframework.context.support.ClassPathXmlApplicationContext;
private ApplicationContext context;
private void test(){
CustomerDAO customerDAO=(CustomerDAO)context.getBean("customerDAO");
List list=customerDAO.findAll();
if(list!=null&&list.size()>0){
System.out.println("list.size():"+list.size());
}else{
System.out.println("ERROR or NULL");
}
}
private void run(){
context=new ClassPathXmlApplicationContext("applicationContext.xml");
test();
}
public static void main(String[] args){
new Test().run();
}
}
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<bean id="customerDAOProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="target">
<ref local="customerDAO" />
</property>
<property name="transactionAttributes">
<props>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<property name="customerDAO"><ref bean="customerDAOProxy"/></property>
</bean>
<beans
xmlns="
xmlns:xsi="
xsi:schemaLocation="http://www.springframework.org/schema/beans
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://localhost:3306/pullhand">
</property>
<property name="username" value="root"></property>
<property name="password" value="815241"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>com/ssh/beans/po/Customer.hbm.xml</value></list>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory" />
</property>
</bean>
<bean id="customerDAOProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="target">
<ref local="customerDAO" />
</property>
<property name="transactionAttributes">
<props>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
<bean id="customerDAO" class="com.ssh.beans.dao.CustomerDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<bean name="/customer" class="com.ssh.struts.action.CustomerAction" >
<property name="customerDAO"><ref bean="customerDAOProxy"/></property>
</bean>
</beans>
package com.ssh.struts.action;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.ssh.beans.po.Customer;
public class CustomerAction extends Action {
ICustomerDAO customerDAO=null;
public void setCustomerDAO(ICustomerDAO customerDAO){
this.customerDAO=customerDAO;
}
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
List list=new ArrayList();
Customer customer=null;
if(customerDAO!=null){
list=customerDAO.getALLCustomer();
for(int i=0;i<list.size();i++){
customer=(Customer)list.get(i);
System.out.println("OK:"+customer.getCustName());
}
}else{
System.out.println("ERROR or NULL");
}
return mapping.findForward("success");
}
}HTTP Status 404 - Servlet action is not available
Apache Tomcat/5.0.28
<list>
<value>
com/ssh/beans/po/Customer.hbm.xml
</value>
</list>
</property>