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

Tomcat :一个简单的Servlet容器

程序员文章站 2022-05-23 17:36:00
...

Servlet容器处理Servlet请求的简单流程图如下图所示:

 


Tomcat :一个简单的Servlet容器
 UML类图如下图所示:



Tomcat :一个简单的Servlet容器

 

HttpServletProcessor类:

 

package com.flyer.tomcat.first;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 一个简单的http服务器
 * <p />
 * 
 * @author Administrator
 */
public class HttpServer {
    
    private static Logger logger = LoggerFactory.getLogger(HttpServer.class);

    private final static String SHUTDOWN_COMMAND = "/shutdown";
    
    public final static String WEB_ROOT = System.getProperty("user.dir") + File.separator + "webroot";

    private boolean shutdown = false;

    public static void main(String[] args) {
        logger.info("server start");
        HttpServer server = new HttpServer();
        try {
            server.await();
        } catch (IOException e) {
            logger.error("io exception",e);
        }
    }

    private void await() throws IOException {

        ServerSocket serverSocket = new ServerSocket(9090,1,InetAddress.getByName("127.0.0.1"));
        InputStream input = null;
        OutputStream output = null;
        while (!shutdown) {
            Socket socket = null;
            try {
                socket = serverSocket.accept();
                input = socket.getInputStream();
                output = socket.getOutputStream();
                Request request = new Request(input);
                request.parse();
                Response response = new Response(output);
                response.setRequest(request);
                
                if(request.getUri().startsWith("/servlet")){
                    ServletProcessor servletProcessor = new ServletProcessor();
                    servletProcessor.process(request, response);
                }else{
                    StaticResourceProcessor processor = new StaticResourceProcessor();
                    processor.process(request, response);
                }
                
                
                socket.close();

                shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                
                input.close();
                output.close();
            }
        }

    }

}
 

代码

 

package com.flyer.tomcat.first;

import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Servlet请求处理器
 * <p />
 * 
 * @author Administrator
 */
public class ServletProcessor implements Processor {

    private static Logger logger = LoggerFactory.getLogger(ServletProcessor.class);

    // private final static String FILE_PATH = Constants.getClassPath() + File.separator + "com" +
    // File.separator
    // + "flyer" + File.separator + "tomcat" + File.separator + "first" + "" + File.separator;

    @Override
    public void process(HttpServletRequest request, HttpServletResponse response) {
        Request internalRequest = (Request) request;
        String uri = internalRequest.getUri();
        String servletClassName = uri.substring(uri.lastIndexOf("/") + 1);
        URLClassLoader classLoader = null;
        File file = new File(Constants.getClassPath());
        URL url = null;
        try {
            url = file.toURI().toURL();
        } catch (MalformedURLException e) {
            logger.error("convert to url error", e);
        }
        logger.info("url:" + url);
        URL[] urls = new URL[1];
        urls[0] = url;
        classLoader = new URLClassLoader(urls);
        Class<?> myClass = null;
        try {
            myClass = classLoader.loadClass(servletClassName);
        } catch (ClassNotFoundException e) {
            logger.error("class not found", e);
        }
        Servlet servlet = null;
        if (myClass != null) {
            try {
                servlet = (Servlet) myClass.newInstance();
            } catch (InstantiationException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            try {
                servlet.service(request, response);
            } catch (ServletException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

}
 

改进:

 

添加facade类,为的是Request类中的parse方法和getUri方法不被Servlet类访问。

 


Tomcat :一个简单的Servlet容器