BaseAction的java多态思考

BaseAction的java多态思考

对于struts框架,我们都知道我们写的*Action类是继承struts的Action(org.apache.struts.action.Action)类,并重写其定义的execute方法,进而来实现我们自己的业务逻辑。

但考虑到到一些需求,我们可以在struts的Action和我们自己写的*Action类之间加一层Action类来实现过滤功能,我们将其定义为BaseAction,整个继承关系:*Action--extends---->BaseAction---extends--->Action。

举例如下:

在ListAction类和Struts框架的Action类之间加一层BaseAction类。

ListAction:

//extends BaseAction
public class ListAction extends BaseAction {

 public ActionForward doExecute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) throws Exception {
  
  Connection conn = null;
  conn = this.getDataSource(request).getConnection();
  BookDAO bookDAO  = DAOFactory.getBookDAO(conn);
  List list = bookDAO.findAll();
  request.setAttribute("books", list);
  return mapping.findForward(Constants.FORWARD_LIST); 
 }
 
 //实现BaseAction中的needLogin方法,判断*Action是否需要登陆验证
 public boolean needLogin() {  
  return true;
 }
}

BaseAction:

public abstract class BaseAction extends Action {

  //override the method execute of Action  
 public final ActionForward execute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) throws Exception {

  if(needLogin()){
     //取出LoginAction中放入session中的用户名"aaa"
     Object o = request.getSession().getAttribute("aaa");
   if(o == null){
     //登陆验证失败,返回login.jsp
     return actionMapping.findForward("login");
   }
  } 
  //返回调用ListAction中的doExcute()方法,执行业务逻辑
  return doExecute(actionMapping, actionForm, request, response);
 }

 //abstract method
 public abstract ActionForward doExecute(ActionMapping actionMapping, ActionForm actionForm, HttpServletRequest  request, HttpServletResponse response)  throws Exception;
 
 //abstract method
 public abstract boolean needLogin();

}

在BaseAction中重写struts中Action的excute()方法,在ListAction中定义doexcute()方法并extends BaseAction类,登陆系统是根据login.do进入LoginAction,调用重写struts中的excute()方法,此时LoginAction没有,就到父类BaseAction去调用excute()方法,执行其业务逻辑后,如过用户是已经登陆过就返回doExcute()方法,回到ListAction调用doExcute()的业务逻辑,如果是非登陆用户则直接转向Login.jsp。这里将java中多态,抽象类以及回调的思想体现得淋漓尽致。


你可能感兴趣的:(BaseAction的java多态思考)