1.首先以插件的方式让struts知道spring的存在:
在struts-config.xml中加入:
2.进行代理:
parameter="add"
type="org.springframework.web.struts.DelegatingActionProxy" />
在spring的配置文件中:
abstract="false" singleton="true" lazy-init="default"
autowire="default" dependency-check="default">
让action中的path与spring中的name属性相等。
3.这种方式的配置存在的缺陷:在struts-cofig.xml我们不知道action的类型!
4.改进:利用spring的DelegatingRequestProcessor
采用DelegatingRequestProcessor将处理转发给Spring容器中的bean
DelegatingRequestProcessor继承自RequestProcessor。为了让Struts使用DelegatingRequestProcessor,还需要在struts-config.xml文件中增加如下代码:
这一行代码是告诉Struts用DelegatingRequestProcessor来 代替原来的RequestProcessor。完成设置这个设置后,Struts会将拦截到的用户请求转发到Spring context下的bean,根据bean的name属性来匹配。而Struts中的action配置则无需配置type属性(即使配置了type属性也 不起任何作用,除非在spring的配置文件里找不到对应的name属性值)。
配置了上面的一行代码后,就可以在Spring的配置文件(可以不是applicationContext.xml,比如假设这里是action- servlet.xml)中配置用来处理请求的Action bean了。配置的时候需要注意的是Action bean不再需要id属性,而要用name替代id属性,这时name属性的值应与struts-config.xml中配置的Action的path属 性的值相同。
这样,处理请求的Action就能处于Spring的管理之下了。
5.当然我们也可以让我的action继承ActionSupport
在action中利用如下的代码获得原来需要注入的bean:
ApplicationContext context = this.getWebApplicationContext();
CourseService courseService = context.getBean("courseService);
这种方式与利用sett注入的效果是一样的。不过我们的代码依赖了spring的AcitonSurpport的类,而且要手动过的bean,违反了IOC原则。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/9474419/viewspace-473074/ ,如需转载,请注明出处,否则将追究法律责任。