自訂架構(MyMvc)

來源:互聯網
上載者:User

標籤:

//初次接觸自訂架構,簡單的登入功能的實現流程::

當我們實現登入功能的時候,首先會建立一個login.jsp

會寫這些登入表單

  <form action="loginAction.action" method="post">    姓名:<input type="text" name="name"/><br/>    密碼:<input type="text" name="pwd"/><br/>    <input type="submit" value="登入">    </form>

//當然我們現在需要做的就是 吧我們自己寫的架構在項目啟動的時候成功部署

首先我們要在程式啟動的時候讓程式自行啟動一個servlet,並在servlet中寫自己架構的流程部署

需要在web.xml 中配置   

<!-- 當值為0或者大於0時,表示容器在應用啟動時就載入這個servlet; -->
<load-on-startup>0</load-on-startup>


 

<?xml version="1.0" encoding="UTF-8"?><!-- 定義約束檔案 --><!-- ELEMENT 表示元素 --><!-- ATTLIST 表示屬性 --><!-- CDATA 表示字串類型 --><!-- REQUIRED 表示此屬性必須的寫 --><!-- *代表多個 --><!-- IMPLIED 表示此屬性可寫 --><!DOCTYPE Framework[    <!ELEMENT Framework (actions)>    <!ELEMENT actions (action*)>    <!ELEMENT action (result*)>        <!ATTLIST action name CDATA #REQUIRED                     class CDATA #REQUIRED    >    <!ATTLIST RESULT name CDATA #IMPLIED                     redirect (true|false) "false"    >]><Framework><actions>   <action name="loginAction" class="Action.LoginAction">   <result name="success">success.jsp</result>   <result name="login">index.jsp</result>   </action></actions></Framework>

 

 

 

public void init(ServletConfig config) throws ServletException {        //config對象是javax.servlet.ServletConfig的對象,功能是獲得初始化配置資訊        //config.getInitParameter是取得指定名稱的初始化參數內容        String filename = config.getInitParameter("config");        System.out.println("GG\t"+filename);        String [] filenames=null;        if(filename==null)        {            //如果沒有別的參數資訊,就將已經配好的放入數組中            filenames=new String[]{"Framework.xml"};            for (String string : filenames) {                System.out.println(string);            }        }        else        {            //若果有其他的配置參數資訊,那麼以,分隔存入數組中            filenames=filename.split(",");            for (String string : filenames) {                System.out.println(string+"\t");            }        }        //使用init方法初始化        man=new ActionMappingManager(filenames);    }

因為標紅的代碼,所以他就會執行如下代碼:

package Action;/** * 步驟三: * 由於action節點不止一個,所以需要配置一個ActionMappingManage類來管理ActionMapping類 */import java.io.InputStream;import java.util.HashMap;import java.util.Iterator;import java.util.Map;import org.dom4j.Document;import org.dom4j.Element;import org.dom4j.io.SAXReader;/** * 由於這個類是actions * 所以包含了一個成員變數   定製成key value的形式是因為   * actions 中每一個action 都有他對應的 name值,每一個name代表一個key * 每個action 代表一個 value * @author SLEEP * 解析資源檔中的節點對象 * */public class ActionMappingManager {    //actionMapping類的集合  private Map<String,ActionMapping> maps=new HashMap<String,ActionMapping>();  public ActionMapping getActionMapping(String name)  {      return maps.get(name);  }  //通過init 裝配的xml檔案擷取actions  public ActionMappingManager(String[] files)  {      for (String filename : files) {                   Init(filename);      }  }  //建立初始化方法,使用dom4j解析設定檔  public void Init(String path)  {     System.out.println("呵呵-----------------------------------------");     try {         //getResourceAsStream取得該資源輸入資料流的引用保證程式可以從正確的位置抽取資料         //把Framework.xml這個資來源物件轉換成  流          InputStream is=this.getClass().getResourceAsStream("/"+path);          //解析xml 用saxreader 對象去讀取流          Document doc= new SAXReader().read(is);          //擷取根節點          Element root = doc.getRootElement();          //擷取自訂架構中的第一個 acitons節點          Element actions=(Element)root.elementIterator().next();          System.out.println("根節點"+actions.getName());          //使用for迴圈來遍曆actions節點下的所有action節點          for(Iterator<Element> action=actions.elementIterator();action.hasNext();)          {              //擷取到<action>節點 action 是一個action的集合 ,我們要取出來第一項              Element actionnext = action.next();              System.out.println("根節點下的子節點"+actionnext.getName());              //分別擷取到action節點中的name屬性和class屬性              String name = actionnext.attributeValue("name");              String classname = actionnext.attributeValue("class");              //將以上兩個屬性儲存到ActionMapping類中              ActionMapping mapp=new ActionMapping();              mapp.setClassname(classname);              mapp.setName(name);              //由於一個action節點下有多個result節點 遍曆action下所有的result節點              for(Iterator<Element> result=actionnext.elementIterator("result");result.hasNext();)              {                  //擷取到result節點                  Element resultnext = result.next();                  //提取result節點的name屬性值和result節點中的值                  String resultname = resultnext.attributeValue("name");                  String resultvalue=resultnext.getText();                  //將其分別存入到actionMapping中的雙列集合中去,方便調用actionMapping類(actionMapping類中就有資料了!)                  mapp.addResult(resultname, resultvalue);                  System.out.println(mapp.getName());              }              //得到所有action節點的集合              maps.put(mapp.getName(), mapp);          }              } catch (Exception e) {        e.printStackTrace();    }        }}

//servlet方法中的init 執行完畢之後,我們的tomcat成功開啟

當我們點擊登入的時候因為是post 請求,所以會自動調用servlet 中的doPost方法如下:

ActionMappingManager man=null;    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {                //由於index.jsp為預設請求介面,所以getname方法會擷取到index.jsp正好與ActionMappingManager中map的key對應        //擷取到ActionMapping對象        ActionMapping actionMapping = man.getActionMapping(getname(request));        //擷取action介面利用反射機制        Action action = ActionManager.getActionClass(actionMapping.getClassname());        try {            //返回一個邏輯視圖名            String message = action.execute(request, response);            String results = actionMapping.getResults(message);            response.sendRedirect(results);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    //擷取請求的路徑名 例:day01_0100/index.jsp   擷取的是index.jsp       public String getname(HttpServletRequest request)    {        //項目+請求地址        String requestURI = request.getRequestURI();        System.out.println(requestURI);        //項目名稱        String contextPath = request.getContextPath();        System.out.println(contextPath);        //具體的請求        String path=requestURI.substring(contextPath.length());        System.out.println(path);        String filename=path.substring(1,path.lastIndexOf(".")).trim();        System.out.println(filename);        return filename;    }ActionMappingManager man=null;    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {                //由於index.jsp為預設請求介面,所以getname方法會擷取到index.jsp正好與ActionMappingManager中map的key對應        //擷取到ActionMapping對象        ActionMapping actionMapping = man.getActionMapping(getname(request));        //擷取action介面利用反射機制        Action action = ActionManager.getActionClass(actionMapping.getClassname());        try {            //返回一個邏輯視圖名            String message = action.execute(request, response);            String results = actionMapping.getResults(message);            response.sendRedirect(results);        } catch (Exception e) {            // TODO Auto-generated catch block            e.printStackTrace();        }    }    //擷取請求的路徑名 例:day01_0100/index.jsp   擷取的是index.jsp       public String getname(HttpServletRequest request)    {        //項目+請求地址        String requestURI = request.getRequestURI();        System.out.println(requestURI);        //項目名稱        String contextPath = request.getContextPath();        System.out.println(contextPath);        //具體的請求        String path=requestURI.substring(contextPath.length());        System.out.println(path);        String filename=path.substring(1,path.lastIndexOf(".")).trim();        System.out.println(filename);        return filename;    }

//因為自訂Mvc沒有攔截器,所以<url-pattern>*.action</url-pattern>

<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<!-- 沒有像struts2那樣的過濾器,手動限制過濾所有的action -->
<url-pattern>*.action</url-pattern>
</servlet-mapping>

這樣一個自訂架構就完成了!

 

自訂架構(MyMvc)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.