服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

浅谈struts+hibernate+spring的整合方法

1、在工程中导入spring支持,导入的jar包有:

◆ spring 2.0 core libraries

◆spring 2.0 orm/dao/hibernate3 libraries

◆ spring 2.0 aop libraries

◆ spring 2.0 web libraries

2、在spring配置文件中配置datasource和sessionfactory,将hibernate配置与spring配置整合在一起(可以删除hibernate.cfg.xml文件);

3、导入数据库源所要使用的jar包,如:dbcp所用的jar包(commons-pool.jar);

4、修改所有dao的hibernate实现,因为spring中提供了一个hibernatedaosupport类,可以简化数据库的操作。使用所有dao类都继承自该类;

5、将dao采用依赖注入的方式注入到biz中,再将biz采用依赖注入的方式注入到action中,在spring配置文件中做相应配置;

6、将spring与struts集成:

1)在spring配置文件配置action:将biz注入到action中;

2)修改struts的配置文件:将action的type属性修改为:org.springframework.web.struts.delegatingactionproxy;

3)在web.xml文件中配置监听器以及web应用的初始化参数:

contextconfiglocation /web-inf/applicationcontext.xml
  /web-inf/applicationcontext-beans.xml
  org.springframework.web.context.contextloaderlistener

7、为了解决应用中的中文乱码问题,我们可以不用自己开发过滤器类,spring为我们提供了一个,只需要配置一下即可:

characterencodingfilter
org.springframework.web.filter.charact
[color=brown][/color]erencodingfilter
encoding
utf-8
characterencodingfilter
/*

8、为了解决hibernate延迟加载的问题,使用spring中提供的过滤器来解决,它能够让session

在请求解释完成之后再关闭,配置方式如下:

hibernate session manager filter 
org.springframework.orm.hibernate3.support.
opensessioninviewfilter
hibernate session manager filter /*

9、因为opensessioninviewfilter在getsession的时候,会把获取回来的session的flush mode 设为flushmode.never。故进行insert、 update和delete操作时会产生异常:org.springframework.dao.invaliddataaccessapiusageexception: write operations are not allowed in read-only mode (flushmode.never/manual): turn your session into flushmode.commit/auto or remove 'readonly' marker from transaction definition. 因此需要采用spring的事务声明,使方法受transaction控制:

<!-- 配置事务管理器 -->
<bean id="transactionmanager" class="
org.springframework.orm.hibernate3.hibernatetransactionmanager">
<property name="sessionfactory" ref="sessionfactory" />
</bean>
<!-- 配置advice(事务的传播特性) -->
<tx:advice id="
txadvice" transaction-manager="transactionmanager">
<tx:attributes>
<tx:method name="add*" propagation="required"/>
<tx:method name="del*" propagation="required"/>
<tx:method name="update*" propagation="required"/>
<tx:method name="get*" propagation="supports" read-only="true"/>
<tx:method name="
search*" propagation="supports" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置事务管理器应用的范围 -->
<aop:config>
<aop:pointcut id="affectmethods" expression="
execution(* edu.accp.dao.hibimpl.*.*(..))"/>
<aop:advisor advice-ref="txadvice" pointcut-ref="affectmethods"/>
</aop:config>

10、 部署应用程序,启动服务器,如果发现异常: java.lang.nosuchmethoderror: org.objectweb.asm.classvisitor.visit(iiljava/lang/string;ljava/lang/string;[ljava/lang/string;ljava/lang/string;)v 这是由于整合时jar包的冲突引起的。应将"web应用程序/web-inf/lib/asm-2.2.3.jar"删除即可。

扫描关注微信公众号