Struts and Spring together?

徘徊边缘 提交于 2019-12-03 22:07:14

From a struts 1 ActionForm class you'll be needing:

WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext).getBean("yourService");

Are you using Struts 1 or 2?

If you're using Struts 1 then there are couple of ways of doing it. I prefer to do it using org.springframework.web.struts.DelegatingActionProxy. You'll need to have the spring-webmvc-struts.jar in the classpath.

struts-config.xml:

   <action path="/faq" type="org.springframework.web.struts.DelegatingActionProxy" name="faqForm" parameter="method">
        <forward name="List" path="faq.list" />
    </action>

applicationContext.xml:

<bean name="/faq" class="com.mypackage.FAQAction" autowire="byType" />

I've found this technique to be the most elegant, it doesn't affect old code that doesn't use spring.

There are at least two more ways of integrating struts 1 with spring. There's an article at ibm developerworks that explains the pros and cons of the different solutions, google "Get a better handle on Struts actions, with Spring" (newbies like myself aren't allowed to include links).

Normally you add the spring contextloader listener to your web xml.

<listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

Then you add

<constant name="struts.objectFactory" value="spring"/>

to your struts.xml.

Then in your action class you can say things like:

class MyAction {
  @Autowired MyService service;
   ....
}

That's all there is to it for struts2.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!