搭建SSH环境(Struts-2.3.4.1 Spring 4.3.6 Spring 5.2.6)
导入必要的jar包。在Spring的配置文件中,定义数据源
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<!-- 指定数据库驱动 -->
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<!-- 指定连接数据库的URL -->
<property name="url" value="jdbc:mysql://localhost:3306/TwoGou"></property>
<!-- 指定数据库连接的用户名 -->
<property name="username" value=" " />
<!-- 指定数据库连接的密码 -->
<property name="password" value=" " />
</bean>
定义hibernate的sessionFactory
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<!-- 依赖注入已配置好的 dataSource -->
<property name="dataSource">
<ref local="dataSource"/>
</property>
<!-- 指定Hibernate所有映射文件的路径 -->
<!-- <property name="mappingResources">
<list>
<value></value>
</list>
</property> -->
<!-- 设置Hibernate的属性 -->
<property name="hibernateProperties">
<props>
<!-- 设置Hibernate的数据库方言 -->
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<!-- 指定是否在控制台输出由hibernate生成的SQL语句 -->
<prop key="show_sql">true</prop>
</props>
</property>
</bean>
在struts.xml中将Struts 2默认的objectFactory设置为spring
<constant name="struts.objectFactory" value="spring"></constant>
在web.xml文件中装载Spring的上下文,以保证Spring随着web应用的启动而启动,有两种装载方式:
①使用ServletContextListener配置
<!-- 装载spring时加载的文件路径 默认是加载WEB-INF/路径下的applicationContext.xml-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value> /WEB-INF/classes/applicationContext.xml</param-value>
</context-param>
<!-- Spring的上下文装载 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
②使用load-on-startup Servlet的配置
<servlet>
<!-- 配置ContextLoaderServlet -->
<servlet-name>SpringContextServlet</servlet-name>
<servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
在web.xml中配置Struts2
<filter>
<!-- 指定核心Filter的名字 -->
<filter-name>struts2</filter-name>
<!-- 指定核心Filter的实现类 -->
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<!-- 配置Filter拦截的URL -->
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
hibernate.cfg.xml(配置数据源和映射文件)文件就不再使用了。
Spring集成Hibernate是在applicationContext.xml中配置dataSource和sessionFactory。
Spring集成Struts,首先需要导入struts2-spring-plugin-2.3.4.1.jar插件包(覆盖Struts 2中的objectFactory来增强其核心框架中对象的创建),插件先使用Struts2中的配置文件中的class属性与Spring配置文件中的id属性进行关联,如果能找到对应的关系则由Spring负责创建对象,否则仍由Struts 2框架自身负责创建对象,创建后再由Spring进行装配。
整体的配置已经完毕。