struts2使用spring实现IOC时的配置和要注意到问题

在struts2中,通过spring来实现其IOC有很多的文章都有介绍,本文将总结一下其配置过程。此外,对几个很多文章都没涉及到容易出错的地方,在这里也一并总结一下,希望能给大家在配置的过程中提供帮助,少走弯路。
要想让struts2实现IOC的功能需要做如下几步工作:
(1)、web.xml中添加如下配置:
	<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>

(2)、需要修改struts.properties配置文件:
struts.objectFactory = org.apache.struts2.spring.StrutsSpringObjectFactory

[b]注意,很多网上的文章写的是:[/b]
struts.objectFactory = spring

[b]我个人配置的经验是,这样配置可能会报错,原因我也不知道……。[/b]
(3)、引入spring.jar和struts2-spring-plugin-2.0.11.1.jar两个jar包。
(4)、将struts的*Action.java以bean的形式写在spring的配置文件中,如下代码所示:
<bean id="userAction" class="com.demo.web.user.UserAction" />

(5)、将spring的配置文件加入web.xml中,形如:
	<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:spring/applicationContext*.xml
</param-value>
</context-param>

(6)、修改strtus.xml配置文件:
将原来的
……
<action name="user" class="com.demo.web.user.UserAction">
<result name="reload" type="redirect-action">user</result>
</action>
……

改为:
……
<action name="user" class="userAction">
<result name="reload" type="redirect-action">user</result>
</action>
……


完成这个过程后,基本上算大功告成。
[b]但是,在实际的配置过程中,需要注意如下问题[/b]
1、关于调用struts的action时出现如下错误:
[color=red]No thread-bound request found: Are you referring to request attributes outside of an actual web request? If you are actually operating within a web request and still receive this message,your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request. [/color]
必然,这个错误是由于IOC引起的,如果不用IOC的方式,这个错误就不会出现。一种出现该错误的情况在于你的Action配置了session,request或则response。大家都知道在struts2中,request和response的实现机制已经大不一样了,不以参数的形式存在于方式之中,而是通过实现SessionAware, ServletRequestAware,ServletResponseAware接口的set方法实现的。
不管怎么样,解决办法是有的,其实该错误本身就说了解决办法(use RequestContextListener or RequestContextFilter to expose the current request):
在web.xml中添加:
	<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>

重新启动,你会发现,现在错误没有了。
2、关于struts.properties的两个参数设置:
#该参数设置spring管理的struts bean的装配模式
#有如下参数可供选择
#name 按照你的action的属性的名字和Spring里的bean的名字匹配,如果匹配就自动装配。这是缺省的
#type 按照你的action的属性的类型,在Spring注册的bean中查找,如果相同就自动装配。这需要你在Spring中仅注册了一个此类型的bean
#auto Spring会试图自动监测来找到最好的方法自动装配你的action
#constructor Spring会自动装配bean的构造函数的参数

struts.objectFactory.spring.autoWire = type
#是否使用类缓存。你可以通过设置修改struts.properties中下列属性的值来改变是否使用Spring自身的类缓存机制。可以设定的值为true或false,默认为true
struts.objectFactory.spring.useClassCache = false
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值