There are 2 ways in which Spring features can be injected in Struts. The common point in all the 2 strategies is that we need to register a Struts plug-in that is aware of the Spring application context. Add the following code to your struts-config.xml to register the plug-in:
<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
<set-property property="contextConfigLocation"
value="/WEB-INF/training-servlet.xml,/WEB-INF/…"/>
</plug-in>
ContextLoaderPlugIn loads a Spring application context (a WebApplication-
Context, to be specific), using the context configuration files listed (commaseparated)
in its contextConfigLocation property.
- Extending the ActionSupport class instead of Action class
public class ListCourseAction extends ActionSupport {
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws Exception {
ApplicationContext context = getWebApplicationContext();
CourseService courseService = (CourseService) context.getBean("courseService");
Set allCourses = courseService.getAllCourses();
request.setAttribute("courses", allCourses);
return mapping.findForward("courseList");
}
}
The ActionSupport class extends the Action class and has the added method of getWebApplicationContext() which will return the current applicationContext with the help of which we can get the beans.
- Using the DelegatingActionProxy
The struts action mapping in the struts-config needs to have the DelegatingActionProxy as the class attribute value
<action path="/listCourses"
type="org.springframework.web.struts.DelegatingActionProxy"/>
and the equivalent mapping in the spring config should be
<bean name="/listCourses"
class="com.springinaction.training.struts.ListCourseAction">
<property name="courseService">
<ref bean="courseService"/>
</property>
</bean>