Struts+Spring+Hibernate搭建过程顺序详解

第一篇 strutsspring的融合

第一:配置境与技支持

1境:tomcat5.0 + eclipse3.2.2 + myEclipse5.5 + jdk1.5

2、技struts1.1+spring2.0

分析经过多次实验,(初建struts+spring目中出问题和工具及技版本没有根本系,只要在(其他目运行)已配置成功的境下运行就好。里要注意的是:myEclipse5.0以下的版本不支持spring2.0。小小提示:本人初次在该环境下操作,多次不成功,最后从新安装配置境后,struts+spring目才正常运行,疑与myEclipse

第二:新建工程SSHProject

1、新建工程

分析:不同版本的eclipse新建对话框不同,3.2.2以下版本没有java EE 5.0里我们选择J2EE1.4

2struts

3spring

分析:里我使用的是spring2.0,如果你的版本不支持2.0,就使用spring1.2版本。spring1.2struts1.1兼容,但spring1.2只支持hibernate3.0以下的版本。如果你选择spring1.2,就不得不使用hibernate3.0或者2.1。小小提示:于初学者来,最好把所有的spring目。提醒:applicationContext.xml放在src下,但我要知道编译部署后,默classes文件,所以我在以后的配置中,一定要注意路径问题

3、新建com.ssh.beans.pocom.ssh.beans.dao两个包已做用。

好了,工程框架已搭好,在我就可以往里面放西了。

第三 actionbean

1、在com.ssh.beans.poCustomer.java。内容如下:

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.daoCustomerDAO.java及其接口ICustomerDAO.java。内容如下:

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();
}

3CustomerAction.java

分析action建与我以前action,但我要注意的是,你入什版本的struts就要生成什版本的action里是struts1.1

接下来我看看struts-config.xml里面的内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
<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>

</action-mappings>

<message-resources parameter="com.ssh.struts.ApplicationResources" />
</struts-config>

,内容和我以前的东东

CustomerAction.java一些内容:

package com.ssh.struts.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
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.CustomerDAO;
import com.ssh.beans.dao.ICustomerDAO;
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;
  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");
}
}

好的,我们现测试一下!如果访问http://localhost:8080/SSHProject/customer.doindex.jsp面,并出用custName明以上我的工作是正确的!

这里要先部署一下tomcat :在tomcat路径下“ F:/Program Files/Apache Software Foundation/Tomcat 5.5/conf/Catalina/localhost”新建一个SSHProject.xml文件,里面加入如下代码:

<?xml version='1.0' encoding='utf-8'?>

<Context docBase="D:/workspace/SSHProject/WebRoot"

           path="/SSHProject" reloadable="true"

           workDir="D:/workspace/SSHProject/work/org/apache/jsp">

</Context>

第四 配置stuts-config.xmlapplicationContext.xml文件

看到里,大家可能会认为和以前的web工程的建没有什,和strutsspring融合没有什么关系,不用着急,奥妙就在sturts-config.xmlapplicationContext.xml文件配置中。

1、配置stuts-config.xml文件

里,我要做两个工作:第一,将CustomerActionDelegatingActionProxy代理。第二,添加代理插件ContextLoaderPlugIn。修改后的内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>
<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>

<message-resources parameter="com.ssh.struts.ApplicationResources" />

<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
     <set-property property="contextConfigLocation"
         value="/WEB-INF/classes/applicationContext.xml"/>
</plug-in>

</struts-config>

注:粗体字修改的内容

分析:你一定要做到:1、确保spring-struts.jar目。2、保applicationContext.xml文件路径正确。我spring就提到,applicationContext.xml文件放在src下,编译部署后,文件默存放在WEB-INF/classes下。所以上面的配置value="/WEB-INF/classes/applicationContext.xml"/>

2、配置applicationContext.xml

个文件中,我的任是加入我需要的bean。到目前止,我要加入两个bean,即:CustomerDAOCustomerAction。修改后的内容

<?xml version="1.0" encoding="UTF-8"?>
<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>

注:粗体字添加的内容

分析:个文件中你要确保:第一,CustomerAction bean<bean>标签的属性name(name="/customer")一定与struts-config.xml中属性path(path="/customer")一致。第二、<property>标签的属性nameCustomerAction中一定有对应的属性。第三、<ref>标签的属性bean一定与CustomerDAO bean<bean>标签的属性name一致(注:就是注入目标对)。第四、CustomerDAO bean<bean>标签的属性class一定是一个实现类(不能接口)

3、修改CustomerAction.java

简单,只要把setCustomerDAO(new CustomerDAO());句去掉就好。因applicationContext.xmlcustomerDAO行了setter注入。(呵呵,至于什setter注入,不了解的朋友先看看springIOC)

好的,到止,我经对strutsspring行了融合。再来测试一下,如果入同的内容,就OK

如果以上操作大家都没有问题,我就向下看。来吧,一起融合springhibernate

第二篇 SpringHibernate的融合

有的朋友可能只希望知道springhibernate的融合。所以在struts+spring+hibernate之前,我使用stuts,先一下spring+hibernate的融合。如果仍然用SSHProject目,需要把podao包下面的类删除,因在生成影射文件和DAO可能会出重名文件。applicationContext.xml中的bean样删除。

第一 配置数据

既然我用到hibernate,就要他配置数据里我使用的是mysql5.0eclipse3.2.2一下的版本与3.2.2版本数据的配置是不同的,里我3.2.2的配置。

1、打DB Brower

2、新建数据库连

DB Brower中右>新建打下面对话框,选择输入正确的配置。提示:注意你的数据名、密、和驱动器。

单击完成测试如果接到数据,就OK

第二 选择hibernate与包的

1hibernate选择

上面我提到,spring1.2只支持hibernate3.0以下的版本,所以如果你选择的是spring1.2一定要注意问题里我使用的是hibernate3.1

2、包的

单击完成”OK

分析:入包几个问题1、在找spring建好的applicationContext.xml文件没有找到路径,被迫把其他目的数据库连bean考到文件内((注:仅仅是我存在的问题)2、把自生成的sessionFactory除。3、最后可能会出找不到包,所以你要手添加几个包。

在我看看applicationContext.xml文件内容有什么变化,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<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>

注:粗体字加入的内容。

第三 建影射文件podao

1建影射文件

首先你要确定所需要的包都classpath路径中,否建影射文件中会出一些不能操作的象。如果出现问题,建大家多重做几次。

单击"完成",就OK

在包源管理器中我可以看到,自生成四个文件,包括CustomerDAO

了方便操作我CustomerDAO放在dao包下。如果你没有ICustomerDAO接口,那我就使用它了(spring是面接口的,所以我的操作都应该经过接口)

接下来,我再看看applicationContext.xml有什么变化。内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<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>
   <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>

注:粗体字新内容。提醒:如果你没有改CustomerDAO的路径,它应该po包下。

2dao

CustomerDAO.java使用hibernate生成,ICustomerDAO.java接口使用我以前建好的。

3测试类

既然我不使用action,那就新建一个Test.java用于测试。内容如下:

package com.ssh.struts.action;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.ssh.beans.dao.CustomerDAO;

public class Test{

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();
}
}

内容补充:

补充一:测试Test.java的内容改为:

package com.ssh.struts.action;

 

import java.util.List;

 

import org.springframework.context.ApplicationContext;

import org.springframework.context.support.ClassPathXmlApplicationContext;

 

import com.ssh.beans.dao.TrVoyDAO;

import com.ssh.beans.po.TrVoy;

 

public class Test{

 

private ApplicationContext context;

 

       private void test(){

              TrVoyDAO customerDAO=(TrVoyDAO)context.getBean("TrVoyDAO");

         

              List list = customerDAO.getALLCustomer();

          if(list!=null&&list.size()>0){

                 System.out.println("list.size():"+list.size());

                

                 for (int i = 0; i < list.size(); i++) {

                        TrVoy trVoy = (TrVoy)list.get(i);

                       

                        System.out.println(trVoy.getVslCd() + " " + trVoy.getVoyNo());

                 }

                

          }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();

       }

}

补充二:系统生成的TrVoyDAO要实现ICustomerDAO接口里的getALLCustomer()方法。TrVoyDAOgetALLCustomer()方法实现如下:

public List getALLCustomer(){

              Session session = getSession();

              List list=new ArrayList();

//            Customer c1=new Customer("1","zhang");

//            Customer c2=new Customer("2","xiaoling");

//            list.add(c1);

//            list.add(c2);

              Query bemQuery = session.createQuery("from TrVoy");

              list = bemQuery.list();

              return list;

       }

特别注意,这里的from TrVoy 是类名而不是table名。

分析:测试中可能出两个异常:

异常一、java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool。如果出现这个异常明缺少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如果出现这个异常,明在构建路径中没有驱动包。

补充异常一:即异常二。

解决方案:把从oracle根目oracle/ora92/jdbc/lib/classes12.jar 拷到/SSHProject/WebRoot/WEB-INF/lib

补充异常二log4j:WARN Please initialize the log4j system properly

解决方案log4j.properties文件需要放到web-inf/class目录下面,eclipse里面放到src目录下面,会自动拷贝到class目录下面去。

文件里面的内容如下即可:

log4j.rootLogger=WARN, Console

 

log4j.appender.Console=org.apache.log4j.ConsoleAppender

log4j.appender.Console.layout=org.apache.log4j.PatternLayout

log4j.appender.Console.layout.ConversionPattern=(%r ms) [%t] %-5p: %c#%M %x: %m%n

 

log4j.logger.com.genuitec.eclipse.sqlexplorer=DEBUG

log4j.logger.org.apache=WARN

log4j.logger.org.hibernate=WARN

补充异常三:错误处(0 ms) [main] WARN : net.sf.ehcache.config.Configurator#configure : No configuration found.

解决方案:

原因:报这是因/sandh/web-inf/classes下面没有ehcache.xml个文件!个文件是hibernate存配置文件。

解决方法:从/SSHProject/WebRoot/WEB-INF/lib里的ehcache-1.1.jar  中把文件ehcache-failsafe.xml  出来改名 ehcache.xml 制到classes下面就行了!

 

好的,我们现测试一下,如果System.out.println("list.size():"+list.size());行,明我们对springhibernate的融合成功了。

第三篇 整合struts+spring+hibernate

在上两篇的基只要再applicationContext.xml文件行修改,就可以达到我整合的目地。

第一 完善applicationContext.xml内容

1、添加事务处理。内容如下:

  <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>

2CustomerAction Bean注入事务处理。内容如下:

   <bean name="/customer" class="com.ssh.struts.action.CustomerAction" >
      <property name="customerDAO">
<ref bean="customerDAOProxy"/></property>
   </bean>

3、最applicationContext.xml文件,内容如下:

<?xml version="1.0" encoding="UTF-8"?>
<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>
   <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>

第二,修改CustomerAction

最后内容如下:


package com.ssh.struts.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
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;


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");
}
}

第三 解决找不到Action问题

初学者会常遇到下面问题

HTTP Status 404 - Servlet action is not available


type Status report

message Servlet action is not available

description The requested resource (Servlet action is not available) is not available.


Apache Tomcat/5.0.28

就是找不到我action

当你努力去解决问题时,会发现去掉applicationContext.xml下面<property>标签,一切正常:

   <property name="mappingResources">
    <list>
     <value>
      com/ssh/beans/po/Customer.hbm.xml
     </value>
    </list>
   </property>

那是什原因呢?我想大家都会首先想到下面两个问题

1、路径是否正确:即com/ssh/beans/po/Customer.hbm.xml的路径正确

2、文件是否正确:即Customer.hbm.xml的文件内容对么

当你了一身力气发现一切OK,到底什原因???

问题在于构件路径(lib)内的包重叠(提示:前提是你要保证这问题之前都正常),所以你要确定构建路径里的包不能重

大家在入包,按照默认导入,不要把所有的包都导进工程,在操作中在把需要的jar导进(最好不要把整个liberaries导进去),这样即可以减小工程的大小,又能确保struts/spring/hibernate的包不会重叠或者被替

好了,我的任完成了,大家包去吧!祝你好运

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值