自定义MVC

其实吧,自定义MVC虽然听着挺高大上的,不过就是模仿其他的框架(如Struts2等),在这里简单来说就是copy了一下,只是有些东西还是自己来写的.

*:自定义MVC只是用到了dom4j

1、Framework.xml配置文件

<?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>

 

2、Action接口

package Action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 1、创建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);
}

 

3、ActionMapping类(创建actionMapping 一个actionMapping对应一个action节点)

package Action;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * 2、创建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);
    }
}

 

 4、ActionMappingManager(创建ActionMappingManager 一个actions节点下可能会多个action节点

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;

/**
 * 3、创建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);
        }

    }

}

 

5、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;
       }

}

 

6、YourServlet

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();
        }

    }

}

 

7、web.xml

<?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>

 

8、登陆页面

<%@ 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>

 

9、成功页面

<%@ 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>

 

10、成功了

 下载地址:http://pan.baidu.com/s/1kVSnd11  密码:9e8s

posted on 2017-11-02 11:24  瞿亮  阅读(237)  评论(0编辑  收藏  举报

导航