Pages

Tuesday, March 1, 2011

How to integrate your Struts application with Spring


How to integrate your Struts application with Spring
To integrate your Struts application with Spring, we have two options:
1.      Configure Spring to manage your Actions as beans, using the ContextLoaderPlugin, and set their dependencies in a Spring context file.
2.      Subclass Spring's ActionSupport classes and grab your Spring-managed beans explicitly using a getWebApplicationContext()method.

Procedure to integrate struts and spring according to case 1
1.      get and include the “struts2-spring-plugin-xxx.jar
2.      Configure the Spring listener “org.springframework.web.context.ContextLoaderListener” in web.xml file.
               <listener>
                        <listener-class>
                                       org.springframework.web.context.ContextLoaderListener
                         </listener-class>
            </listener>
3.      Register all the Spring’s Beans in the applicationContext.xml file; the Spring listener will locate this xml file automatically.
               <bean id="userBo" class="com.mkyong.user.bo.impl.UserBoImpl" />
            <bean id="userSpringAction" class="com.mkyong.user.action.UserSpringAction">
                        <property name="userBo" ref="userBo" />            
            </bean>
4.      Declared all the relationship in struts.xml
               <action name="userSpringAction"  class="userSpringAction" >
                        <result name="success">pages/user.jsp</result>
            </action>
  This will pass the Spring’s “userBo” bean into the UserAction via setUserBo() automatically.
            UserBo userBo; 
            public void setUserBo(UserBo userBo) {
                        this.userBo = userBo;
Alternatively, you can use the Spring’s generic WebApplicationContextUtils class to get the Spring’s bean directly.
WebApplicationContext context =
                                     WebApplicationContextUtils.getRequiredWebApplicationContext(
                                    ServletActionContext.getServletContext()
                        );
                        UserBo userBo1 = (UserBo)context.getBean("userBo");
                        userBo1.printUser ();

1 comment: