现在的位置: 首页 > 综合 > 正文

Spring整合web应用和整合Struts1.x

2018年05月28日 ⁄ 综合 ⁄ 共 2429字 ⁄ 字号 评论关闭

一、Spring整合Web应用

 1. 在Web应用程序中,要使用Spring的IoC容器(WebApplicationContext),必须对它进行初始化。Spring提供了两种方式:
  1) ContextLoadListener : 在容器部署这个Web应用时就会触发这个监听器,这个监听器就会创建并初始化Spring的WebApplicationContext实例。具体配置如下(推荐使用)
      a) 在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>
      b) 在web.xml中配置ContextLoadListener监听器
<listener>
  <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

  2) ContextLoadServlet : 这个Servlet在初始化阶段也会创建并初始化Spring的WebApplicationContext实例。需要把它配置为自启动方式。如下配置:
     a) 在web.xml中通过应用上下文初始化参数来指定Spring的配置文件的路径,同上a) 所示的配置。
     b) 在web.xml中注册此Servlet:
<servlet>
    <servlet-name>ContextLoadServlet<servlet-name>
    <servlet-class>org.springframework.web.context.ContextLoaderServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

 2. 经过以上配置后,在Servlet或JSP中,直接使用Spring提供的WebApplicationContextUtils工具类就可以获取Spring的WebApplicationContext容器了,然后就可以从该容器中获取你想要的Bean了。

 

二、Spring整合Struts1:  

 1. 注意:Spring2.5以上版本整合Struts1.x时,需要在classpath中添加spring-webmvc-struts.jar包。

 

 2. Spring有侵入性的整合Struts1: 
    Action类可以直接继承Spring提供的ActionSupport(或它的子类),这些类都提供了getApplicationContext()的方法来获取Spring的WebApplicationContext容器。

 

 3. Spring无侵入性的整合Struts1:  强烈推荐使用
   1) 在Struts配置文件中把默认的请求处理器换成Spring提供的DelegatingRequestProcessor这个请求处理器。具体配置如下:
       <controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"/>
       
   2) 在Struts配置文件中配置的每个Action,都要对应的在Spring的配置文件中进行相应的配置。
     例如:struts配置文件有:
    <action path="/dept" type="com.qiujy.web.dept.DeptAction"
                 name="deptForm" scope="request"
                 parameter="method" validate="false">
      <forward name="findAll" path="/list_dept.jsp"/>
    </action>
    那么在Spring配置文件中要有如下相应配置:<bean name="/dept" class="com.qiujy.web.dept.DeptAction" parent="baseAction"/>
   这样,客户提交的Struts请求就会映射到Spring容器创建的针对对应Action实例的代理对象上。Spring就可以对这些代理对象直接注入依赖。从而实现表示层和业务层依赖关系的松藕合。

 

三、Spring针对Hibernate还提供了org.springframework.orm.hibernate3.support.OpenSessionInViewFilter类,可以直接配置在web.xml中。用来在请求到达服务器资源时就开启session,在响应返回客户端之前关闭Session,以便于在JSP页面中仍可以初始化实体对象中延迟加载的属性。(效率问题,要谨慎使用)

 

四、Spring针对Web应用添加了一个请求数据编码设置的过滤器org.springframework.web.filter.CharacterEncodingFilter,可直接在web.xml中配置生效。

 

五、Spring应用的流行架构:
       struts1 + spring2 + hibernate3集成开发 (ssh)
       struts2 + spring2 + hibernate3集成开发(s2sh)

抱歉!评论已关闭.