ward name="success" path="/WEB-INF/pages/detail.jsp"/﹥
﹤ forward name="failure" path="/WEB-INF/pages/search.jsp"/﹥
﹤ /action﹥
﹤ /action-mappings﹥
﹤ message-resources parameter="ApplicationResources"/﹥
﹤ plug-in className="org.apache.struts.validator.ValidatorPlugIn"﹥
﹤ set-property property="pathnames" value="/WEB-INF/validator- rules.xml,/WEB-INF/validation.xml"/﹥
﹤ /plug-in﹥
﹤ plug-in className="org.springframework.web.struts.ContextLoaderPlugIn"﹥ (1)
﹤ set-property property="contextConfigLocation" value="/WEB- INF/beans.xml"/﹥
﹤ /plug-in﹥
﹤ /struts-config﹥
集成Spring和Struts的实例(2)
时间:2011-06-19 IT168 javaresearch
4.使用Spring的ActionSupport类
要用Spring去集成Struts,创建一个Spring 上下文是必须要做的。 org.springframework.web.struts.ActionSupport 类提供一个 getWebApplicationContext() 方法非常容易地获得Spring上下文,全部你需要 去做的是从Spring的ActionSupport 代替Struts 中的Action类去延伸你的 action,如下所示:
package com.infotek.Creditcard.actions;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.springframework.context.ApplicationContext;
import org.springframework.web.struts.ActionSupport;
import com. infotek.Creditcard.beans.Creditcard;
import com. infotek.Creditcard.business.CreditcardService;
public class SearchSubmit extends ActionSupport { |(1)
public ActionForward execute(ActionMapping mapping,ActionForm form,
HttpServletRequest request,HttpServletResponse response)
throws IOException, ServletException {
DynaActionForm searchForm = (DynaActionForm) form;
String isbn = (String) searchForm.get("cardno");
//the old fashion way
//CreditcardService creditcardService = new CreditcardServiceImpl ();
ApplicationContext ctx = getWebApplicationContext(); |(2)
CreditcardService creditcardService =
(CreditcardService ) ctx.getBean("creditcardService"); |(3)
CreditCard creditard = CreditCardService.read(cardno.trim());
if (null == creditard) {
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_ERROR,new ActionError ("message.notfound"));
saveErrors(request, errors);
return mapping.findForward("failure") ;
}
request.setAttribute("creditcard", creditcard);
return mapping.findForward("success");
}
}
在(1)中,我们通过延伸Spring ActionSupport 类而不是Struts Action 类 创建了一个action;在(2)中,我们使用getWebApplicationContext()方法获得一 个 ApplicationContext;为了获得商务服务, 在(3)中,我们使用 ApplicationContext去查找Spring bean;这 |