技术开发 频道

设计模式:设计自己的MVC框架

    2.还是先来看下两个模型:ActionForward和ActionModel,没什么东西,属性以及相应的getter,setter方法:
/** * 类说明:转向模型 * @author dennis * * */ public class ActionForward { private String name; //forward的name private String viewUrl; //forward的url public static final ActionForward SUCCESS=new ActionForward("success"); public static final ActionForward FAIL=new ActionForward("fail"); public ActionForward(String name){ this.name=name; } public ActionForward(String name, String viewUrl) { super(); this.name = name; this.viewUrl = viewUrl; } //...name和viewUrl的getter和setter方法 }
    我们看到ActionForward预先封装了SUCCESS和FAIL对象。
public class ActionModel { private String path; // action的path private String className; // action的class private Map<String, ActionForward> forwards; // action的forward public ActionModel(){} public ActionModel(String path, String className, Map<String, ActionForward> forwards) { super(); this.path = path; this.className = className; this.forwards = forwards; } //...相应的getter和setter方法 }
    3。知道了两个模型是什么样,也应该可以猜到我们的配置文件大概是什么样的了,与struts的配置文件格式类似:
<?xml version="1.0" encoding="UTF-8"?> <actions> <action path="/login" class="com.strutslet.demo.LoginAction"> <forward name="success" url="hello.jsp"/> <forward name="fail" url="fail.jsp"/> </action> </actions>
    path是在应用中将被调用的路径,class指定了调用的哪个action,forward元素指定了转向,比如我们这里如果是success就转向hello.jsp,失败的话转向fail.jsp,这里配置了demo用到的LoginAction。

    4。Dispacher接口,主要是getNextPage方法,此方法负责获得下一个页面将导向哪里,提供给前端控制器转发。
public interface Dispatcher { public void setServletContext(ServletContext context); public String getNextPage(HttpServletRequest request,ServletContext context); }
    5。原先书中实现了一个WorkFlow的Dispatcher,按照顺序调用action,实现工作流调用。而我们所需要的是根据请求的path调用相应的action,执行action的execute方法返回一个ActionForward,然后得到ActionForward的viewUrl,将此viewUrl提供给前端控制器转发,看看它的getNextPage方法:
public String getNextPage(HttpServletRequest request, ServletContext context) { setServletContext(context); Map<String, ActionModel> actions = (Map<String, ActionModel>) context .getAttribute(Constant.ACTIONS_ATTR); //从ServletContext得到所有action信息 String reqPath = (String) request.getAttribute(Constant.REQUEST_ATTR);//发起请求的path ActionModel actionModel = actions.get(reqPath); //根据path得到相应的action String forward_name = ""; ActionForward actionForward; try { Class c = Class.forName(actionModel.getClassName()); //每个请求对应一个action实例 Action action = (Action) c.newInstance(); actionForward = action.execute(request, context); //执行action的execute方法 forward_name = actionForward.getName(); } catch (Exception e) { log.error("can not find action "+actionModel.getClassName()); e.printStackTrace(); } actionForward = actionModel.getForwards().get(forward_name); if (actionForward == null) { log.error("can not find page for forward "+forward_name); return null; } else return actionForward.getViewUrl(); //返回ActionForward的viewUrl }
0
相关文章