先建立一個BascAction,它繼承了Action類,而其他自定義的Action都要繼承這個BaseAction。
/**
*
*/
package com.ascent.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import com.ascent.bean.Customer;
import com.ascent.business.IBookService;
import com.ascent.business.ICustomerService;
import com.ascent.business.IOrderItemService;
import com.ascent.business.IOrderService;
import com.ascent.util.AppContext;
/**
* @author
*
*/
public class BaseAction extends Action {
/**
*
*/
public BaseAction() {
super();
}
protected IBookService getBookService() {
return (IBookService) AppContext.getInstance().getAppContext(). getBean(
"bookService");
}
protected IOrderService getOrderService() {
return (IOrderService) AppContext.getInstance().getAppContext(). getBean(
"orderService");
}
protected ICustomerService getCustomerService() {
return (ICustomerService) AppContext.getInstance().getAppContext(). getBean(
"customerService");
}
protected IOrderItemService getOrderItemService() {
return (IOrderItemService) AppContext.getInstance().getAppContext(). getBean(
"orderItemService");
}
protected String checkUser(HttpServletRequest request,
HttpServletResponse response){
Customer user = null;
user = (Customer) request.getSession().getAttribute("user");
if(user==null){
System.out.println("you have no loginning!!!!");
ActionErrors errors = new ActionErrors();
errors.add(ActionErrors.GLOBAL_MESSAGE,new ActionError("errors. login"));
this.saveErrors(request,errors);
return null;
}else{
return user.getCustName();
}
}
}
/**
*
*/
package com.ascent.util;
import org.springframework.context.support.*;
/**
* <p>Title: bookstoressh</p>
*
* <p>Description: bookstore System</p>
*
* <p>Copyright: Copyright (c) 2005</p>
*
* <p>Company: ascenttech</p>
*
* @author
* @version 1.0
*/
public class AppContext {
private static AppContext instance;
private AbstractApplicationContext appContext;
public synchronized static AppContext getInstance() {
if (instance == null) {
instance = new AppContext();
}
return instance;
}
private AppContext() {
this.appContext = new ClassPathXmlApplicationContext(
"applicationContext.xml");
}
public AbstractApplicationContext getAppContext() {
return appContext;
}
}
如果在Struts中定義了一個繼承自BaseAction的Action,那麼就可以通過getXXXService()的方法來得到某一個service的實例,繼而可以實現對業務方法的調用。這裏實際上使用了一個設計模式——服務定位器(service locator)。