Spring整合web应用和整合Struts1.x(转)

一、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)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值