手动模拟一个简单的servlet容器的实现

新建一个java普通工程

工程目录结构如下:
在这里插入图片描述

新建webroot目录用于存放要访问的servlet以及静态资源

在这里插入图片描述

各个类的关系说明

在这里插入图片描述

主类(含main方法)HttpServer1主要功能

  • 通过socket进行服务器(main方法启动服务)端监听,等待远程客户端(浏览器)连接
  • 与客户端建立连接
  • 通过socket获取到输入inputstrem以及输出流outputstream
  • 用输入流实例化request对象,输出流实例化response对象
  • 关联(实例化)两个处理器ServletProcessor(处理servlet的处理器)和StaticResourceProcessor(处理静态资源的处理器)
  • 将request对象及response对象传给两个处理器进行处理,处理后分别返回结果给客户端

HttpServer1 完整代码

package com.xl.test;

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

public class HttpServer1 {
    
    

  /** WEB_ROOT is the directory where our HTML and other files reside.
   *  For this package, WEB_ROOT is the "webroot" directory under the working
   *  directory.
   *  The working directory is the location in the file system
   *  from where the java command was invoked.
   */
  // shutdown command
  private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";

  // the shutdown command received
  private boolean shutdown = false;

  public static void main(String[] args) {
    
    
    HttpServer1 server = new HttpServer1();
    server.await();
  }

  public void await() {
    
    
    ServerSocket serverSocket = null;
    int port = 8080;
    try {
    
    
      serverSocket =  new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
    }
    catch (IOException e) {
    
    
      e.printStackTrace();
      System.exit(1);
    }

    // Loop waiting for a request
    while (!shutdown) {
    
    
      Socket socket = null;
      InputStream input = null;
      OutputStream output = null;
      try {
    
    
        socket = serverSocket.accept();
        input = socket.getInputStream();
        output = socket.getOutputStream();
       
        String responseHeader = "HTTP/1.1 200 success\r\n" + "\r\n";
		output.write(responseHeader.getBytes());
        // create Request object and parse
        Request request = new Request(input);
        request.parse();

        // create Response object
        Response response = new Response(output);
        response.setRequest(request);

        // check if this is a request for a servlet or a static resource
        // a request for a servlet begins with "/servlet/"
        if (request.getUri().startsWith("/servlet/")) {
    
    
          ServletProcessor1 processor = new ServletProcessor1();
          processor.process(request, response);
        }
        else {
    
    
          StaticResourceProcessor processor = new StaticResourceProcessor();
          processor.process(request, response);
        }

        // Close the socket
        socket.close();
        //check if the previous URI is a shutdown command
        shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
      }
      catch (Exception e) {
    
    
        e.printStackTrace();
        System.exit(1);
      }
    }
  }
}

注意:一定要设置协议头,否则客户端无法正常接收到数据

String responseHeader = "HTTP/1.1 200 success\r\n" + "\r\n";
		output.write(responseHeader.getBytes());

Request完整代码

package com.xl.test;

import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;


public class Request implements ServletRequest {
    
    

  private InputStream input;
  private String uri;

  public Request(InputStream input) {
    
    
    this.input = input;
  }

  public String getUri() {
    
    
    return uri;
  }

  private String parseUri(String requestString) {
    
    
    int index1, index2;
    index1 = requestString.indexOf(' ');
    if (index1 != -1) {
    
    
      index2 = requestString.indexOf(' ', index1 + 1);
      if (index2 > index1)
        return requestString.substring(index1 + 1, index2);
    }
    return null;
  }

  public void parse() {
    
    
    // Read a set of characters from the socket
    StringBuffer request = new StringBuffer(2048);
    int i;
    byte[] buffer = new byte[2048];
    try {
    
    
      i = input.read(buffer);
    }
    catch (IOException e) {
    
    
      e.printStackTrace();
      i = -1;
    }
    for (int j=0; j<i; j++) {
    
    
      request.append((char) buffer[j]);
    }
    System.out.print(request.toString());
    uri = parseUri(request.toString());
  }

  /* implementation of the ServletRequest*/
  public Object getAttribute(String attribute) {
    
    
    return null;
  }

  public Enumeration getAttributeNames() {
    
    
    return null;
  }

  public String getRealPath(String path) {
    
    
    return null;
  }

  public RequestDispatcher getRequestDispatcher(String path) {
    
    
    return null;
  }

  public boolean isSecure() {
    
    
    return false;
  }

  public String getCharacterEncoding() {
    
    
    return null;
  }

  public int getContentLength() {
    
    
    return 0;
  }

  public String getContentType() {
    
    
    return null;
  }

  public ServletInputStream getInputStream() throws IOException {
    
    
    return null;
  }

  public Locale getLocale() {
    
    
    return null;
  }

  public Enumeration getLocales() {
    
    
    return null;
  }

  public String getParameter(String name) {
    
    
    return null;
  }

  public Map getParameterMap() {
    
    
    return null;
  }

  public Enumeration getParameterNames() {
    
    
    return null;
  }

  public String[] getParameterValues(String parameter) {
    
    
    return null;
  }

  public String getProtocol() {
    
    
    return null;
  }

  public BufferedReader getReader() throws IOException {
    
    
    return null;
  }

  public String getRemoteAddr() {
    
    
    return null;
  }

  public String getRemoteHost() {
    
    
    return null;
  }

  public String getScheme() {
    
    
   return null;
  }

  public String getServerName() {
    
    
    return null;
  }

  public int getServerPort() {
    
    
    return 0;
  }

  public void removeAttribute(String attribute) {
    
    
  }

  public void setAttribute(String key, Object value) {
    
    
  }

  public void setCharacterEncoding(String encoding)
    throws UnsupportedEncodingException {
    
    
  }

}

Response完整代码

package com.xl.test;

import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletResponse;
import javax.servlet.ServletOutputStream;

public class Response implements ServletResponse {
    
    

  private static final int BUFFER_SIZE = 1024;
  Request request;
  OutputStream output;
  PrintWriter writer;

  public Response(OutputStream output) {
    
    
    this.output = output;
  }

  public void setRequest(Request request) {
    
    
    this.request = request;
  }

  /* This method is used to serve a static page */
  public void sendStaticResource() throws IOException {
    
    
    byte[] bytes = new byte[BUFFER_SIZE];
    FileInputStream fis = null;
    try {
    
    
    	
//    	String responseHeader = "HTTP/1.1 200 success\r\n" + "\r\n";
//		output.write(responseHeader.getBytes());
    	
    	
      /* request.getUri has been replaced by request.getRequestURI */
      File file = new File(Constants.WEB_ROOT, request.getUri());
      fis = new FileInputStream(file);
      /*
         HTTP Response = Status-Line
           *(( general-header | response-header | entity-header ) CRLF)
           CRLF
           [ message-body ]
         Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
      */
      int ch = fis.read(bytes, 0, BUFFER_SIZE);
      while (ch!=-1) {
    
    
        output.write(bytes, 0, ch);
        ch = fis.read(bytes, 0, BUFFER_SIZE);
      }
    }
    catch (FileNotFoundException e) {
    
    
      String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
        "Content-Type: text/html\r\n" +
        "Content-Length: 23\r\n" +
        "\r\n" +
        "<h1>File Not Found</h1>";
      output.write(errorMessage.getBytes());
    }
    finally {
    
    
      if (fis!=null)
        fis.close();
    }
  }


  /** implementation of ServletResponse  */
  public void flushBuffer() throws IOException {
    
    
  }

  public int getBufferSize() {
    
    
    return 0;
  }

  public String getCharacterEncoding() {
    
    
    return null;
  }

  public Locale getLocale() {
    
    
    return null;
  }

  public ServletOutputStream getOutputStream() throws IOException {
    
    
    return null;
  }

  public PrintWriter getWriter() throws IOException {
    
    
    // autoflush is true, println() will flush,
    // but print() will not.
    writer = new PrintWriter(output, true);
    return writer;
  }

  public boolean isCommitted() {
    
    
    return false;
  }

  public void reset() {
    
    
  }

  public void resetBuffer() {
    
    
  }

  public void setBufferSize(int size) {
    
    
  }

  public void setContentLength(int length) {
    
    
  }

  public void setContentType(String type) {
    
    
  }

  public void setLocale(Locale locale) {
    
    
  }
}

ServletPorcessor1完整代码

package com.xl.test;

import java.net.URL;
import java.net.URLClassLoader;
import java.net.URLStreamHandler;
import java.io.File;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class ServletProcessor1 {
    
    

  public void process(Request request, Response response) {
    
    

    String uri = request.getUri();
    String servletName = uri.substring(uri.lastIndexOf("/") + 1);
    URLClassLoader loader = null;

    try {
    
    
      // create a URLClassLoader
      URL[] urls = new URL[1];
      URLStreamHandler streamHandler = null;
      File classPath = new File(Constants.WEB_ROOT);
      // the forming of repository is taken from the createClassLoader method in
      // org.apache.catalina.startup.ClassLoaderFactory
      String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;
      // the code for forming the URL is taken from the addRepository method in
      // org.apache.catalina.loader.StandardClassLoader class.
      urls[0] = new URL(null, repository, streamHandler);
      loader = new URLClassLoader(urls);
    }
    catch (IOException e) {
    
    
      System.out.println(e.toString() );
    }
    Class myClass = null;
    try {
    
    
      myClass = loader.loadClass(servletName);
    }
    catch (ClassNotFoundException e) {
    
    
      System.out.println(e.toString());
    }

    Servlet servlet = null;

    try {
    
    
      servlet = (Servlet) myClass.newInstance();
      servlet.service((ServletRequest) request, (ServletResponse) response);
    }
    catch (Exception e) {
    
    
      System.out.println(e.toString());
    }
    catch (Throwable e) {
    
    
      System.out.println(e.toString());
    }

  }
}

StaticResourceProcessor完整代码

package com.xl.test;

import java.io.IOException;

public class StaticResourceProcessor {
    
    

  public void process(Request request, Response response) {
    
    
    try {
    
    
      response.sendStaticResource();
    }
    catch (IOException e) {
    
    
      e.printStackTrace();
    }
  }
}

Constants完整代码

package com.xl.test;

import java.io.File;

public class Constants {
    
    
  public static final String WEB_ROOT =
    System.getProperty("user.dir") + File.separator  + "webroot";
}

PrimitiveServlet完整代码

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

public class PrimitiveServlet implements Servlet {
    
    

  public void init(ServletConfig config) throws ServletException {
    
    
    System.out.println("init");
  }

  public void service(ServletRequest request, ServletResponse response)
    throws ServletException, IOException {
    
    
    System.out.println("from service");
    PrintWriter out = response.getWriter();
    out.println("Hello. Roses are red.");
    out.print("Violets are blue.");
  }

  public void destroy() {
    
    
    System.out.println("destroy");
  }

  public String getServletInfo() {
    
    
    return null;
  }
  public ServletConfig getServletConfig() {
    
    
    return null;
  }

}

index.html完整代码

<html>
<head>
<title>Welcome to BrainySoftware</title>
</head>
<body>

<br>
Welcome to BrainySoftware.
</body>
</html>

test.html完整代码

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>测试文件</title>
</head>
<body> 
<table border="1">
    <tr style="color:#00FF00">
        <th>Header 1</th>
        <th>Header 2</th>
    </tr>
    <tr style="color:#00FFFF">
        <td>row 1, cell 1</td>
        <td>row 1, cell 2</td>
    </tr>
    <tr style="color:#FF00FF">
        <td>row 2, cell 1</td>
        <td>row 2, cell 2</td>
    </tr>
</table>
</body>
</html>

测试

启动HttpServer1中的main方法

在这里插入图片描述

浏览器中输入http://localhost:8080/servlet/PrimitiveServlet,测试访问servlet

如果浏览器收到 Hello. Roses are red,则说明访问servlet成功

结果

在这里插入图片描述

测试访问静态资源

浏览器中分别输入http://localhost:8080/index.html测试index.html文件以及http://localhost:8080/test.html测试 test.html文件
在这里插入图片描述
在这里插入图片描述

结果显示访问静态资源成功。

参考:《how tomcat works》

猜你喜欢

转载自blog.csdn.net/qq_29025955/article/details/119418348