【熵增教育】自定義MVC框架——熵增學院

自定義MVC框架

  • 實現自定義MVC的體系結構圖

https://images2015.cnblogs.com/blog/803693/201609/803693-20160920114523527-633744873.png

1、Model I模式開發Web應用時,分兩種情況:

  *純JSP技術方式開發

  *JSP+JavaBean方式開發

2、Model I模式開發的不足:

  *JSP頁面中嵌入大量的Java代碼,可讀性差。

  *大量代碼在JSP中難以複用。

  *後期維護及擴展的難度大。

3、爲了克服Model I模式的缺陷,引入了Model II的模式開發 

  *Model II模式體現了基於MVC(Model-View-Controller,模型-視圖-控制器)的設計模式,簡單的說,Model II模式就是將數據顯示、流程控制和業務邏輯處理分離,使之相互獨立。 

4、MVC設計模式由3個部分組成各部分的作用。

  *Model:模型,主要用於數據和業務的處理。

  *View:視圖,用於數據顯示。

  *Controller:控制器,用於流程控制。

5、MVC設計模式的特點

  *一個模型可以對應多個視圖。

  *顯示與邏輯控制分離。

  *分層控制,減低了代碼間的耦合。

  • 我們如何創建一個自己的MVC框架??

(一)我們要在lib裏面準備一個夾包

dom4j-1.6.1.jar   主要作用:解析xml文件

(二)準備配置文檔(在src下)

<!DOCTYPE myframework[

    <!ELEMENT myframework (actions) >

    <!ELEMENT actions (action*)>

    <!ELEMENT action (result*)>

    <!ATTLIST action name CDATA #REQUIRED

                     class CDATA #REQUIRED

    >

    <!ATTLIST result name CDATA #IMPLIED

                    redirect (true|false) "false"

    >

]>

解釋:

https://images2015.cnblogs.com/blog/803693/201609/803693-20160922083847621-1737094974.png

解釋:根據上述約束完成的“*”代表該節點可以出現多次

 

<myframework>

        <actions>

            <action name="LoginAction" class="cn.action.LoginAction">

                <result name="success">success.jsp</result>

                <result name="login">login.jsp</result>

            </action>

        </actions>

</myframework>

 

(三)自己準備一個Action接口,用於放入結果集和執行方法

package cn.framework;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public interface Action {

   public final String SUCCESS = "success";

   public final String ERROR = "error";

   public final String LOGIN = "login";

   public final String INPUT = "input";

   public String execute(HttpServletRequest request,

         HttpServletResponse response);

}

 

(四)定義一個ResultMapping用來存放result節點

package cn.framework;

public class ResultMapping {

  //result節點名字

  private String name;

  //是否重定向

  private boolean redirect;

  //跳轉的頁面

  private String url;

  public ResultMapping() {

  }

  public ResultMapping(String name, boolean redirect, String url) {

     this.name = name;

     this.redirect = redirect;

     this.url = url;

  }

  public String getName() {

     return name;

  }

  public void setName(String name) {

     this.name = name;

  }

  public boolean isRedirect() {

     return redirect;

  }

  public void setRedirect(boolean redirect) {

     this.redirect = redirect;

  }

  public String getUrl() {

     return url;

  }

  public void setUrl(String url) {

     this.url = url;

  }

}

 

(五)定義一個ActionMapping用來存放Action節點

package cn.framework;

 

import java.util.HashMap;

import java.util.Map;

public class ActionMapping {

  // Action名稱

  private String name;

  // Action名稱對應的Action的類的全稱

  private String className;

  // result集合

  private Map<String, ResultMapping> results = new HashMap<String, ResultMapping>();

 

  public ActionMapping() {

  }

  public ActionMapping(String name, String className, Map<String, ResultMapping> results) {

     super();

     this.name = name;

     this.className = className;

     this.results = results;

  }

  public String getName() {

     return name;

  }

  public void setName(String name) {

     this.name = name;

  }

  public String getClassName() {

     return className;

  }

 

  public void setClassName(String className) {

     this.className = className;

  }

  public Map<String, ResultMapping> getResults() {

     return results;

  }

  public void setResults(Map<String, ResultMapping> results) {

     this.results = results;

  }

}

(六)準備一個ActionMappingManager是用來管理ActionMapping的

package cn.framework;

import java.io.InputStream;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import org.dom4j.Attribute;

import org.dom4j.Document;

import org.dom4j.Element;

import org.dom4j.io.SAXReader;

public class ActionMappingManager {

 

  Map<String, ActionMapping> actionMapping = new HashMap<String, ActionMapping>();

 

  public ActionMappingManager() {

     init();

  }

 

  public ActionMapping getActionMapping(String actionName) {

     return actionMapping.get(actionName);

  }

 

  public ActionMappingManager(String fileName) {

 

  }

 

  public Map<String, ActionMapping> getActionMapping() {

     return actionMapping;

  }

 

  public void setActionMapping(Map<String, ActionMapping> actionMapping) {

     this.actionMapping = actionMapping;

  }

 

  public static void main(String[] args) {

 

     new ActionMappingManager().init();

 

  }

 

  public void init() {

     InputStream is = this.getClass().getResourceAsStream("/myframework.xml");

   

     SAXReader sr = new SAXReader();  

     try {

        Document doc = sr.read(is);

 

        Element elRoot = doc.getRootElement();

 

        List<Element> listActions = elRoot.elements();

 

        for (Element elActions : listActions) {

 

           List<Element> listAction = elActions.elements();

 

           for (Element elAction : listAction) {

              ActionMapping aMapping = new ActionMapping();

              Attribute attName = elAction.attribute("name");

              Attribute attClass = elAction.attribute("class");

              aMapping.setName(attName.getValue());

              aMapping.setClassName(attClass.getValue());

              List<Element> listResult = elAction.elements();

              for (Element elResult : listResult) {

                 ResultMapping rMapping = new ResultMapping();

                 Attribute attResultName = elResult.attribute("name");

                 Attribute attResultRedirect = elResult.attribute("redirect");

                 rMapping.setName(attResultName.getValue());

                rMapping.setRedirect(Boolean.parseBoolean(attResultRedirect.getValue()));

                 rMapping.setUrl(elResult.getTextTrim());

                 aMapping.getResults().put(rMapping.getName(), rMapping);

              }

              actionMapping.put(aMapping.getName(), aMapping);

           }

        }

     } catch (Exception e) {

        e.printStackTrace();

     }

  }

}

 

 

(七)利用反射機制找到自己的實列

package cn.framework;

 

public class ActionManager {

 

  public static Action createAction(String className) {

     Class<?> clz = null;

 

     try {

        clz = Thread.currentThread().getContextClassLoader().loadClass(className);

     } catch (Exception ex) {

        ex.printStackTrace();

     }

     try {

        if (clz == null) {

           clz = Class.forName(className);

        }

     } catch (Exception ex) {

        ex.printStackTrace();

     }

     Action action = null;

 

     try {

        action = (Action) clz.newInstance();

     } catch (Exception ex) {

        ex.printStackTrace();

     }

 

     return action;

  }

}

 

(八)寫一個業務邏輯

package cn.action;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import cn.framework.Action;

 

public class LoginAction implements Action {

 

  @Override

  public String execute(HttpServletRequest request, HttpServletResponse response) {

 

     return "success";

  }

}

 

(九)核心控制器Servlet

 

package cn.framework;

import java.io.IOException;

import javax.servlet.ServletConfig;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

 

public class MVCServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;

 

  protected void doGet(HttpServletRequest request, HttpServletResponse response)

        throws ServletException, IOException {

  }

 

  ActionMappingManager amanager = null;

 

  @Override

  public void init(ServletConfig config) throws ServletException {

     amanager = new ActionMappingManager();

  }

 

  protected void doPost(HttpServletRequest request, HttpServletResponse response)

        throws ServletException, IOException {

     ActionMapping am = amanager.getActionMapping(getActionName(request));

     Action action = ActionManager.createAction(am.getClassName());

     String r = action.execute(request, response);

     ResultMapping rm = am.getResults().get(r);

     if (rm.isRedirect()) {

        response.sendRedirect(rm.getUrl());

     } else {

        request.getRequestDispatcher(rm.getUrl()).forward(request, response);

     }

  }

 

  public String getActionName(HttpServletRequest request) {

     String actionName = null;

 

     String uri = request.getRequestURI();

 

     String contentPath = request.getContextPath();

 

     String actionPath = uri.substring(contentPath.length());

 

     actionName = actionPath.substring(1, actionPath.indexOf(".")).trim();

 

     return actionName;

 

  }

 

}

(十)修改web.xml

   <servlet>

      <servlet-name>MVCServlet</servlet-name>

      <servlet-class>cn.framework.MVCServlet</servlet-class>

   </servlet>

   <servlet-mapping>

      <servlet-name>MVCServlet</servlet-name>

      <url-pattern>*.action</url-pattern>

   </servlet-mapping>

 

(十一)準備一個login.jsp頁面

 

(十二)發佈到Tomcat運行

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章