實現一個簡單的Tomcat

scu醬油仔發表於2018-11-06

實現一個簡單的Tomcat

1. Tomcat作用

我們的web應用會執行在Tomcat中,那麼顯然請求必定是先到達Tomcat的,Tomcat對於請求實際上會進行如下的處理:

  • 提供Socket服務:Tomcat的啟動,必然是Socket服務,支援http協議。
  • 進行請求的分發:一個Tomcat可以為多個web應用提供服務,那麼就需要把url下發到不同的web應用。
  • 需要將請求和響應封裝成request和response:我們在寫後端程式碼的時候都是直接使用request和response的,這是因為Tomcat已經做好了。

下面我們就自己來實現這三步。

2. 實現程式碼

專案結構:

  src
    └─mytomcat
            BookServlet.java
            CarServlet.java
            MyRequest.java
            MyResponse.java
            MyServlet.java
            MyTomcat.java
            ServletMapping.java
            ServletMappingConfig.java

2.1 封裝http請求和響應

package mytomcat;

import java.io.IOException;
import java.io.InputStream;

/**
 * 封裝http請求
 */
public class MyRequest {
    
    private String url;
    private String method;
    
    public MyRequest(InputStream inputStream) throws IOException {
        
        String httpRequest = "";
        byte[] httpRequestBytes = new byte[1024];
        int length = 0;
        if((length = inputStream.read(httpRequestBytes)) > 0) {
            httpRequest = new String(httpRequestBytes, 0, length);
        }
        
        String httpHead = httpRequest.split("
")[0];
        url = httpHead.split("\s")[1];
        method = httpHead.split("\s")[0];
        
        System.out.println(this.toString());
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getMethod() {
        return method;
    }

    public void setMethod(String method) {
        this.method = method;
    }
    
    @Override
        public String toString() {
            return "MyRequest -- url:" + url + ",method:" + method;
        }

}
package mytomcat;

import java.io.IOException;
import java.io.OutputStream;

/**
 * 封裝http響應
 */
public class MyResponse {
    
    private OutputStream outputStream;
    
    public MyResponse (OutputStream outputStream) {
        this.outputStream = outputStream;
    }
    
    public void write(String content) throws IOException {
        StringBuffer httpResponse = new StringBuffer();
        httpResponse.append("HTTP/1.1 200 OK
")
                    .append("Content-Type: text/html
")
                    .append("
")
                    .append(content);
        
        outputStream.write(httpResponse.toString().getBytes());
        outputStream.close();
    }

}

2.2 實現不同的Servlet

package mytomcat;
/**
 * Servlet抽象類
 */
public abstract class MyServlet {
    
    public abstract void doGet(MyRequest myRequest, MyResponse myResponse);
    
    public abstract void doPost(MyRequest myRequest, MyResponse myResponse);
    
    public void service(MyRequest myRequest, MyResponse myResponse) {
        if(myRequest.getMethod().equalsIgnoreCase("POST")) {
            doPost(myRequest, myResponse);
        }else if(myRequest.getMethod().equalsIgnoreCase("GET")) {
            doGet(myRequest, myResponse);
        }
    }
}
package mytomcat;

import java.io.IOException;

/**
 * 處理操作`書`的http請求
 */
public class BookServlet extends MyServlet {

    @Override
    public void doGet(MyRequest myRequest, MyResponse myResponse) {
        try {
            myResponse.write("[get] book...");
        }catch(IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doPost(MyRequest myRequest, MyResponse myResponse) {
        try {
            myResponse.write("[post] book...");
        }catch(IOException e) {
            e.printStackTrace();
        }
    }

}
package mytomcat;

import java.io.IOException;

/**
 * 處理操作`車`的http請求
 */
public class CarServlet extends MyServlet {

    @Override
    public void doGet(MyRequest myRequest, MyResponse myResponse) {
        try {
            myResponse.write("[get] car...");
        }catch(IOException e) {
            e.printStackTrace();
        }
        
    }

    @Override
    public void doPost(MyRequest myRequest, MyResponse myResponse) {
        try {
            myResponse.write("[post] car...");
        }catch(IOException e) {
            e.printStackTrace();
        }
    }

}

2.3 定義Servlet對映POJO類

package mytomcat;

public class ServletMapping {
    
    private String servletName;
    private String url;
    private String className;
    
    public ServletMapping(String servletName, String url, String className) {
        super();
        this.servletName = servletName;
        this.url = url;
        this.className = className;
    }

    public String getServletName() {
        return servletName;
    }

    public void setServletName(String servletName) {
        this.servletName = servletName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }
    
}

2.4 配置Servlet對映關係

package mytomcat;

import java.util.ArrayList;
import java.util.List;

/**
 * 配置請求url和處理的servlet的對應關係
 */
public class ServletMappingConfig {
    
    public static List<ServletMapping> servletMappingList = new ArrayList<>();;
    
    static {
        servletMappingList.add(new ServletMapping("Book", "/book", "mytomcat.BookServlet"));
        servletMappingList.add(new ServletMapping("Car", "/car", "mytomcat.CarServlet"));
    }

}

2.5 主類

package mytomcat;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

public class MyTomcat {
    private int port;
    //儲存請求url和處理請求servlet的對應關係
    private Map<String, String> urlServletMap = new HashMap<String, String>();
    
    public MyTomcat(int port) {
        this.port = port;
    }
    
    public void start() {
        initServletMapping();
        
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(port);
            System.out.println("MyTomcat is start...
監聽埠:" + port);
            
            while(true) {
                System.out.println("等待請求...");
                Socket socket = serverSocket.accept();
                InputStream inputStream = socket.getInputStream();
                OutputStream outputStream = socket.getOutputStream();
                
                MyRequest myRequest = new MyRequest(inputStream);
                MyResponse myResponse = new MyResponse(outputStream);
                
                //請求分發
                disPatch(myRequest, myResponse);
                socket.close();
            }
        }catch(IOException e) {
            e.printStackTrace();
        }finally {
            if(serverSocket != null) {
                try {
                    serverSocket.close();
                }catch(IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    //初始化url和處理的servlet的對應關係
    private void initServletMapping() {
        for(ServletMapping servletMapping: ServletMappingConfig.servletMappingList) {
            urlServletMap.put(servletMapping.getUrl(), servletMapping.getClassName());
        }
    }
    
    //分發處理請求
    private void disPatch(MyRequest myRequest, MyResponse myResponse) {
        String className = urlServletMap.get(myRequest.getUrl());
        
        //反射
        try {
            Class<MyServlet> myServletClass = (Class<MyServlet>) Class.forName(className);
            MyServlet myServlet = myServletClass.newInstance();
            
            myServlet.service(myRequest, myResponse);
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        MyTomcat myTomcat = new MyTomcat(8080);
        myTomcat.start();
    }
}

3. 測試

執行MyTomcat主類,然後在瀏覽器輸入http://localhost:8080/car,可以看到返回[get] car...,大功告成。

原始碼地址:

https://github.com/WangJun-SCU/mytomcat

相關文章