一、整合原理:
(一)web.xml
(1)spring容器是以监听器的形式与Tomcat整合的
<listener>
<listenerclass>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext.xml</param-value>
</context-param>
主要实现功能的方法和语句:
publicvoid contextInitialized(ServletContextEvent event){
this.contextLoader=createContextLoader();
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
其中createContextLoader()方法加载spring的web容器,而
initWebApplicationContext()则初始化spring的web容器,并加载其配置文件。加载完这两个方法后,spring的web容器就启动了,在spring容器中的单例模式下的bean就被实例化了,也就是说dao层和service层的对象和代理对象就在这时候形成。
(2)以过滤器的形式整合Struts2容器
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
启动Tomcat时:
publicclass StrutsPrepareAndExecuteFilter{
public void init(FilterConfig filterConfig){
//获取初始化的各种配置文件
/*default.properties文件
Struts-default.xml
Struts-plugin.xml
Struts.xml*/
Dispatcher dispatcher =init,initDispatcher(config);
//静态注入,初始化配置文件中的bean
Init.initStaticContentLoader(config,dispatcher);
}
}
二、附加
(一)请求URL:personAction_savePerson.action
(1)步骤:
1.先找Struts的配置文件,然后根据struts2的相关配置查找action的创建方式
2.然后从struts.objectFactory中查找到底是由哪个类创建了action
3.然后会去struts-default.xml,struts-plugin.xml,struts.xml文件中查找struts.objectFactory(哪个配置文件加载在最后,哪个决定)
4.最后在struts和spring整合的包中找到了struts-plugin.xml文件
<beantype="com.opensymphony.xwork2.ObjectFactory" name="spring"class="org.apache.struts2.spring.StrutsSpringObjectFactory" />
<constantname="struts.objectFactory" value="spring" />
5.最终得知action是由StrutsSpringObjectFactory创建的,该类继承了其父类SpringObjectFactory。
(二)、S2SH整合框架后,spring管理事务
(1)事务的范围影响session的生命周期:
如果当前执行的方法没有事务,这调用完this.getHibernateTemplate方法后,session立即关闭;
当当前执行的方法有事务,这调用完该方法后,session再关闭
(2)在web.xml文件中,做OpenSessionInView的配置操作:
在提交一个请求时,OpenSessionInview已经打开了session,在response后再关闭session。即将session提前开启,延后关闭,解决了懒加载的异常。
缺点:因为session被延迟关闭,而Hibernate的一级缓存在session中,这就会产生大量的缓存数据被长时间停留在内存(需要定期手动清理缓存)。