导入依赖包:
除了导入Struts2和Spring的核心库之外,还要导入commons-logging和struts2-spring-plugin包。(PS:Struts2是主导,把spring嵌到struts2中。)
配置:
通过配置ContextLoaderListener监听器,使容器启动时,自动加载applicationContext配置,因为它实现了ServletContextListener这个接口,容器启动时会自动执行它实现的方法。
默认情况下,会加载WEB-INF/applicationContext.xml这个文件,我们可以通过配置contextConfigLocation参数改变配置文件的路径。
以上配置均在web.xml文件的<web-app></web-app>区域。
Spring和Struts2的整合:
在web.xml中完成加载WebApplicationContext之后,接下来就可以做到Spring和Struts2的整合了。整合有两种方法,分别叙述如下:
第一种实现方法–把Action配置在beans.xml里,利用Spring初始化Action的bean:
1) 将Struts的业务逻辑控制器类(action)配置在Spring的配置文件中(由spring容器负责生成action),业务逻辑控制器中引用的业务类一并注入。注意,必须将业务逻辑控制器类配置为scope=”prototype”!
示例如下:
2) 在struts.xml或者等效的Struts2配置文件中配置Action时,指定<action>的class属性为Spring配置文件中相应bean的id或者name值。
示例如下:
第二种实现方法–不需要在beans.xml里配置Action,利用Struts-Spring_Plugin插件自动初始化Action:
1) 业务类在Spring配置文件中配置,业务逻辑控制器类(action)不需要配置,Struts2的Action像没有整合Spring之前一样配置,<action>的class属性指定业务逻辑控制器类的全限定名。
2) 业务逻辑控制器类中引用的业务类不需要自己去初始化,Struts2的Spring插件会使用bean的自动装配将业务类注入进来,其实业务逻辑控制器类也不是Struts2创建的,而是Struts2的Spring插件创建的。默认情况下,插件使用by name的方式装配,可以通过增加Struts2常量来修改匹配方式:设置方式为:struts.objectFactory.spring.autoWire = typeName,可选的装配参数如下:
- a) name:等价于Spring配置中的autowire=”byName”,这是缺省值。
- b) type:等价于Spring配置中的autowire=”byType”。
- c) auto:等价于Spring配置中的autowire=”autodetect”。
- d) constructor:等价于Spring配置中的autowire=” constructor”。
简述OpenSessionInViewFilter:
OpenSessionInViewFilter是Spring提供的一个针对Hibernate的一个支持类,其主要意思是在发起一个页面请求时打开Hibernate的Session,一直保持这个Session,直到这个请求结束,具体是通过一个Filter来实现的。 由于Hibernate引入了Lazy Load特性,使得脱离Hibernate的Session周期的对象如果再想通过getter方法取到其关联对象的值,Hibernate会抛出一个LazyLoad的Exception。所以为了解决这个问题,Spring引入了这个Filter,使得Hibernate的Session的生命周期变长。
配置:
PS:因为是过滤器,一定要注意它的位置,要将它放在配置struts2的前面。
我的第一个SSH示例:
web.xml
beans.xml
struts2.xml
action:
Java
PS:DAO层,业务层之前博客有,在此不在缀余,业务层没写什么内容也就不粘了。