自定義MVC的步驟
1.定義個Servlet(ActionServlet)控制所有的*.do請求
2.獲得請求路徑(request.getRequestURI()),截取到後面的請求名(cname)
3.在WEB-INF下創建一個config.properties文件,保存一個鍵值對,根據不同的請求得到其對應的Class,同時創建好對應的處理類
4.在Servlet的init方法中加載配置文件
Properties config=new Properties();
String path=this.getServletContext.getRealPath();//得到其絕對路徑
path=path+"/WEB-INF/config.properties";
config.load(new FileInputStream(path));//加載到內存中
this.getServletContext.setAttribute("config",config);//存入到application中
5.到dopost方法中取出application中的數據,結合前面取到的請求名得到其對應的類名
Properties config=(Properties )this.getServletContext.getAttribute("config");
String className=config.getProperty(cname);
6.將"/WEB-INF/config.properties"存入到web.xml文件中,並通過代碼取出
String sname=this.getServletContext.getInitParameter("config");
7.根據取出來的類名(全路徑名),實例化對象
Class.forName(className).newInstance();
8.新建一個接口(Action),聲明方法execute();將所有的實現類繼承action接口
9.將Class.forName返回的對象統一爲轉換爲Action,再統一的調用execute()方法(多態)
10.修改接口的方法execute(),讓其帶參數(request,response),其所有的繼承類對應的做修改,保證能從ActionServlet傳送到對應頁面
11.將Action存入到一個池中,步驟:現在init方法中建立一個池(Properties),再在dopost方法中判斷,以保證每一個類只會被實例化一次