Spring+Hibernate+Struts

转载地址:http://www.blogjava.net/blameswood/articles/189085.html

===============Spring+Hibernate+Struts配置===============
spring加载log4j
   web.xml

   < context - param >
    
< param - name > log4jConfigLocation </ param - name >
    
< param - value >/ WEB - INF / classes / log4j.properties </ param - value >
  
</ context - param >
  
< listener >
    
< listener - class > org.springframework.web.util.Log4jConfigListener </ listener - class >
  
</ listener >


一.spring+struts
1.加载springContext
      通过struts-config.xml中增加plug-in插件来加载springContext
   <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
     <set-property property="contextConfigLocation" value="/WEB-INF/applicationContext.xml" />
   </plug-in>
  
applicationContext.xml为spring的配置文件

2.将strutsAction交给Spring容器进行管理
      修改struts-config.xml中的action属性,action的type值不指定具体的实现类,统一修改成代理类

  
  <action input="/login.jsp"
         name="loginActionForm"
         path="/loginAction" 
         scope="request"   
         type="org.springframework.web.struts.DelegatingActionProxy"
         validate="false">
      <forward name="success" path="/success.jsp" />
      <forward name="failure" path="/failure.jsp" />
    </action>

3.在applicationContext.xml中的bean name值设定与struts-config.xml中action path值相对应,以使代理类DelegatingActionProxy能够根据传入的path在springContext中找到相应的bean,并将实例返回给struts.
<bean name="/loginAction" class="com.derek.action.LoginAction" singleton="false">
  <property name="login">
    <ref bean="loginBOProxy" />
  </property>
</bean>

二.spring+hibernate
  
1.dateSource
      在springContext中设置dateSource Bean
     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="net.sourceforge.jtds.jdbc.Driver"></property>
        <property name="url" value="jdbc:jtds:sqlserver://192.168.56.32:1433/testDB"></property>
        <property name="username" value="it"></property>
        <property name="password" value="it"></property>
     </bean>
     2.sessionFactory
       在springContext中设置sessionFactory Bean
  <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <property name="mappingResources">
        <list>
          <value>hbm/OvertimeRecord.hbm.xml</value><!--hbm映射文件-->
          <value>hbm/OvertimePermit.hbm.xml</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
           <prop key="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</prop>
           <prop key="hibernate.show_sql">true</prop>
           <prop key="hibernate.jdbc.fetch_size">50</prop>
           <prop key="hibernate.jdbc.batch_size">20</prop>
        </props>
    </property>
  </bean>
 
 
3.transactionManager
   在springContext中设置transactionManager Bean
 
  <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
     <property name="sessionFactory">
       <ref local="sessionFactory" />
     </property>
   </bean>

  
4.DAO bean
      <bean id="Ilogin" class="com.derek.business.Login">
          <property name="sessionFactory">
              <ref local="sessionFactory"/>
          </property>
      </bean>
      public class Login extends HibernateDaoSupport implements LoginInterface
      DAO 继承HibernateDaoSupport
      HibernateSupport实现了HibernateTemplate和SessionFactory实例的关联, HibernateTemplate对Hibernate Session操作进行了封装,HibernateTemplate.execute方法则是一封装机制的核心. 借助HibernateTemplate我们可以脱离每次数据操作必须首先获得Session实例、启动事务、提交/回滚事务以及烦杂的try/catch/finally的繁琐操作.
        Spring中的事务管理实际上是基于动态AOP机制实现,为了实现动态AOP,Spring在默认情况下会使用Java DynamicProxy,但是,Dynamic Proxy要求其代理的对象必须实现一个接口,该接口定义了准备进行代理的方法。而对于没有实现任何接口的Java Class,需要采用其他方式,Spring通过CGLib实现这一功能。


   5.DAOProxy 代理bean
        通过代理,将上面的DAO bean 纳入到spring容器的事务管理中,并在其中设置对哪些方法进行事务管理
     <bean id="loginBOProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
           <property name="transactionManager">
                <ref bean="transactionManager" />
           </property>
           <property name="target">
                <ref local="Ilogin" /> <!--所代理的bean-->
           </property>
           <property name="transactionAttributes">
                <props>
                     <prop key="insert*">PROPAGATION_REQUIRED</prop> <!--以insert开头的方法加入事务管理-->
                     <prop key="get*">PROPAGATION_REQUIRED,readOnly</prop> <!--以get开头的方法只读-->
                </props>
           </property>
      </bean>

    
    6.action bean
      <bean name="/loginAction" class="com.derek.action.LoginAction" singleton="false">
         <property name="login">
            <ref bean="loginBOProxy" /> <!--要将其使用的DAO bean加入事务管理,就必须ref他的代理bean,且在LoginAction中该属性须由其接口强制类型转换-->
         </property>
      </bean>

示例代码:
  struts-conifg.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 >

  
< form - beans >
    
< form - bean name = " loginActionForm "  type = " com.derek.form.LoginActionForm "   />
  
</ form - beans >
  
< action - mappings >
    
< action input = " /login.jsp "  name = " loginActionForm "  path = " /loginAction "  scope = " request "  type = " org.springframework.web.struts.DelegatingActionProxy "  validate = " false " >
      
< forward name = " success "  path = " /success.jsp "   />
      
< forward name = " failure "  path = " /failure.jsp "   />
    
</ action >
  
</ action - mappings >
  
< plug - in className = " org.springframework.web.struts.ContextLoaderPlugIn " >
    
< set - property property = " contextConfigLocation "  value = " /WEB-INF/applicationContext.xml "   />
  
</ plug - in >
</ struts - config >

  applicationContext.xml
<? xml version = " 1.0 "  encoding = " UTF-8 " ?>
<! DOCTYPE beans SYSTEM  " D:/JAVA/MyWork/SpringDemo/SpringWeb/WEB-INF/spring-beans.dtd " >
<!-- DOCTYPE beans PUBLIC  " -//SPRING//DTD BEAN//EN "   " http://www.springframework.org/dtd/spring-beans.dtd " -->

<!--
  
-  Root application context  for  the Countries application.
  
-  Web - specific beans are defined in  " countries-servlet.xml " .
  
-->
< beans >

< bean id = " dataSource "   class = " org.springframework.jdbc.datasource.DriverManagerDataSource " >
 
< property name = " driverClassName "  value = " net.sourceforge.jtds.jdbc.Driver " ></ property >
 
< property name = " url "  value = " jdbc:jtds:sqlserver://192.168.56.32:1433/testDB " ></ property >
 
< property name = " username "  value = " it " ></ property >
 
< property name = " password "  value = " itservice " ></ property >
</ bean >

< bean id = " sessionFactory "   class = " org.springframework.orm.hibernate3.LocalSessionFactoryBean " >
 
< property name = " dataSource "  ref = " dataSource " ></ property >
 
< property name = " mappingResources " >
  
< list >
    
< value > hbm/OvertimeRecord.hbm.xml </ value >
    
< value > hbm/OvertimePermit.hbm.xml </ value >
  
</ list >
 
</ property >
 
< property name = " hibernateProperties " >
  
< props >
     
< prop key = " hibernate.dialect " > org.hibernate.dialect.SQLServerDialect </ prop >
     
< prop key = " hibernate.show_sql " > true </ prop >
     
< prop key = " hibernate.jdbc.fetch_size " > 50 </ prop >
     
< prop key = " hibernate.jdbc.batch_size " > 20 </ prop >
  
</ props >
 
</ property >
</ bean >

< bean id = " transactionManager "   class = " org.springframework.orm.hibernate3.HibernateTransactionManager " >
   
< property name = " sessionFactory " >
       
< ref local = " sessionFactory "   />
   
</ property >
</ bean >


<!---------------使用JNDI数据源----------------
bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
  <value>jdbc/cqccms</value>
</property>
<property name="jndiEnvironment">
     <props>
        <prop key="java.naming.factory.initial">
          weblogic.jndi.WLInitialContextFactory
        </prop>
        <prop key="java.naming.provider.url">t3://172.16.101.42:7001</prop>
        <prop key="java.naming.security.principal">weblogic</prop>
        <prop key="java.naming.security.credentials">weblogic</prop>
     </props>   
   </property> 
</bean>

<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate" singleton="true"
  lazy-init="default" autowire="default" dependency-check="default">
  <property name="environment">
     <props>
        <prop key="java.naming.factory.initial">
          weblogic.jndi.WLInitialContextFactory
        </prop>
        <prop key="java.naming.provider.url">t3://172.16.101.42:7001</prop>
        <prop key="java.naming.security.principal">weblogic</prop>
        <prop key="java.naming.security.credentials">weblogic</prop>
     </props>   
   </property>
</bean>

<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" singleton="true"
  lazy-init="default" autowire="default" dependency-check="default">
  <property name="jndiTemplate">
   <ref local="jndiTemplate" />
  </property>
  <property name="userTransactionName">
   <value>weblogic/transaction/UserTransaction</value>
  </property>
</bean>

--------------------------------->



< bean id = " RecordDao "   class = " com.derek.business.RecordDao " >
  
< property name = " sessionFactory " >
    
< ref local = " sessionFactory " />
  
</ property >
</ bean >

< bean id = " RecordDaoProxy "   class = " org.springframework.transaction.interceptor.TransactionProxyFactoryBean " >
  
< property name = " transactionManager " >
    
< ref bean = " transactionManager "   />
  
</ property >
  
< property name = " target " >
    
< ref local = " RecordDao "   />
  
</ property >
  
< property name = " transactionAttributes " >
    
< props >
      
< prop key = " insert* " > PROPAGATION_REQUIRED </ prop >
      
< prop key = " get* " > PROPAGATION_REQUIRED,readOnly </ prop >
    
</ props >
  
</ property >
</ bean >

< bean id = " Ilogin "   class = " com.derek.business.Login " >
  
< property name = " sessionFactory " >
    
< ref local = " sessionFactory " />
  
</ property >
</ bean >

< bean id = " loginBOProxy "   class = " org.springframework.transaction.interceptor.TransactionProxyFactoryBean " >
  
< property name = " transactionManager " >
    
< ref bean = " transactionManager "   />
  
</ property >
  
<property name="target">
    
<ref local="Ilogin" />
  
</property>
  
< property name = " transactionAttributes " >
    
< props >
      
< prop key = " insert* " > PROPAGATION_REQUIRED </ prop >
      
< prop key = " get* " > PROPAGATION_REQUIRED,readOnly </ prop >
    
</ props >
  
</ property >
</ bean >

< bean name = " /loginAction "   class = " com.derek.action.LoginAction "  singleton = " false " >
  
< property name = " login " >
    
< ref bean = " loginBOProxy "   />
  
</ property >
</ bean >
</ beans >

LoginInterface
package  com.derek.myinterface;

public   interface  LoginInterface {
    
public   boolean  check(String name,String pwd);
}

Login
package  com.derek.business;

import  com.derek.myinterface.LoginInterface;
import  org.hibernate.SessionFactory;
import  org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import  java.util.List;

public   class  Login  extends  HibernateDaoSupport  implements  LoginInterface{
    
private  SessionFactory sessionFactory;
    
private  String hsql  =   " from OvertimePermit where account=? and password=? " ;
    
public  Login() {}
    
public   boolean  check(String name,String pwd){
        String condition[] 
=  {name, pwd}; // 查询条件
         /**
         * 借助HibernateTemplate我们可以脱离每次数据操作必须首先
         * 获得Session实例 、启动事务、提交/回滚事务以及烦杂的try/catch/finally的繁琐操作
         
*/        
        List l 
=   this .getHibernateTemplate().find(hsql, condition);
        
        
if  (l.size()  >   0 return   true ;
          
else   return   false ;
    }
}

RecordDaoInterface
package  com.derek.myinterface;

import  java.util.List;
import  hbm.OvertimeRecord;

public   interface  IRecordDao {
    
public  List findAll(String hsql);
    
public   void  insert(OvertimeRecord or);
}

RecordDao
package  com.derek.business;

import  com.derek.myinterface.IRecordDao;
import  java.util.List;
import  org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import  org.hibernate.SessionFactory;
import  hbm.OvertimeRecord;

public   class  RecordDao  extends  HibernateDaoSupport  implements  IRecordDao{
    
private  SessionFactory sessionFactory;
    
public  RecordDao() {
    }

    
public  List findAll(String hsql) {
       
return   this .getHibernateTemplate().find(hsql);
    }

    
public   void  insert(OvertimeRecord or) {
        
this .getHibernateTemplate().saveOrUpdate(or);
    }
}

LoginAction通过容器注入的Login实例完成业务操作(必须由接口强制类型转化)
package  com.derek.action;

import  javax.servlet.http. * ;
import  com.derek.form. * ;
import  org.apache.struts.action. * ;
import  org.apache.log4j.Logger;
import  com.derek.myinterface.LoginInterface;

public   class  LoginAction  extends  Action {
    
private  LoginInterface login;
    
public  ActionForward execute(ActionMapping actionMapping,
                                 ActionForm actionForm,
                                 HttpServletRequest servletRequest,
                                 HttpServletResponse servletResponse) {
        Logger log 
=  Logger.getLogger( this .getClass().getName());
        LoginActionForm loginActionForm 
=  (LoginActionForm) actionForm;
        String name 
=  loginActionForm.getName();
        String pwd 
=  loginActionForm.getPwd();
        
boolean  TF  =  login.check(name,pwd);
        
if (TF){ log.warn( " LoginSuccess------------ " );; return  actionMapping.findForward( " success " );}
          
else { log.warn( " LoginFailure------------ " );; return  actionMapping.findForward( " failure " );}
    }
    
public   void  setLogin(LoginInterface Ilogin) { this .login  =  Ilogin;}
    
public  LoginInterface getLogin() { return  login;}
}

类中直接通过Context获得bean实例(必须通过代理类获得实例且由其接口强制类型转化)

package  com.derek.pub;

import  org.springframework.context.ApplicationContext;
import  org.springframework.context.support.FileSystemXmlApplicationContext;
import  com.derek.myinterface.IRecordDao;
import  java.util.List;
import  hbm.OvertimeRecord;

public   class  Untitled1 {
    
public  Untitled1() {
    ApplicationContext ctx 
=   new  FileSystemXmlApplicationContext( " applicationContext.xml " );
    IRecordDao recordDao 
=  (IRecordDao)ctx.getBean( " RecordDaoProxy " );
    OvertimeRecord newor 
=   new  OvertimeRecord( " 004104 " , "dada " , "1 00120 " , "it " , " 2006/04/02 " , " 2006/04/02 " , " 001145 " , "david " , " 001145 " , "david " , " 00 " , " 00 " , " 1 " , " 1 " , " 1 " , " 1 " );
    newor.setMark(
" 0 " );
    recordDao.insert(newor);
    List l 
=  recordDao.findAll( " from OvertimeRecord " );
    
for ( int  i = 0 ;i < l.size();i ++ ){
    OvertimeRecord or 
=  (OvertimeRecord)l.get(i);
    System.out.println(or.getId());
    }
    }
    
public   static   void  main(String[] a){
    Untitled1 u 
=   new  Untitled1();
    }
}

      一个Spring application context的定义能够被很多种不同的上下文实现所读取, 比如FileSystemXmlApplicationContextClassPathXmlApplicationContext以及XmlWebApplicationContext。 默认的情况下,一个web应用程序会从”WEB-INF/applicationContext.xml”中得到root context。 在所有的Spring应用中,XML文件中定义的application context会把所有相关的application beans连接起来, 包括Hibernate session factory以及数据访问和业务对象(就像上面定义的那些bean)。 它们中的大部分都不会意识到被Spring容器所管理,甚至在同其他bean合作的时候, 因为它们仅仅遵循JavaBeans的规范。一个bean属性及可以表示值参数,也可以是其他的合作bean。 下面的bean定义能够作为Spring web MVC context的一部分,在最基础的 application context中访问business beans。

ApplicationContext context  =  WebApplicationContextUtils.getWebApplicationContext(servletContext);
ProductService productService 
=  (ProductService) context.getBean( " myProductService " );
ApplicationContext context 
=
    
new  FileSystemXmlApplicationContext( " C:/myContext.xml " );
ProductService productService 
=
    (ProductService) context.getBean(
" myProductService " );
ApplicationContext context 
=
    
new  ClassPathXmlApplicationContext( " myContext.xml " );
ProductService productService 
=
    (ProductService) context.getBean(
" myProductService " );
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值