自己动手写web框架----1

时间:2023-03-09 18:00:53
自己动手写web框架----1

本文可作为<<自己动手写struts–构建基于MVC的Web开发框架>>一书的读书笔记。

一个符合Model 2规范的web框架的架构图应该如下:

自己动手写web框架----1

Controller层的Servlet就是一个全局的大管家,它判断各个请求由谁去处理。

而各个BusinessLogic就决定具体做什么。

通过上面的图,我们能看出来核心的组件就是那个servlet,它要处理所有的请求。

那么我们就先在web.xml里配置这个servlet:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
 xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaeehttp://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <display-name>web.xml的示例</display-name>

    <!--控制器-->
    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>com.gd.action.GdServlet</servlet-class>
    </servlet>  

    <!--拦截.do的请求-->
     <servlet-mapping>
        <servlet-name>Servlet</servlet-name>
         <url-pattern>*.do</url-pattern>
     </servlet-mapping>

</web-app>

很简单,就是拦截所有.do的请求,交给com.gd.action.GdServlet来处理。

而我们的”大管家”至少要满足下面的格式要求。

package com.gd.action;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GdServlet extends HttpServlet{
    /**
     *
     */
    private static final long serialVersionUID = -5277297442646870070L;

    public void init() throws ServletException {

      }

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        doPost(req, res);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        dodispatcher (req, res);
    }

    private void do_Dispatcher (HttpServletRequest req, HttpServletResponse res) {

    }

    public void destroy() {
    }
}

咱们暂时先不考虑do_Dispatcher内部。这是最大的问题,咱们放到最后。

先解决周边问题:

1 假如,我们已经生成了对应的模型层,那么总得给传递模型层数据吧。数据来源于request,我们要是直接把request传递给某个具体的模型层,这就完全不符合Model 2规范了。因此最好的办法就是把request中的数据剥离出来形成一个对象,再把这个对象传递给具体的模型层。

这个对象是什么类型?request中的数据是以key-value的形式存储的,那就使用HashMap吧。

 private Map<String, Object> fromRequestToMap(HttpServletRequest req){

        try {
            req.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        Enumeration<String> e=req.getParameterNames();
        Map<String, Object> infoIn=new HashMap<String, Object>();
        while (e.hasMoreElements()) {
            String paraName = (String) e.nextElement();
            //为什么使用getParameterValues而不是getParameter?大家自己查资料
            Object[] value=req.getParameterValues(paraName);

            if (value==null) {
                infoIn.put(paraName, "");
            }else if(value.length==1) {
                infoIn.put(paraName, value[0]);
            }else {
                infoIn.put(paraName, value);
            }
        }
        return infoIn;
    }

2 所有的模型层应该有个共同的接口,接收上面的infoIn,处理,然后返回数据。我们看看上面,也就能猜出返回的数据也应该是HashMap。

其接口应该是这样的:

public interface Action{
    public Map<String,Object> execute(Map<String,Object> infoIn);
}

3 我们写一个最简单的逻辑模型层。

package com.gc.action;

import java.util.HashMap;

public class HelloWorldAction  implements com.gd.action.Action{

    /**该方法用来实现没有传入动作时要处理的内容
    * @param infoIn
    * @return HashMap
    */

    private HashMap<String, Object> doInit(HashMap<String, Object> infoIn) {
        HashMap<String, Object> infoOut = infoIn;

        infoOut.put("msg", "HelloWorld");

        return infoOut;

    }

    @Override
    public HashMap<String, Object> doAction(HashMap<String, Object> infoIn) {
        // TODO Auto-generated method stub
        String action = (infoIn.get("action") == null) ? "" : (String)infoIn.get("action");
        HashMap<String, Object> infoOut = new HashMap<String, Object>() ;
        if (action.equals(""))
            infoOut = this.doInit(infoIn);
        else if (action.equals("show"))
            //....
        return infoOut;

    }
}

假定这个action的功能就只是显示一个helloword。

4 具体的模型层已经有了,从控制层给模型层传递的参数类型也有了。下来就是关键的一步,也就是在控制层指定请求的模型。

假定我们我请求上面那个HelloWorldAction,最后的信息返回给index.jsp那么我们可以发出下面的请求地址:

http://localhost:8700/Struts2Demo/gc/dfd.do?logicName=HelloWorldAction&forwardJsp=index

那个dfd是个随机的字符串。

通过

String ss = req.getServletPath();

就可以获得/gc/dif.do这个字符串。

而我们的HelloWorldAction位于

package com.gc.action;

OK,反射。

 Action action=null;
    String servletPath=req.getServletPath();
    String systemPath=servletPath.split("/")[1];  //systemPath 就是gc
    String logicActionName=req.getParameter("logicName");  // logicActionName 就是HelloWorldAction
    String actionPath=getActionPath(systemPath, logicActionName);
    action=(Action) Class.forName(actionPath).newInstance();
    Map<String, Object> infoOut=action.doAction(infoIn);   

    private String getActionPath(String systemPath,String actionName){
        String actionPath="";
        if (systemPath!=null)
            actionPath="com."+systemPath+".action."+actionName;

        return actionPath;
    }

这样一来,我们就取得了要访问的action,并且让调用了其doAction方法。

下面的任务就返回给视图层了:

Map<String, Object> infoOut=action.doAction(infoIn);
    infoOut.put("systemPath", systemPath);
    req.setAttribute("infoOut", infoOut);
    forwards(req, res);

    private void forwards(HttpServletRequest req, HttpServletResponse res) {
        // TODO Auto-generated method stub
        Map<String, Object> infoOut=(Map<String, Object>) req.getAttribute("infoOut");
        try {
            req.getRequestDispatcher("/"+infoOut.get("systemPath")+"/jsp/"+
                    infoOut.get("forwardJsp")+".jsp").forward(req, res);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

再看视图层:

<%@ page contentType="text/html; charset=GBK" language="java" import="java.sql.*" errorPage="" %>
<%@ page import="java.sql.*,java.util.*,javax.servlet.*,
         javax.servlet.http.*,java.text.*,java.math.*"%>

<%
    HashMap infoOut = (request.getAttribute("infoOut") == null) ? new HashMap() : (HashMap)request.getAttribute("infoOut");
    String msg = infoOut.get("msg") == null ? "" : (String)infoOut.get("msg");
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>采用新的框架实现HelloWorld输出</title>
<style type="text/css">
<!--
body {
    background-color: #FFFFFD;
    font-family: Verdana, "宋体";
    font-size: 12px;
    font-style: normal;
}
-->
</style>

</head>
<body leftmargin="0" topmargin="0">
<form name="form1" action="/myApp/do" method="post">

<H1><%=msg%><H1>

</form>

</body>
</html>

我们看看效果:

自己动手写web框架----1

似乎还不错

再看看我的项目工程图:

自己动手写web框架----1

这一节,我们很粗略地写了一个web框架,当然这个框架还很丑陋,就能显示个helloworld。我们在下一节在对他进行进一步的完善。