手写Tomcat

需求分析

根据Tomcat的基本功能分析,基本需求包括:

  • 监听端口,接受外部请求
  • 多线程并发处理多个请求
  • 解析HTTP请求,根据URL找到对应的Servlet
  • 扫描Web目录,解析web.xml配置,加载开发者实现的Servlet类,生成对象并调用其service方法得到response返回给客户端

代码实现

接受请求的服务端

通过scoket监听端口,将接受到的请求提交到线程池处理。线程池中的任务为具体的处理逻辑。包括解析HTTP请求,匹配内部的Servlet。这个过程中的难点在于实现自己的HttpServletResponse类。查资料目前只看到Tomcat内部有实现,可以参考实现一个简化的版本。

public void server() throws Exception {
        ExecutorService executor = Executors.newCachedThreadPool();
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("tomcat start");
        while (!serverSocket.isClosed()) {
            final Socket request = serverSocket.accept();
            executor.execute(() -> {
                try {
                    InputStream inputStream = request.getInputStream();
                    System.out.println("accecpt request");
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
                    String msg = null;
                    List msgList = new LinkedList<>();
                    while ((msg = reader.readLine()) != null) {
                        if (msg.length() == 0) {
                            break;
                        }
                        msgList.add(msg);
//                        System.out.println(msg);
                    }
                    HttpServletRequest servletRequest = null; //fixme
                    HttpServletResponse servletResponse = null; //fixme
                    Servlet servlet = new ProjectUtil().servletMapping.get("my-servlet-1.0-SNAPSHOT");
                    servlet.service(servletRequest, servletResponse);
                    // 可以通过outputStream来模拟返回数据
                    OutputStream outputStream = request.getOutputStream();
                    outputStream.write("Hello World".getBytes());
                    outputStream.flush();
                } catch (IOException|ServletException e) {
                    e.printStackTrace();
                }finally {

                }
            });
        }
        serverSocket.close();
    }

加载开发者的Servlet类

配置文件用来表明Web目录名称和对应的Servlet类的位置,此处省略。只加载指定的Servlet类。使用URLClassLoader加载之后,MyServlet类就可以在当前JVM中访问到。

private void loadServlet() throws Exception {
        String filePath = "/home/ubuntu/space/test/myservlet/target/my-servlet-1.0-SNAPSHOT/WEB-INF/classes/";
        File classPath = new File(filePath);
        String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();
        URLClassLoader loader = new URLClassLoader(new URL[]{new URL(repository)});
        for (Map.Entry entry : properties.entrySet()) {
            String servletName = entry.getKey().toString();
            String servletClassName = entry.getValue().toString();
            Class servletClass = loader.loadClass("controller.MyServlet");
            System.out.println(servletClass.getName());
            Servlet servlet = (Servlet) servletClass.newInstance();
            servletMapping.put(servletName, servlet);
        }
    }

上述代码中,将加载到的类通过Java的反射机制生成对象存储在ServletMapping中,供请求处理时进行选择使用。

实现自己的Servlet

继承HttpServlet类,实现自己的MyServlet类。通过Maven打包成war包,部署到上述Tomcat指定的目录下。主要代码如下:

public class MyServlet extends HttpServlet {


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("MyServlet doGet");
        OutputStream outputStream = resp.getOutputStream();
        String name = req.getParameter("name");
        String hello = "Hello " + name;
        outputStream.write(hello.getBytes());
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("MyServlet doPost");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if ("GET".equals(req.getMethod())) {
            this.doGet(req, resp);
        } else {
            this.doPost(req, resp);
        }
    }
}

部署完成后,运行Tomcat,在浏览器中输入请求,可以在控制台中看到MyServlet的输出。要实现根据浏览器输入,执行特定的逻辑,需要实现自己的HttpServletResponse类。

总结

主要用到了Java中的Socket、线程池、类加载器、反射等内容。

你可能感兴趣的:(手写Tomcat)