手写tomcat系列2-第一个Servlet容器

插曲:加班回家写博客花了两个小时,中间网页挂了好几次,浪费了一个小时,完成时已经十一点多了,计划写两篇,只能完成一篇,累,但有收获,明天继续,本实现有安全问题,将在系列3中优化。

从大局开始先上UML图:
1.HttpServer1:负责处理接受请求,依赖(dependency)Request类和Response类;关联(association)ServletProcessor1和StaticResourceProcessor;
2.ServletProcessor1:处理servlet请求,依赖(dependency)Request类和Response类。有点小干货,有兴趣下面有总结。
3.StaticResourceProcessor:处理静态文件请求,依赖(dependency)Request类和Response类。
4.request:不解释,直接去看源码。
5.Response:不解释,直接去看源码。
6.Constants:常量类。
UML图
HttpServer1 类代码

public class HttpServer1 {
 // 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();
    // create Request object and parse 获取请求中的uri
    Request request = new Request(input);
    request.parse();
    // create Response object
    Response response = new Response(output);
    response.setRequest(request);
    // a request for a servlet begins with "/servlet/"
    if (request.getUri().startsWith("/servlet/")) {
     // 动态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);
   }
  }
 }
}

StaticResourceProcessor

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

ServletProcessor1
功能总结:
1.初始化ClassLoader,用于加载servlet类。
2.通过ClassLoader加载Class,并实例化对象。
3.执行servlet的service方法。
4.下面两行代码干货小技巧

URLStreamHandler streamHandler = null;
/**streamHandler参数的作用只是告诉构造函数传参类型,以避免构造函数混淆。*/
urls[0] = new URL(null, repository, streamHandler);

public class ServletProcessor1 {
 public void process(Request request, Response response) {
  String uri = request.getUri();//URI格式:   /servlet/servletName
  String servletName = uri.substring(uri.lastIndexOf("/") + 1);
  URLClassLoader loader = null;
  /**
   * create a URLClassLoader
   * process 方法加载 servlet。
   *  要完成这个,你需要创建一个类加载器并告诉这个类加载器要加载的类的位置。
   *  对于这个 servlet 容器,类加载器直接在 Constants 指向的目录里边查找。
   *  WEB_ROOT 就是指向工作目录下面的 webroot 目录(repository)。
   */ 
  try {
   URL[] urls = new URL[1];
   
   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.
   URLStreamHandler streamHandler = null;
   /**
    *  streamHandler参数的作用只是告诉构造函数传参类型,以避免构造函数混淆。
    */ 
   urls[0] = new URL(null, repository, streamHandler);
   /**
    * 要加载 servlet,你可以使用 java.net.URLClassLoader 类,它是 java.lang.ClassLoader类的一个直接子类。
    * 这里 urls 是一个 java.net.URL 的对象数组,这些对象指向了加载类时候查找的位置。任何以/结尾的 URL 都假设是一个目录。
    * 否则,URL 会 Otherwise  the URL 假定是一个将被下载并在需要的时候打开的 JAR 文件。 
    **/
   loader = new URLClassLoader(urls);
  } catch (IOException e) {
   System.out.println(e.toString());
  }
  Class<?> myClass = null;
  try {
   // 加载servlet
   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());
  }
 }
}

Constants

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

Request

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

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 {
   /* 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) {
   // 如果找不到,返回404
   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) {
 }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值