設計模式:設計自己的MVC架構)

來源:互聯網
上載者:User
原始碼放在sharesources@126.com的郵箱的收件匣裡,使用者名稱:sharesource,密碼:javafans
希望保留給有用的人,謝謝。

    取這樣一個標題太大,吸引眼球嘛@_@。

    事實是最近讀《J2EE設計模式》講述表達層模式的那幾章,書中有一個前端控制器+command模式的workflow例子,就琢磨著可以很簡單地擴充成一個MVC架構。花了一個下午改寫了下,對書中所述的理解更為深入。我想這也許對於學習和理解設計模式,以及初次接觸struts等MVC架構的人可能有點協助。因為整個模型類似於struts,我把它取名叫strutslet^_^。學習性質,切勿認真。

(一)完整的類圖如下:

點擊查看大圖

1。前端控制器(FrontController):前端控制器提供了一個統一的位置來封裝公用請求處理,它的任務相當簡單,執行公用的任務,然後把請求轉交給相應的控制器。在strutslet中,前端控制器主要作用也在於此,它初始化並解析設定檔,接受每個請求,並簡單地把請求委託給調度器(Dispatcher),由調度器執行相應的動作(Action)。調度器把action返回的url返回給FrontController,FrontController負責轉寄。

2。Action介面:command模式很好的例子,它是一個命令介面,每一個實現了此介面的action都封裝了某一個請求:新增一條資料記錄並更新model,或者把某個檔案寫入磁碟。命令解耦了寄件者和接受者之間聯絡。 寄件者調用一個操作,接受者接受請求執行相應的動作,因為使用Command模式解耦,寄件者無需知道接受者任何介面。

3。Dispatcher:調度器,負責流程的轉寄,負責調用action去執行商務邏輯。由調度器選擇頁面和action,它去除了應用行為和前端控制器間的耦合。調度器服務於前端控制器,它把model的更新委託給action,又提供頁面選擇給FrontController

4。ActionForward:封裝了轉向操作所需要資訊的一個模型,包括name和轉向url

5。ActionModel:解析設定檔後,將每一個Action封裝成一個ActionModel對象,所有ActionModel構成一個map,並儲存在ServletContext中,供整個架構使用。

(二)原始碼簡單分析
1。Action介面,只有一個execute方法,任何一個action都只要實現此介面,並實現相應的商務邏輯,最後返回一個ActionForward,提供給Dispacher調用。

  1. public interface Action {
  2.  public ActionForward execute(HttpServletRequest request,ServletContext context); 
  3. }

比如,我們要實現一個登陸系統(demo的例子),LoginAction驗證使用者名稱和密碼,如果正確,返回success頁面,如果登陸失敗,返回fail頁面:

  1. public class LoginAction implements Action {
  2.  private String name="";
  3.  public ActionForward execute(HttpServletRequest request,
  4.    ServletContext context) {
  5.   String userName=request.getParameter("userName");
  6.   String password=request.getParameter("password");
  7.         if(userName.equals("dennis")&&password.equals("123")){
  8.       request.setAttribute("name", name);
  9.       return ActionForward.SUCCESS;  //登陸成功,返回success
  10.         }else
  11.          return ActionForward.FAIL;    //否則,返回fail
  12.  }

 

2.還是先來看下兩個模型:ActionForward和ActionModel,沒什麼東西,屬性以及相應的getter,setter方法:

 

  1. /**
  2.  * 類說明:轉向模型
  3.  * @author dennis
  4.  *
  5.  * */
  6. public class ActionForward {
  7.  private String name;      //forward的name
  8.  private String viewUrl;   //forward的url
  9.  public static final ActionForward SUCCESS=new ActionForward("success");
  10.  public static final ActionForward FAIL=new ActionForward("fail");
  11.  public  ActionForward(String name){
  12.   this.name=name;
  13.  }
  14.  public ActionForward(String name, String viewUrl) {
  15.   super();
  16.   this.name = name;
  17.   this.viewUrl = viewUrl;
  18.  }
  19.  //...name和viewUrl的getter和setter方法
  20. }   

我們看到ActionForward預先封裝了SUCCESS和FAIL對象。

  1. public class ActionModel {
  2.  private String path; // action的path
  3.  private String className; // action的class
  4.  private Map<String, ActionForward> forwards; // action的forward
  5.  public ActionModel(){}
  6.  public ActionModel(String path, String className,
  7.    Map<String, ActionForward> forwards) {
  8.   super();
  9.   this.path = path;
  10.   this.className = className;
  11.   this.forwards = forwards;
  12.  }
  13.  //...相應的getter和setter方法     
  14. }

3。知道了兩個模型是什麼樣,也應該可以猜到我們的設定檔大概是什麼樣的了,與struts的設定檔格式類似:

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <actions>
  3.   <action path="/login"
  4.           class="com.strutslet.demo.LoginAction">
  5.      <forward name="success" url="hello.jsp"/>
  6.      <forward name="fail" url="fail.jsp"/>
  7.    </action>       
  8. </actions>

path是在應用中將被調用的路徑,class指定了調用的哪個action,forward元素指定了轉向,比如我們這裡如果是success就轉向hello.jsp,失敗的話轉向fail.jsp,這裡配置了demo用到的LoginAction。

4。Dispacher介面,主要是getNextPage方法,此方法負責獲得下一個頁面將導向哪裡,提供給前端控制器轉寄。

  1. public interface Dispatcher {
  2.  public void setServletContext(ServletContext context);
  3.  public String getNextPage(HttpServletRequest request,ServletContext context);
  4. }

5。5。原先書中實現了一個WorkFlow的Dispatcher,按照順序調用action,實現工作流程調用。而我們所需要的是根據請求的path調用相應的action,執行action的execute方法返回一個ActionForward,然後得到ActionForward的viewUrl,將此viewUrl提供給前端控制器轉寄,看看它的getNextPage方法:

  1. public String getNextPage(HttpServletRequest request, ServletContext context) {
  2.   setServletContext(context);
  3.   Map<String, ActionModel> actions = (Map<String, ActionModel>) context
  4.     .getAttribute(Constant.ACTIONS_ATTR);   //從ServletContext得到所有action資訊
  5.   String reqPath = (String) request.getAttribute(Constant.REQUEST_ATTR);//發起請求的path
  6.   ActionModel actionModel = actions.get(reqPath);  //根據path得到相應的action
  7.   String forward_name = "";
  8.   ActionForward actionForward;
  9.   try {
  10.    Class c = Class.forName(actionModel.getClassName());  //每個請求對應一個action執行個體
  11.    Action action = (Action) c.newInstance();
  12.    actionForward = action.execute(request, context);  //執行action的execute方法
  13.    forward_name = actionForward.getName();
  14.    
  15.   } catch (Exception e) {
  16.    log.error("can not find action "+actionModel.getClassName());
  17.    e.printStackTrace();
  18.   }
  19.   actionForward = actionModel.getForwards().get(forward_name);
  20.   if (actionForward == null) {
  21.    log.error("can not find page for forward "+forward_name);
  22.    return null;
  23.   } else
  24.    return actionForward.getViewUrl();      //返回ActionForward的viewUrl
  25.  }

 

6。前端控制器(FrontController),它的任務我們已經很清楚,初始化設定檔;儲存所有action到ServletContext供整個架構使用;得到發起請求的path,提供給Dispachter尋找相應的action;調用Dispatcher,執行getNextPage方法得到下一個頁面的url並轉寄:

 

  1. public void init() throws ServletException {
  2.   //初始化設定檔
  3.   ServletContext context=getServletContext();
  4.   String config_file =getServletConfig().getInitParameter("config");
  5.   String dispatcher_name=getServletConfig().getInitParameter("dispatcher");
  6.   if (config_file == null || config_file.equals(""))
  7.    config_file = "/WEB-INF/strutslet-config.xml"; //預設是/WEB-INF/下面的strutslet-config
  8.   if(dispatcher_name==null||dispatcher_name.equals(""))
  9.    dispatcher_name=Constant.DEFAULT_DISPATCHER;
  10.     
  11.   try {
  12.    Map<String, ActionModel> resources = ConfigUtil.newInstance()  //工具類解析設定檔
  13.      .parse(config_file, context);
  14.    context.setAttribute(Constant.ACTIONS_ATTR, resources);  //儲存在ServletContext中
  15.    log.info("初始化strutslet設定檔成功");
  16.   } catch (Exception e) {
  17.    log.error("初始化strutslet設定檔失敗");
  18.    e.printStackTrace();
  19.   }
  20.   //執行個體化Dispacher
  21.   try{
  22.    Class c = Class.forName(dispatcher_name);
  23.       Dispatcher dispatcher = (Dispatcher) c.newInstance();
  24.       context.setAttribute(Constant.DISPATCHER_ATTR, dispatcher); //放在ServletContext
  25.       log.info("初始化Dispatcher成功");
  26.   }catch(Exception e) {
  27.     log.error("初始化Dispatcher失敗");
  28.       e.printStackTrace();
  29.   }
  30.   .....

doGet()和doPost方法我們都讓它調用process方法:

  1. protected void process(HttpServletRequest request,
  2.    HttpServletResponse response) throws ServletException, IOException {
  3.   ServletContext context = getServletContext();
  4.         //擷取action的path 
  5.   String reqURI = request.getRequestURI();
  6.   int i=reqURI.lastIndexOf(".");
  7.   String contextPath=request.getContextPath();
  8.   String path=reqURI.substring(contextPath.length(),i);
  9.   
  10.   request.setAttribute(Constant.REQUEST_ATTR, path);
  11.   Dispatcher dispatcher = (Dispatcher) context.getAttribute(Constant.DISPATCHER_ATTR);
  12.   // make sure we don't cache dynamic data
  13.   response.setHeader("Cache-Control", "no-cache");
  14.   response.setHeader("Pragma", "no-cache");
  15.   // use the dispatcher to find the next page
  16.   String nextPage = dispatcher.getNextPage(request, context);//調用Dispatcher的getNextPage
  17.   // forward control to the view
  18.   RequestDispatcher forwarder = request.getRequestDispatcher("/"
  19.     + nextPage);
  20.   forwarder.forward(request, response);  //轉寄頁面
  21.  }

7。最後,web.xml的配置就非常簡單了,配置前端控制器,提供啟動參數(設定檔所在位置,為空白就尋找/WEB-INF/下面的strutslet-config.xml檔案),我們把所有以action結尾的請求都交給FrontController處理:

  1. <servlet>
  2.     <servlet-name>StrutsletController</servlet-name>
  3.     <servlet-class>com.strutslet.core.FrontController</servlet-class>
  4.     <!--  
  5.     <init-param>
  6.          <param-name>config</param-name>
  7.          <param-value>/WEB-INFstrutslet-config.xml</param-value>
  8.     </init-param>
  9.     -->
  10.        <load-on-startup>0</load-on-startup>
  11.   </servlet>
  12.  <servlet-mapping>
  13.     <servlet-name>StrutsletController</servlet-name>
  14.     <url-pattern>*.action</url-pattern>
  15.  </servlet-mapping>

最後,讓我們看看整個架構圖:

點擊查看大圖

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.