spring4+hibernate4+struts2项目整合的步骤及注意事项

  首先,在整合框架之前,我们需要知道Spring框架在普通Java project和Web project中是略有不同的.

  这个不同地方就在于创建IOC容器实例的方式不同,在普通java工程中,可以在main方法中直接创建,可是web工程就不一样了,在Web项目工程中应该在服务器加载时就创建IOC容器.也就是说,我们需要web容器能自动加载applicationcontext.xml并初始化.最常用的一种方式,就是在web.xml中添加ContextLoaderListener监听器.

  先讲一下,在WEB环境下,使用Spring的注意事项:

    1. 注意一定要有这两个jar包,spring-web-4.2.5.RELEASE.jar和spring-webmvc-4.2.5.RELEASE.jar
    2. Spring的配置文件,和在普通java project的配置文件相同.
    3. 需要在web.xml中加入以下代码:
<!-- 配置Spring配置文件的名称和位置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
        <!--<param-value>/WEB-INF/applicationContext.xml</param-value>-->
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

  

  下面介绍ssh整合和步骤,这里只做简单介绍,详细的步骤,之前的博文中,已经做了详细的介绍.    

  首先我们选择先加入Spring,因为Spring需要管理另外两个框架.

  •   加入Spring
    1.     加入Spring的jar包
    2.     配置web.xml文件(代码见上面)
    3.     配置applicationContext.xml
  •   加入hibernate
    1.     加入hibernate的jar包
    2.     配置hibernate.cfg.xml文件(也可以省略这个配置文件,这里选择保留)
    3.     建立持久化类及对应hbm.xml文件
    4.     和spring进行整合

         (1) 加入c3p0和mysql的驱动(jar包),这里选择使用mysql数据库和c3p0数据库池

              在spring中配置,数据源,sessionFactory,声明式事务.

         (2)   启动项目,检查自动生成的表结构

  •   加入struts2(注意额外需要一个struts2-spring-plugin-2.3.16.1.jar,若有重复的jar包,javasist.jar,则删除版本较低的那个jar包)
    1.      导入struts2的jar包
    2.      web.xml中配置struts的filter
    3.      创建struts2的配置文件struts.xml

   注意:

      在applicationContext.xml中配置Action的bean时,要将scrope设置为prototype,即每次都创建一个新的实例.

      在struts.xml中配置Action的class需要指向IOC容器中该Bean的id(以前class的值是该bean的全类名)

原文地址:https://www.cnblogs.com/fingerboy/p/5289495.html