其實吧,自定義MVC雖然聽着挺高大上的,不過就是模仿其餘的框架(如Struts2等),在這裏簡單來講就是copy了一下,只是有些東西仍是本身來寫的.css
*:自定義MVC只是用到了dom4jhtml
一、Framework.xml配置文件java
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE Framework[ <!ELEMENT Framework (actions)> <!ELEMENT actions (action*)> <!ELEMENT action (rusult*)> <!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>
二、Action接口web
package Action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * 一、建立Action 接口 * * @author 123 * */ public interface Action { /** * Struts2源碼中有五個靜態字符串常量,在這裏咱們只須要兩個就行 */ public static final String SUCCESS = "success"; public static final String LOGIN = "login"; // 方法 public String execute(HttpServletRequest request, HttpServletResponse response); }
三、ActionMapping類(建立actionMapping 一個actionMapping對應一個action節點)數組
package Action; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * 二、建立actionMapping 一個actionMapping對應一個action節點 * * @author 123 * */ public class ActionMapping { /** * name 是對應action中name屬性值 classname 是對應ction中class屬性值 */ private String name; private String classname; // action有多個result節點 private Map<String, String> results = new HashMap<String, String>(); 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, String> getResults() { return results; } // 這個是不須要的 /* * public void setResults(Map<String, String> results) { this.results = * results; } */ // 對應result節點中name屬性值和value屬性值 public void addResult(String name, String value) { this.results.put(name, value); } public String getResults(String name) { return results.get(name); } }
四、ActionMappingManager(建立ActionMappingManager 一個actions節點下可能會多個action節點)app
package Action; import java.io.InputStream; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; /** * 三、建立ActionMappingManager 一個actions節點下可能會多個action節點 * * @author 123 * */ public class ActionMappingManager { // actions中有多個action節點 private Map<String, ActionMapping> maps = new HashMap<String, ActionMapping>(); // 獲取maps中的Actionmapping public ActionMapping get(String name) { return maps.get(name); } // 解析Framework.xml中節點中的數據 public void Init(String path) throws DocumentException { InputStream is = this.getClass().getResourceAsStream("/" + path); Document doc = new SAXReader().read(is); // 獲取根節點 Element rootElement = doc.getRootElement(); // actions節點的獲取 Element actions = (Element) rootElement.elementIterator("actions") .next(); // actions下有多個action節點 for (Iterator<Element> action = actions.elementIterator(); action .hasNext();) { // 具體的action節點 Element actionnext = action.next(); // 當前action節點對應class屬性的值 String classname = actionnext.attributeValue("class"); // 當前action節點對應name屬性的值 String name = actionnext.attributeValue("name"); ActionMapping mapp = new ActionMapping(); // 保存數據 mapp.setClassname(classname); mapp.setName(name); // 因爲一個action下可能有存在多個result節點 for (Iterator<Element> result = actionnext.elementIterator(); result .hasNext();) { // 具體的result節點 Element resultnext = result.next(); String resultname = resultnext.attributeValue("name"); // 獲取result節點中的數據 String page = resultnext.getText(); // 往裏添加數據 mapp.addResult(resultname, page); } // 爲maps填充數據 maps.put(mapp.getName(), mapp); } } /** * 把全部的xml中的數據裝載起來 * * @param file * @throws DocumentException */ public ActionMappingManager(String[] file) throws DocumentException { // 遍歷該數組 for (String filename : file) { Init(filename); } } }
五、LoginAction(實現是本身定義的Action接口)框架
package Action; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 實現是本身定義的Action接口 * @author 123 * */ public class LoginAction implements Action { @Override public String execute(HttpServletRequest request, HttpServletResponse response) { String name = request.getParameter("name"); String pwd = request.getParameter("pwd"); if ("1".equals(pwd) && "1".equals(name)) { return SUCCESS; } return LOGIN; } }
六、YourServletdom
package Servlet; import java.io.IOException; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.dom4j.DocumentException; import Action.Action; import Action.ActionManager; import Action.ActionMapping; import Action.ActionMappingManager; public class YourServlet extends HttpServlet { ActionMappingManager mapping = null; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 獲取actionMapping ActionMapping actionMapping = mapping.get(getPath(request)); System.out.println("actionMapping" + actionMapping); // 利用反射機制獲得action try { String classname = actionMapping.getClassname(); System.out .println("classname=================================================================" + classname); Action loginAction = ActionManager.getActionClass(actionMapping .getClassname()); System.out.println("loginAction" + loginAction); // 調用execute方法 String message = loginAction.execute(request, response); System.out.println("message" + message); String results = actionMapping.getResults(message); System.out.println("results" + results); response.sendRedirect(results); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } // 解析地址訪問路徑 public String getPath(HttpServletRequest request) { // 獲取項目名+請求地址 String requestURI = request.getRequestURI(); String ProjectPath = request.getContextPath(); // loginAction.action String path = requestURI.substring(ProjectPath.length()); System.out.println("ProjectPath" + ProjectPath); System.out.println("path" + path); System.out.println("requestURI" + requestURI); System.out.println("lastIndexOf" + path.lastIndexOf(".")); // 解析地址欄中的字符串 String trim = path.substring(1, path.lastIndexOf(".")).trim(); System.out.println(trim); return trim; } /** * * 當web容器啓動的時候,就加載配置文件 */ @Override public void init(ServletConfig config) throws ServletException { System.out.println("呵呵"); // 獲取初始化配置文件 String filename = config.getInitParameter("config"); String[] files = null; if (filename == null) { files = new String[] { "Framework.xml" }; } else { files = filename.split(","); } try { mapping = new ActionMappingManager(files); } catch (DocumentException e) { e.printStackTrace(); } } }
七、web.xmljsp
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>customMVC</display-name> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>YourServlet</servlet-name> <servlet-class>Servlet.YourServlet</servlet-class> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>YourServlet</servlet-name> <url-pattern>*.action</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> </web-app>
八、登錄頁面ide
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="LoginAction.action" method="post"> 用戶名:<input name="name"> 密碼:<input name="pwd"> <input type="submit"> </form> </body> </html>
九、成功頁面
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'success.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <h1>success!</h1> </body> </html>
十、成功了
下載地址:http://pan.baidu.com/s/1kVSnd11 密碼:9e8s