Tuesday, October 16, 2012

How to use Spring inside Struts Actions?

Spring can be integrated into Struts actions to take advantage of seamless bean findings, here is how:
Step 1: 
Create a BaseAction class and extend this class to create struts actions.
 
BaseAction.java (add spring-webmvc-struts.jar to web-inf/lib)
 
import org.springframework.web.struts.DispatchActionSupport;
public class BaseAction extends DispatchActionSupport {
 protected Object getBean(String name) {
  return getWebApplicationContext().getBean(name);
 }
} 
 
Step 2: Action class sample: 
BalanceAction.java 
public class BalanceAction extends BaseAction {
 @Override
 public ActionForward execute(ActionMapping mapping, ActionForm form,
   HttpServletRequest request, HttpServletResponse response)
   throws Exception {
  try {
   BeanService handle = (BeanService)getBean("BeanName");
   handle.businessMethod();
  } catch (Exception ex) {
   System.out.println("Cannot find the bean...");
  }
  return mapping.findForward("success");
 }
}

No comments: