Struts2+Spring+Hibernate 三大框架的合并集成

来源:互联网 发布:野生动植物数量 数据 编辑:程序博客网 时间:2024/05/22 03:50
这次来看看Struts2+spring+hibernate三大框架的整合应用,主要是SpringHibernate框架的整合,因为前边已经将Strtus2+Spring整合过了基本一样。


        首先看一下分工吧:

           Struts2做的MVC的流程框架,主要完成从客户端访问到选择anction的过程,其中过滤器起到了Controller的作用,action属于model,而jsp则是view页面的展示。


          Spring主要利用Ioc的特长来管理各种对象:action,service,dao,数据访问源,Hibernate的核心对象SessionFactory等,还有就是声明式事务的管理等。


         Hibernate框架主要是实体层和数据库中表的映射,以及封装JDBC代码,提供相应的方法,供我们选择。这样从前台页面一直到后台数据库,都有了框架帮我们维护,使我们的开发变得简单快捷,效率大大提高。当然了,前提是我们对这些框架能够灵活的运用。

 

        再者,就是需要三大框架的导入的对应jar包,这里不再列出。以及对应的配置文件,这里需要说明一下,由于Hibernate框架的核心对象SessionFactory交给了Spring框架进行维护,这里就不需要hibernate.cfg.xml配置文件了,我们将这些信息写到Spring核心配置文件中即可。

 

         好,看一下各个配置文件的编写吧!


          1web.xml文件的几个重点项:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <!-- 用于指定Spring的配置文件路径 -->  
  2. <context-param>  
  3.     <param-name>contextConfigLocation</param-name>  
  4.     <param-value>classpath:applicationContext.xml</param-value>  
  5. </context-param>  
  6.   
  7. <!-- 服务器启动时,通过监听器初始化Spring的配置环境   
  8.     监听器,默认加载文件是:/WEB-INF/applicationContext.xml  
  9. -->  
  10. <listener>  
  11.     <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  12. </listener>  
  13.   
  14.   
  15. <!-- OpenSessionInViewFilter过滤器需要配置在Struts2框架过滤器前面,否则不起作用。 -->  
  16. <filter>  
  17.     <filter-name>OpenSessionInViewFilter</filter-name>  
  18.     <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>  
  19. </filter>  
  20. <filter-mapping>  
  21.     <filter-name>OpenSessionInViewFilter</filter-name>  
  22.     <url-pattern>/*</url-pattern>  
  23. </filter-mapping>  
  24.   
  25. <!-- 配置框架的核心调度器 -->  
  26. <filter>  
  27.     <filter-name>struts2</filter-name>  
  28.     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>  
  29. </filter>  
  30. <filter-mapping>  
  31.     <filter-name>struts2</filter-name>  
  32.     <url-pattern>/*</url-pattern>  
  33. </filter-mapping>  


     2Struts2核心配置文件的编写:


[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <package name="example" namespace="/user" extends="struts-default">  
  2.        <action name="login" class="loginAction" method="login">  
  3.            <result name="success" type="dispatcher">/success.jsp</result>  
  4.            <result name="login" type="redirect">/login.jsp</result>  
  5.        </action>  
  6.    </package>  



       3Spring核心配置文件的编写:

[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  3.         xmlns:aop="http://www.springframework.org/schema/aop"  
  4.         xmlns:tx="http://www.springframework.org/schema/tx"  
  5.         xsi:schemaLocation="  
  6.             http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd  
  7.             http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd  
  8.             http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"  
  9.             default-autowire="byName">  
  10.               
  11.     <!-- 启用AOP功能 -->        
  12.     <aop:aspectj-autoproxy></aop:aspectj-autoproxy>       
  13.     <!-- action,service和dao层配置,这里使用了默认装配功能 -->  
  14.     <bean id="loginAction" class="com.ljh.egov.action.LoginAction" scope="prototype"></bean>  
  15.   
  16.     <bean id="userService" class="com.ljh.egov.service.UserService" ></bean>  
  17.       
  18.     <bean id="userDao" class="com.ljh.egov.dao.UserDao">  
  19.         <property name="sessionFactory" ref="sessionFactory"></property>  
  20.     </bean>  
  21.   
  22.     <!--加载数据库的配置文件  -->  
  23.     <bean class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">  
  24.         <property name="locations">  
  25.             <list>  
  26.                 <value>classpath:db.properties</value>  
  27.             </list>  
  28.         </property>  
  29.     </bean>  
  30.       
  31.     <!-- c3p0数据源的配置,这里也可以设置连接池的大小等等 -->  
  32.     <bean id="c3p0" class="com.mchange.v2.c3p0.ComboPooledDataSource">  
  33.         <property name="user" value="${username}"></property>  
  34.         <property name="password" value="${password}"></property>  
  35.         <property name="jdbcUrl" value="${url}"></property>  
  36.         <property name="driverClass" value="${driverClass}"></property>   
  37.     </bean>  
  38.   
  39.     <!-- sessionFactory的管理,里边通过各种标签进行管理 -->  
  40.     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >  
  41.         <property name="dataSource" ref="c3p0"></property>  
  42.         <property name="hibernateProperties">  
  43.             <props>  
  44.                 <!-- 打印sql语句 -->  
  45.                 <prop key="hibernate.show_sql">true</prop>  
  46.                 <!-- 格式化sql语句 -->  
  47.                 <prop key="hibernate.format_sql">true</prop>  
  48.                 <!-- 当构建SessionFactory对象时,通过映射文件自动创建表 -->  
  49.                 <prop key="hibernate.hbm2ddl.auto">update</prop>  
  50.                 <!-- 数据库方言 -->  
  51.                 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>  
  52.             </props>  
  53.         </property>  
  54.         <!-- 映射文件的包路径 -->  
  55.         <property name="mappingDirectoryLocations">  
  56.             <list>  
  57.                 <value>classpath:com/ljh/egov/bean</value>  
  58.             </list>  
  59.         </property>  
  60.     </bean>  
  61.   
  62.     <!-- 配置功能扩展对象 - 事务管理 -->  
  63.     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  64.         <property name="dataSource" ref="c3p0"></property>  
  65.     </bean>  
  66.       
  67.     <!-- 声明事务管理AOP功能 -->  
  68.     <aop:config>  
  69.         <aop:advisor advice-ref="transactionAdvice" pointcut="execution(* com.ljh.egov..service.*.*(..))"/>     
  70.     </aop:config>   
  71.       
  72.     <tx:advice id="transactionAdvice" transaction-manager="transactionManager">  
  73.         <tx:attributes>  
  74.             <tx:method name="save*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="java.lang.Exception"/>  
  75.             <tx:method name="delete*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="java.lang.Exception"/>  
  76.             <tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT" rollback-for="java.lang.Exception"/>  
  77.             <tx:method name="select*" read-only="true"/>  
  78.         </tx:attributes>  
  79.     </tx:advice>  
  80.   
  81. </beans>  



          4,在Dao层的编写中,这里简单说一下如何获得session对象,去进行相关方法的调用,完成我们的数据操作功能。Dao层首先需要实现我们的HibernateDaoSupport,以便使用此父类中的getHibernateTemplate方法,进行相关方法的调用,先看一个查询方法的实现:


[java] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1.    //参数需要final修饰        public User select(final User user) throws Exception {   
  2.     //HibernateTemplate模板类不能直接支持Query,Criteria接口操作,所以可以通过回调函数传递Session对象,来使用这两个接口。    
  3.     //当调用execute方法时,execute方法会回调参数对象的重写方法(doInHibernate).  
  4.     //这里的利用匿名内部类,充当了一个回调函数,就是为了使用类中的Session对象  
  5.     return (User)this.getHibernateTemplate().execute(new HibernateCallback(){  
  6.         //称之为回调函数,一般由框架负责调用执行。  
  7.         public Object doInHibernate(Session session) throws HibernateException,SQLException {  
  8.               
  9.          //在匿名内部类中引用方法的局部变量,必须是final修饰的。                  
  10.               
  11.             Query query = session.createQuery("from User u where u.usercode=? and u.userpswd=?");                 
  12.               
  13.             query.setParameter(0, user.getUsercode());  
  14.             query.setParameter(1, user.getUserpswd());  
  15.   
  16.             return query.uniqueResult();  
  17.         }             
  18.     });  
  19. }  



         对于其它配置文件,这里不再给出,和单自使用框架差不多!当然对于这些配置文件,我们也可以根据实际业务进行划分,是每一个配置文件的功能单一,容量不至于过大,方便我们的管理。

 

         最后简单说一下,三大框架应用中优化的考虑问题吧!


           Struts2

                    1,发布时需要关闭开发模式(DevMode

                    2,不使用用不到的拦截器,拦截器等各种组件越多,性能越低,奔着一个达到目标使用最少的原则,进行相关开发。

                    3,过滤器的过滤规则尽量不要使用/*,这里我们开发可以制定规则,将过滤器的过滤范围降低到最小,方便框架的快速过滤!


         Spring:

                   1,尽量不要采用自动装配,使用手动装配指明方向,框架能够更快的寻找到相关的类。

                   2,尽量使用延迟加载功能,这样可以减少和数据库的通信,提高性能。


         Hibernate:

                  1,所有框架使用较新的版本,可以提供更好的性能支持,毕竟什么东西都是向着更好的方向发展。但是也不要一味的追求最新,如果有bug或什么情况还是不好的,奔着一个在有把握的基础上寻求最新的原则。

                  2,使用合理的缓存策略,主要是二级缓存和查询缓存的选择使用,根据实际情况,合理使用。

                  3,尽量使用延迟加载功能。

                  4,推荐使用uuid的主键生成策略,移植性好,支持大数据量。

                  5,推荐使用乐观锁代替悲观锁。

 

        总而言之,合理使用框架中的一些功能,考虑全面,来提高使用框架的性能。

 

         当然,这里只是简单的框架搭建,还有很多功能,没有加入,需要我们根据实际的情况,不断的完善配置文件,使其的功能越来越强大,使我们的项目开发完全融入到框架中开发,那样我们才会得心应手。总而言之,需要我们多用,多观察,多总结,多反思……

阅读全文
0 0