posts - 0,  comments - 1,  trackbacks - 0
    ===============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() > 0return 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","100120","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");

Feedback

# re: Spring+Hibernate+Struts  回复  更多评论   

2006-07-24 21:56 by han
你好!
我在调试过程中遇到下面的问题,请指教

# re: Spring+Hibernate+Struts  回复  更多评论   

2006-07-24 21:57 by han
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/appcontext.xml]: Initialization of bean failed; nested exception is net.sf.hibernate.MappingException: org.dom4j.DocumentException: null Nested exception: null
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:403)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:233)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:145)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:277)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:313)
org.springframework.web.context.support.AbstractRefreshableWebApplicationContext.refresh(AbstractRefreshableWebApplicationContext.java:139)
org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:252)
org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:190)
org.springframework.web.context.ContextLoaderServlet.init(ContextLoaderServlet.java:83)
javax.servlet.GenericServlet.init(GenericServlet.java:211)
org.apache.catalina.startup.Catalina.start(Catalina.java:556)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
java.lang.reflect.Method.invoke(Method.java:324)
org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:287)
org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:425)

# re: Spring+Hibernate+Struts  回复  更多评论   

2006-07-24 22:01 by han
web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"">http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/appcontext.xml</param-value>
</context-param>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>

<servlet>
<servlet-name>SpringContextServlet</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>

</web-app>

# re: Spring+Hibernate+Struts  回复  更多评论   

2006-07-24 22:01 by han

appcontext.xml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
"http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://localhost:3306/test</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>1</value>
</property>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource"/>
</property>
<property name="mappingResources">
<list>
<value>person/Info.hbm.xml</value>

</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">net.sf.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>

<bean id="myTransactionManager" class="org.springframework.orm.hibernate.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
<bean id="personService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="transactionManager">
<ref local="myTransactionManager"/>
</property>
<property name="target">
<ref local="personServiceImp"/>
</property>
<property name="transactionAttributes">
<props>
<prop key="get*">PROPAGATION_REQUIRED</prop>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="update">PROPAGATION_REQUIRED</prop>
<prop key="delete">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>



<bean id="personDao" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="proxyInterfaces">
<value>person.PersonDao</value>
</property>
<property name="interceptorNames">
<list>
<value>hibernateInterceptor</value>
<value>personDaoTarget</value>
</list>
</property>
</bean>

<bean id="hibernateInterceptor" class="org.springframework.orm.hibernate.HibernateInterceptor">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>



<bean id="personServiceImp" class="person.PersonServiceImp">
<property name="person">
<ref local="personDao"/>
</property>
</bean>
<bean id="personDaoTarget" class="person.PersonDaoImp">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>

</beans>
posted on 2008-03-27 17:39 火焰出林 阅读(786) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航:
 
<2024年11月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
1234567

留言簿(1)

随笔分类

文章分类(25)

文章档案(23)

新闻档案(8)

相册

最新随笔

搜索

  •  

最新评论