欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

手写tomcat透彻理解Servlet实现原理

程序员文章站 2022-04-02 18:15:20
...

疑问:

  1. 为什么要配置一个web.xml文件?

  2. 为什么一定要继承Servlet,不继承不行吗?

  3. 为什么一定要重写doPost/doGet方法?

  4. HttpRequest和HttpResponse是哪里冒出来的,自己从来没有new过?

  5. 在浏览器输入url是如何被转换为调用java方法的?

手写tomcat透彻理解Servlet实现原理

  代码结构如下:

手写tomcat透彻理解Servlet实现原理

http包中的代码

package com.zuojie.http;

import java.io.OutputStream;

public class ZuojieReponse {

    private OutputStream os;

    public ZuojieReponse(OutputStream os){
        this.os=os;
    }

    public void write(String outString)throws Exception{
        os.write(outString.getBytes());

    }

}

 

package com.zuojie.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;

public class ZuojieRequest {
    private String method;
    private String url;
    //构造方法
    public ZuojieRequest(InputStream is){
        //http协议,就是一串字符串
      //  System.out.println();
        try {
            String content="";
            byte [] buff= new byte[1024];
            int len=0;
            if((len = is.read(buff))>  0){
                content= new String (buff,0,len);
                System.out.println(content);
            }
            String line=content.split("\\n")[0];
            String [] arr= line.split("\\s");
            this.method=arr[0];
            this.url=arr[0].split("\\?")[0];//这里目前有点问题。希望可以在评论分享



        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public String getMethod(){
        return this.method;
    }

    public  String getUrl(){
        return  this.url;
    }

    public Map <String,String > getParmenter(){
        return null;
    }
}
package com.zuojie.servlet;

import com.zuojie.http.ZuojieReponse;
import com.zuojie.http.ZuojieRequest;
import com.zuojie.http.ZuojieServlet;

public class MiniServlet extends ZuojieServlet {
    @Override
    public void doGet(ZuojieRequest request, ZuojieReponse reponse) throws Exception {
        this.doPost(request,reponse);
    }

    @Override
    public void doPost(ZuojieRequest request, ZuojieReponse reponse) throws Exception {
        reponse.write("this is MiniTomcat");

    }
}
package com.zuojie.servlet;

import com.zuojie.http.ZuojieReponse;
import com.zuojie.http.ZuojieRequest;
import com.zuojie.http.ZuojieServlet;

public class MiniTwoServlet extends ZuojieServlet{
    @Override
    public void doGet(ZuojieRequest request, ZuojieReponse reponse) throws Exception {
        this.doPost(request,reponse);
    }

    @Override
    public void doPost(ZuojieRequest request, ZuojieReponse reponse) throws Exception {
        reponse.write("this is MiniTwoServlet");
    }
}

tomcat中的代码 

package com.zuojie.tomcat;


import com.zuojie.http.ZuojieReponse;
import com.zuojie.http.ZuojieRequest;
import com.zuojie.http.ZuojieServlet;

import java.io.FileInputStream;
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;
import java.util.Properties;

/**
 * author:佐杰
 */

public class ZuojieTomcat {
    private int port=9090;//定义一个默认的端口
    private ServerSocket server;
    private Map<String,ZuojieServlet> servletMappping=new HashMap<String,ZuojieServlet>();
    private Properties webxml=new Properties();

    //1.加载配置文件,初始化ServletMaping
    private void init(){
        //1.加载web.xml,同是初始化servletmaping对象
        try {
            String WEB_INF=this.getClass().getResource("/").getPath();
            FileInputStream fis=new FileInputStream(WEB_INF+"web.properties");
            webxml.load(fis);

            for (Object key:webxml.keySet()) {
                String k=key.toString();
                if(k.endsWith(".url")){
                  String servletName=  k.replaceAll("\\.url$","");

                  String url=webxml.getProperty("k");

                  String className=webxml.getProperty(servletName+".className");

                  ZuojieServlet obj= (ZuojieServlet) Class.forName(className).newInstance();

                  servletMappping.put(url,obj);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void process(Socket client) throws  Exception{
        //3.获取到Socket对象,将socket getInputStream()封装成request
        //                    将socket getInputStream()封装成response

        InputStream is= client.getInputStream();
        OutputStream out=client.getOutputStream();

        ZuojieRequest request=new ZuojieRequest(is);
        ZuojieReponse reponse=new ZuojieReponse(out);

        //想办法拿到用户请求的url才行

        System.out.println("===="+request.getMethod());
        String url=request.getUrl();
        if(servletMappping.containsKey(url)) {
            servletMappping.get(request.getMethod()).service(request, reponse);
        }else {
            reponse.write("404-NOT-FOUND");
        }

        out.flush();//刷新
        out.close();
        //为什么要关闭client,因为HTTP请求都是采用短链接
        client.close();
    }

    //4.实现动态调用doGet/doPost方法,并且能够自定义返回结果
    public void start(){
        init();
        try {
            server=new ServerSocket(this.port);
            System.out.println("Zuojie Tomcat 已启动,监听的端口是"+this.port);
           // Socket socket = server.accept();
          //  System.out.println(socket);
            //2.等待用户请求,用一个死循环来等待用户请求
            while(true){
                try {
                    Socket client = server.accept();
                    process(client);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        new ZuojieTomcat().start();

    }

}

web.properties

servlet.one.url=/MiniServlet.do
servlet.one.className=com.zuojie.servlet.MiniServlet

servlet.two.url=/MiniTwoServlet.do
servlet.two.className=com.zuojie.servlet.MiniTwoServlet