1. 需要安装jdk和java ee sdk中的glassfish5/glassfish/modules/javax.servlet-api.jar
  2. 运行项目,SimpleContainer—>main方法
  3. 浏览器输入http://localhost:8080/servlet/Test,完成

SimpleContainer.java

public class SimpleContainer {

    private boolean shutdown = false;
    private static Logger log = Logger.getLogger(SimpleContainer.class.getName());

    public static void main(String[] args) {
        File f = new File(".");
        System.out.println(f.getAbsolutePath());
        SimpleContainer server = new SimpleContainer();

        server.start();

    }

    private void start() {
        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(8080, 10,
                    InetAddress.getByName("localhost"));
        } catch (IOException e) {
            System.out.println("Server starts failed");
            e.printStackTrace();
            System.exit(1);
        }
        log.info("Server starts successfully.");
        service(serverSocket);

    }

    private void service(ServerSocket serverSocket) {
        while (!shutdown) {
            try {
                processRequest(serverSocket);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    private void processRequest(ServerSocket serverSocket) throws IOException {

        log.info("waitting for incoming request ... ");
        Socket socket = serverSocket.accept();
        log.info("receive a request from "
                + socket.getRemoteSocketAddress().toString());
        InputStream in = socket.getInputStream();
        BaseRequest request = new BaseRequest(in);
        log.info("Request Object ready!");

        OutputStream out = socket.getOutputStream();
        BaseResponse response = new BaseResponse(out);
        ServletProcessor.processServletRequest(request, response);


        socket.close();

    }
}

BaseRequest.java

public class BaseRequest implements HttpServletRequest {

    private InputStream inputStream;
    private String uri;
    private StringBuffer requestContentBuffer = new StringBuffer(2048);

    public BaseRequest(InputStream in) {
        this.inputStream = in;
        prepareContent();
        parseAndSetUri();
    }



    private void prepareContent() {

        byte[] buffer = new byte[2048];
        int i = -1;

        try {
            i = inputStream.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (int k = 0; k < i; k++) {
            requestContentBuffer.append((char) buffer[k]);
        }
        System.out.println(requestContentBuffer.toString());

    }

    private void parseAndSetUri() {
        String requestString = requestContentBuffer.toString();
        int index1 = requestString.indexOf(' ');
        int index2 = -1;
        if (index1 != -1) {
            index2 = requestString.indexOf(' ', index1 + 1);
        }
        this.uri = (index2 > index1) ? requestString.substring(index1 + 1,
                index2) : null;

    }

    //其他接口空实现方法,很多

} 

BaseResponse.java

public class BaseResponse implements HttpServletResponse {

    private OutputStream outputStream;

    public BaseResponse(OutputStream out) {
        this.outputStream = out;
    }


    @Override
    public PrintWriter getWriter() throws IOException {
        return new PrintWriter(this.outputStream);
        //return  null;
    }

    //其他接口空实现方法,很多
}

ServletProcessor.java

public class ServletProcessor {

    private static Logger log = Logger.getLogger(ServletProcessor.class.getName());

    public static void processServletRequest(BaseRequest request,
                                             BaseResponse response) {
        String uri = request.getUri();
        String servletName = MappingHelper.resolve(uri);
        log.info("Processing servlet: " + servletName);

        Servlet servlet = loadServlet(servletName);

        callService(servlet, request, response);

    }

    private static URLClassLoader createUrlClassLoader() {

        URLClassLoader loader = null;
        try {
            URL[] urls = new URL[1];
            URLStreamHandler streamHandler = null;
            File classPath = new File(Constant.RESOURCE_ROOT);

            // org.apache.catalina.startup.ClassLoaderFactory  
            String repository = (new URL("file", null,
                    classPath.getCanonicalPath() + File.separator)).toString();
            urls[0] = new URL(null, repository, streamHandler);
            loader = new URLClassLoader(urls);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return loader;
    }

    private static Servlet loadServlet(String servletName) {
        URLClassLoader loader = createUrlClassLoader();
        Servlet servlet = null;
        try {
            @SuppressWarnings("unchecked")
            Class<Servlet> servletClass = (Class<Servlet>) loader
                    .loadClass(servletName);
            servlet = (Servlet) servletClass.newInstance();
        } catch (Exception e){
            e.printStackTrace();
        }
        return servlet;
    }

    private static void callService(Servlet servlet, ServletRequest request,
                                    ServletResponse response) {
        try {
            servlet.service(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

} 

MappingHelper.java

public class MappingHelper {

    public static Properties requestMapping;
    static {
        requestMapping = new Properties();
        try {
            File f = new File(Constant.MAPPING_FILE);
            System.out.println(f.getAbsolutePath());
            requestMapping.load(new FileInputStream(f));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String resolve(String requestPath) {
        return requestMapping.getProperty(requestPath);
    }

}

Constant.java

public  class Constant {
    static String MAPPING_FILE = "out/production/java/mapping.txt";
    static String RESOURCE_ROOT = "out/production/";
}

mapping.txt

/servlet/Test=TestServlet

TestServlet.java

public class TestServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("TestServlet doGet.........................");
        System.out.println(this.getClass().getClassLoader().getParent());
        try{
            //BaseResponse bresp = (BaseResponse) resp;
            String str = "HTTP/1.1 200 OK\n" +
                    "Server: Microsoft-IIS/5.00000\n" +
                    "Date: Thu, 07 Jul 2005 13:08:16 GMT\n\n" +

                    "this is from TestServlet\n";
            PrintWriter out = resp.getWriter();
            out.write(str);
            out.flush();
            out.close();

        }catch (Exception e){}
    }
}

项目完整地址:https://u695858.pipipan.com/fs/695858-231499617
密码:778887

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐