Struts2+Hibernate+Spring整合过程

来源:互联网 发布:双色球数据分布图 编辑:程序博客网 时间:2024/06/07 17:41

学习了这么久框架,很长时间没有总结一下这个过程了,有的时候会忘记一些内容,所以还是写一下,加深一下记忆:

SSH整合的步骤:(很大的前提就是整合好jar包放在lib目录里卖弄)

第一步:Struts2框架跟Spring框架整合

1.1配置web.xml文件

(1)添加监听器标签(当启动服务器的时候加载applicationContext.xml文件)

<listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <context-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:applicationContext.xml</param-value>    </context-param>

(2)添加过滤器标签

<filter>    <filter-name>struts2</filter-name>    <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  </filter>  <filter-mapping>    <filter-name>struts2</filter-name>    <url-pattern>*.action</url-pattern>
1.2引入struts.xml核心文件,并且配置该文件

要配置的东西跟之前的一样,但是<action class="在spring框架ApplicationContext.xml文件中注册过的类名(id的值),该类必须要标明周期Scope="prototype"">

这样就整合好Struts框架跟spring框架了

第二步:整合hibernate跟spring框架

为了降低hibernate框架跟spring框架的耦合度,我们保留hibernate.cfg.xml文件,只是把数据源及C3P0连接池的配置交给了Spring。

所以配置hibernate框架跟spring框架其实就是配置applicationContext.xml文件。

1.配置数据库连接(c3po也一样)

1.1首先我们为了兼容不同数据库,所以我们先建立jdbc.properties属性文件

jdbc.driver = com.mysql.jdbc.Driverjdbc.url = jdbc:mysql://localhost:3306/student?useUnicode=true&characterEncoding=utf8jdbc.username =rootjdbc.password = root

然后配置数据源dataSourse

<!-- 引入c3p0连接池配置 --><context:property-placeholder location="classpath:jdbc.properties"/><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="driverClass" value="${jdbc.driver}"></property><property name="jdbcurl" value="${jdbc.url}"></property><property name="jdbcuser" value="${jdbc.username}"></property><property name="jdbcpwd" value="${jdbc.password}"></property></bean>
c3p0的有空可以写进属性文件,然后参照jdbc的方式

2.我们要在applictionContext.xml文件注入spring框架支持hibernate框架的SessionFactiory,把数据源作为属性提供给sessionFactory操作,并把hibernate.cfg.xml文件和*.hbn.xml文件关联进去,也是作为属性;

<!-- 注入spring framework 提供的sessionFactory --><bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"><!-- 注入数据库配置 --><property name="dataSource" ref="dataSource"></property><!-- 导入hibernate框架基础配置 --><property name="configLacation" value="classpath:hibernate.cfg.xml"></property><!-- 导入类的实体映射文件 --><property name="mappingLocations" value="classpath:com/zqu/student/pojo/*.hbm.xml"></property></bean>
这样我们就把hibernate跟spring框架整合好了

第三步:配置注解的声明式事务(@Transaction),因为sessionFactory的Session session需要封装事务,所以要把sessionFactory作为一个属性,从而启动事务管理器

<!-- 使用spring框架为hibernate提供的事务管理器 --><bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"><property name="sessionFactory" ref="sessionFactory"></property></bean><!-- 使用spring框架提供的事务注解@Transactional--><tx:annotation-driven transaction-manager="transactionManager"/>

这样就完成了SSH框架的整合,下面就享受spring框架带来的乐趣吧。



0 0
原创粉丝点击