即便再简陋的服务器也是服务器,今天就来循着书本的第二章来看看如何实现一个servlet容器。

背景知识

  既然说到servlet容器这个名词,我们首先要了解它到底是什么。

servlet

  相比你或多或少有所了解。servlet是用java编写的服务器端程序,主要功能在于交互式地浏览和修改数据,生成动态Web内容。狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者。

容器

  容器的概念很大,在这里可以理解为能够管理对象(servlet)的生命周期,对象与对象之间的依赖关系。

  基于对以上两个概念的解释,那么对于serelvet容器的概念也就不再那么陌生了。

servlet容器

  就是创建、管理servlet规范中相关对象、生命周期的应用程序。

Servlet接口

  servlet是一种编程规范,要实现servlet编程需要用到javax.servlet和javax.servlet.http。所有的servlet程序都需要实现或继承自实现了javax.servlet.servlet接口。

Servlet接口的方法

  • init():servlet容器的初始化方法,该方法只会被调用一次;
  • service():不同于init只会触发一次,service在客户端请求后就会被调用。同时需要传入参数servletRequest和servletResponse。从字面意思就能知道,servletRequest携带了客户端发送的HTTP请求的信息,而servletResponse则用于封装servlet的响应信息。
  • destroy():当servlet实例调用完毕要被移除时,destroy方法将被调用。
  • getServletConfig():该方法用于取得<servlet> <init-param>配置的参数
  • getServletInfo():该方法提供有关servlet的信息,如作者、版本、版权。

servlet容器的职责

  • 第一次调用servlet时,需要载入serlvet类并调用init方法;
  • 针对客户端的request请求,创建一个servletRequest对象和一个servletResponse对象;
  • 传参servletRequest和servletResponse,调用service方法;
  • 当关闭servlet类时,调用destroy方法。

简陋的servlet容器

  之所以说是简陋的servlet容器,因为这里并没有实现servlet所有的方法,该容器只能支持很简单的servlet,也没有init方法和destroy方法。主要实现功能如下:

  • 等待HTTP请求;
  • 创建serlvetRequest和servletResponse对象;
  • 能够分别处理静态资源和servlet,当客户端请求静态资源时,则调用StaticResourceProcessor对象的process方法;当请求为serlvet则载入请求的servlet类并调用service方法。

主要包括6个类

  • HttpServer1:程序的入口,负责创建Request和Response对象,并根据HTTP请求类型将其转给相应的处理器处理;
  • Request:用于封装客户端HTTP请求信息;
  • Response:用于封装服务器响应信息;
  • StaticResourceProcessor:静态资源处理器;
  • ServletProcessor1:servlet处理器;
  • Constants:用于定义一些常量,如WEB_ROOT

HttpServer1

  1. package day0522;
  2.  
  3. import java.net.Socket;
  4. import java.net.ServerSocket;
  5. import java.net.InetAddress;
  6. import java.io.InputStream;
  7. import java.io.OutputStream;
  8. import java.io.IOException;
  9.  
  10. public class HttpServer1 {
  11.  
  12. /** WEB_ROOT is the directory where our HTML and other files reside.
  13. * For this package, WEB_ROOT is the "webroot" directory under the working
  14. * directory.
  15. * The working directory is the location in the file system
  16. * from where the java command was invoked.
  17. */
  18. // shutdown command
  19. private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
  20.  
  21. // the shutdown command received
  22. private boolean shutdown = false;
  23.  
  24. public static void main(String[] args) {
  25. HttpServer1 server = new HttpServer1();
  26. server.await();
  27. }
  28.  
  29. public void await() {
  30. ServerSocket serverSocket = null;
  31. int port = 8080;
  32. try {
  33. serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
  34. }
  35. catch (IOException e) {
  36. e.printStackTrace();
  37. System.exit(1);
  38. }
  39.  
  40. // Loop waiting for a request
  41. while (!shutdown) {
  42. Socket socket = null;
  43. InputStream input = null;
  44. OutputStream output = null;
  45. try {
  46. socket = serverSocket.accept();
  47. input = socket.getInputStream();
  48. output = socket.getOutputStream();
  49.  
  50. // create Request object and parse
  51. Request request = new Request(input);
  52. request.parse();
  53.  
  54. // create Response object
  55. Response response = new Response(output);
  56. response.setRequest(request);
  57.  
  58. // check if this is a request for a servlet or a static resource
  59. // a request for a servlet begins with "/servlet/"
  60. if (request.getUri().startsWith("/servlet/")) {
  61. ServletProcessor1 processor = new ServletProcessor1();
  62. processor.process(request, response);
  63. }
  64. else {
  65. StaticResourceProcessor processor = new StaticResourceProcessor();
  66. processor.process(request, response);
  67. }
  68.  
  69. // Close the socket
  70. socket.close();
  71. //check if the previous URI is a shutdown command
  72. shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
  73. }
  74. catch (Exception e) {
  75. e.printStackTrace();
  76. System.exit(1);
  77. }
  78. }
  79. }
  80. }

  

从代码可以看出,该类主要内容与上篇的HttpServer类似,不同点有:

  • await会一直等待HTTP请求,如果等到请求,该方法会根据请求类型分发给对应的处理器来处理;
  • 支持静态资源的请求,可以通过类似http://localhost:8080/index.html这样的请求来访问
  • index.html页面;
  • 支持servlet的请求和解析,可以通过类似http://localhost:8080/PrimitiveServlet来访问PrimitiveServlet

Request与上篇介绍的Request无异,不再介绍,但是需要说明一点,这里的Request实现了ServletRequest接口。

  1. package day0522;
  2.  
  3. import java.io.InputStream;
  4. import java.io.IOException;
  5. import java.io.BufferedReader;
  6. import java.io.UnsupportedEncodingException;
  7. import java.util.Enumeration;
  8. import java.util.Locale;
  9. import java.util.Map;
  10. import javax.servlet.RequestDispatcher;
  11. import javax.servlet.ServletInputStream;
  12. import javax.servlet.ServletRequest;
  13.  
  14. public class Request implements ServletRequest {
  15.  
  16. private InputStream input;
  17. private String uri;
  18.  
  19. public Request(InputStream input) {
  20. this.input = input;
  21. }
  22.  
  23. public String getUri() {
  24. return uri;
  25. }
  26.  
  27. private String parseUri(String requestString) {
  28. int index1, index2;
  29. index1 = requestString.indexOf(' ');
  30. if (index1 != -1) {
  31. index2 = requestString.indexOf(' ', index1 + 1);
  32. if (index2 > index1)
  33. return requestString.substring(index1 + 1, index2);
  34. }
  35. return null;
  36. }
  37.  
  38. public void parse() {
  39. // Read a set of characters from the socket
  40. StringBuffer request = new StringBuffer(2048);
  41. int i;
  42. byte[] buffer = new byte[2048];
  43. try {
  44. i = input.read(buffer);
  45. }
  46. catch (IOException e) {
  47. e.printStackTrace();
  48. i = -1;
  49. }
  50. for (int j=0; j<i; j++) {
  51. request.append((char) buffer[j]);
  52. }
  53. System.out.print(request.toString());
  54. uri = parseUri(request.toString());
  55. }
  56.  
  57. /* implementation of the ServletRequest*/
  58. public Object getAttribute(String attribute) {
  59. return null;
  60. }
  61.  
  62. public Enumeration getAttributeNames() {
  63. return null;
  64. }
  65.  
  66. public String getRealPath(String path) {
  67. return null;
  68. }
  69.  
  70. public RequestDispatcher getRequestDispatcher(String path) {
  71. return null;
  72. }
  73.  
  74. public boolean isSecure() {
  75. return false;
  76. }
  77.  
  78. public String getCharacterEncoding() {
  79. return null;
  80. }
  81.  
  82. public int getContentLength() {
  83. return 0;
  84. }
  85.  
  86. public String getContentType() {
  87. return null;
  88. }
  89.  
  90. public ServletInputStream getInputStream() throws IOException {
  91. return null;
  92. }
  93.  
  94. public Locale getLocale() {
  95. return null;
  96. }
  97.  
  98. public Enumeration getLocales() {
  99. return null;
  100. }
  101.  
  102. public String getParameter(String name) {
  103. return null;
  104. }
  105.  
  106. public Map getParameterMap() {
  107. return null;
  108. }
  109.  
  110. public Enumeration getParameterNames() {
  111. return null;
  112. }
  113.  
  114. public String[] getParameterValues(String parameter) {
  115. return null;
  116. }
  117.  
  118. public String getProtocol() {
  119. return null;
  120. }
  121.  
  122. public BufferedReader getReader() throws IOException {
  123. return null;
  124. }
  125.  
  126. public String getRemoteAddr() {
  127. return null;
  128. }
  129.  
  130. public String getRemoteHost() {
  131. return null;
  132. }
  133.  
  134. public String getScheme() {
  135. return null;
  136. }
  137.  
  138. public String getServerName() {
  139. return null;
  140. }
  141.  
  142. public int getServerPort() {
  143. return 0;
  144. }
  145.  
  146. public void removeAttribute(String attribute) {
  147. }
  148.  
  149. public void setAttribute(String key, Object value) {
  150. }
  151.  
  152. public void setCharacterEncoding(String encoding)
  153. throws UnsupportedEncodingException {
  154. }
  155.  
  156. @Override
  157. public int getRemotePort() {
  158. // TODO Auto-generated method stub
  159. return 0;
  160. }
  161.  
  162. @Override
  163. public String getLocalName() {
  164. // TODO Auto-generated method stub
  165. return null;
  166. }
  167.  
  168. @Override
  169. public String getLocalAddr() {
  170. // TODO Auto-generated method stub
  171. return null;
  172. }
  173.  
  174. @Override
  175. public int getLocalPort() {
  176. // TODO Auto-generated method stub
  177. return 0;
  178. }
  179.  
  180. }

  

Response

  同理,这里的Response也不在赘述。

  1. package day0522;
  2.  
  3. import java.io.OutputStream;
  4. import java.io.IOException;
  5. import java.io.FileInputStream;
  6. import java.io.FileNotFoundException;
  7. import java.io.File;
  8. import java.io.PrintWriter;
  9. import java.util.Locale;
  10. import javax.servlet.ServletResponse;
  11. import javax.servlet.ServletOutputStream;
  12.  
  13. public class Response implements ServletResponse {
  14.  
  15. private static final int BUFFER_SIZE = 1024;
  16. Request request;
  17. OutputStream output;
  18. PrintWriter writer;
  19.  
  20. public Response(OutputStream output) {
  21. this.output = output;
  22. }
  23.  
  24. public void setRequest(Request request) {
  25. this.request = request;
  26. }
  27.  
  28. /* This method is used to serve a static page */
  29. public void sendStaticResource() throws IOException {
  30. byte[] bytes = new byte[BUFFER_SIZE];
  31. FileInputStream fis = null;
  32. try {
  33. /* request.getUri has been replaced by request.getRequestURI */
  34. File file = new File(Constants.WEB_ROOT, request.getUri());
  35. fis = new FileInputStream(file);
  36. /*
  37. HTTP Response = Status-Line
  38. *(( general-header | response-header | entity-header ) CRLF)
  39. CRLF
  40. [ message-body ]
  41. Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
  42. */
  43. int ch = fis.read(bytes, 0, BUFFER_SIZE);
  44. while (ch!=-1) {
  45. output.write(bytes, 0, ch);
  46. ch = fis.read(bytes, 0, BUFFER_SIZE);
  47. }
  48. }
  49. catch (FileNotFoundException e) {
  50. String errorMessage = "HTTP/1.1 404 File Not Found\r\n" +
  51. "Content-Type: text/html\r\n" +
  52. "Content-Length: 23\r\n" +
  53. "\r\n" +
  54. "<h1>File Not Found</h1>";
  55. output.write(errorMessage.getBytes());
  56. }
  57. finally {
  58. if (fis!=null)
  59. fis.close();
  60. }
  61. }
  62.  
  63. /** implementation of ServletResponse */
  64. public void flushBuffer() throws IOException {
  65. }
  66.  
  67. public int getBufferSize() {
  68. return 0;
  69. }
  70.  
  71. public String getCharacterEncoding() {
  72. return null;
  73. }
  74.  
  75. public Locale getLocale() {
  76. return null;
  77. }
  78.  
  79. public ServletOutputStream getOutputStream() throws IOException {
  80. return null;
  81. }
  82.  
  83. public PrintWriter getWriter() throws IOException {
  84. // autoflush is true, println() will flush,
  85. // but print() will not.
  86. writer = new PrintWriter(output, true);
  87. return writer;
  88. }
  89.  
  90. public boolean isCommitted() {
  91. return false;
  92. }
  93.  
  94. public void reset() {
  95. }
  96.  
  97. public void resetBuffer() {
  98. }
  99.  
  100. public void setBufferSize(int size) {
  101. }
  102.  
  103. public void setContentLength(int length) {
  104. }
  105.  
  106. public void setContentType(String type) {
  107. }
  108.  
  109. public void setLocale(Locale locale) {
  110. }
  111.  
  112. @Override
  113. public String getContentType() {
  114. // TODO Auto-generated method stub
  115. return null;
  116. }
  117.  
  118. @Override
  119. public void setCharacterEncoding(String charset) {
  120. // TODO Auto-generated method stub
  121.  
  122. }
  123. }

  

  这里的getWriter方法中新建了PrintWriter,其中第二个参数是一个boolean类型,表示是否启动autoFlush。

StaticResourceProcessor

  1. package day0522;
  2.  
  3. import java.io.IOException;
  4.  
  5. public class StaticResourceProcessor {
  6.  
  7. public void process(Request request, Response response) {
  8. try {
  9. response.sendStaticResource();
  10. }
  11. catch (IOException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. }

  

看代码可以看出:

  该类相较上篇是新建的类,主要实现的方法有sendStaticResource,实际上这个方法在上篇中也有,只是直接放在Response中出现,并在HttpServer中声明调用,而这里是将两种请求类型分别封装成类。

ServletProcessor

  1. package day0522;
  2.  
  3. import java.net.URL;
  4. import java.net.URLClassLoader;
  5. import java.net.URLStreamHandler;
  6. import java.io.File;
  7. import java.io.IOException;
  8. import javax.servlet.Servlet;
  9. import javax.servlet.ServletRequest;
  10. import javax.servlet.ServletResponse;
  11.  
  12. public class ServletProcessor1 {
  13.  
  14. public void process(Request request, Response response) {
  15.  
  16. String uri = request.getUri();
  17. String servletName = uri.substring(uri.lastIndexOf("/") + 1);
  18. URLClassLoader loader = null;
  19.  
  20. try {
  21. // create a URLClassLoader
  22. URL[] urls = new URL[1];
  23. URLStreamHandler streamHandler = null;
  24. File classPath = new File(Constants.WEB_ROOT);
  25. // the forming of repository is taken from the createClassLoader method in
  26. // org.apache.catalina.startup.ClassLoaderFactory
  27. String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;
  28. // the code for forming the URL is taken from the addRepository method in
  29. // org.apache.catalina.loader.StandardClassLoader class.
  30. urls[0] = new URL(null, repository, streamHandler);
  31. loader = new URLClassLoader(urls);
  32. }
  33. catch (IOException e) {
  34. System.out.println(e.toString() );
  35. }
  36. Class myClass = null;
  37. try {
  38. myClass = loader.loadClass(servletName);
  39. }
  40. catch (ClassNotFoundException e) {
  41. System.out.println(e.toString());
  42. }
  43.  
  44. Servlet servlet = null;
  45.  
  46. try {
  47. servlet = (Servlet) myClass.newInstance();
  48. servlet.service((ServletRequest) request, (ServletResponse) response);
  49. }
  50. catch (Exception e) {
  51. System.out.println(e.toString());
  52. }
  53. catch (Throwable e) {
  54. System.out.println(e.toString());
  55. }
  56.  
  57. }
  58. }

  

从代码看出:

  • 该类只有一个方法process,接收Request和Response两个参数;
  • 通过uri.substring来获取请求的servlet名;
  • 通过新建一个类加载器来装载请求的servlet类,用的类加载器为java.net.URLClassLoader;
  • 有了类加载器后,通过loadClass方法载入serlvet类;
  • 创建一个载入类的实例,并调用其service方法。

至此,我们明白了:

  • servlet容器会等待http请求;
  • request负责封装http请求信息;
  • response负责封装相应信息;
  • staticResourceProcessor负责静态资源请求处理;
  • servletProcessor负责servlet的请求处理;
  • 一个简易的servlet容器的运作原理。

如果您觉得阅读本文对您有帮助,请点一下“推荐”按钮,您的“推荐”将是我最大的写作动力!如果您想持续关注我的文章,请扫描二维码,关注JackieZheng的微信公众号,我会将我的文章推送给您,并和您一起分享我日常阅读过的优质文章。

友情赞助

如果你觉得博主的文章对你那么一点小帮助,恰巧你又有想打赏博主的小冲动,那么事不宜迟,赶紧扫一扫,小额地赞助下,攒个奶粉钱,也是让博主有动力继续努力,写出更好的文章^^。

    1. 支付宝                          2. 微信

                      

探秘Tomcat——一个简易的Servlet容器的更多相关文章

  1. 一个简单的servlet容器

    [0]README 0.1)本文部分文字转自 “深入剖析Tomcat”,旨在学习  一个简单的servlet容器  的基础知识: 0.2)for complete source code, pleas ...

  2. how tomcat works 读书笔记(二)----------一个简单的servlet容器

    app1 (建议读者在看本章之前,先看how tomcat works 读书笔记(一)----------一个简单的web服务器 http://blog.csdn.net/dlf123321/arti ...

  3. Tomcat学习笔记(二)—— 一个简单的Servlet容器

    1.简介:Servlet编程是通过javax.Servlet和javax.servlet.http这两个包的类和接口实现的,其中javax.servlet.Servlet接口至关重要,所有的Servl ...

  4. 一个简单的Servlet容器实现

    上篇写了一个简单的Java web服务器实现,只能处理一些静态资源的请求,本篇文章实现的Servlet容器基于前面的服务器做了个小改造,增加了Servlet请求的处理. 程序执行步骤 创建一个Serv ...

  5. DI 原理解析 并实现一个简易版 DI 容器

    本文基于自身理解进行输出,目的在于交流学习,如有不对,还望各位看官指出. DI DI-Dependency Injection,即"依赖注入":对象之间依赖关系由容器在运行期决定, ...

  6. 攻城狮在路上(肆)How tomcat works(二) 一个简单的servlet容器

    该节在上一节的基础上增加了所谓对静态资源和动态资源访问的不同控制流程.示例里面采用的是对路径“/servlet/”进行了特殊处理. 一. 主要还是从HttpServer1中的main方法开始,先解析出 ...

  7. 2.自己搭建的一个简易的ioc容器

    1.persondao类namespace MyselfIoC{    public class PersonDao    {        public override string ToStri ...

  8. Tomcat剖析(二):一个简单的Servlet服务器

    Tomcat剖析(二):一个简单的Servlet服务器 1. Tomcat剖析(一):一个简单的Web服务器 2. Tomcat剖析(二):一个简单的Servlet服务器 3. Tomcat剖析(三) ...

  9. SpringBoot 源码解析 (六)----- Spring Boot的核心能力 - 内置Servlet容器源码分析(Tomcat)

    Spring Boot默认使用Tomcat作为嵌入式的Servlet容器,只要引入了spring-boot-start-web依赖,则默认是用Tomcat作为Servlet容器: <depend ...

随机推荐

  1. 【JSOI2007】【Bzoj1029】建筑抢修

    贪心... 按照T2来进行排序,用堆来进行维护.循环一遍,如果循环时间加上已用时间不超过截止时间,那就ANS++.否则,将它与堆顶判断,如果小于堆顶就把堆顶踢出,把它加入. #include<c ...

  2. PHP基础知识之遍历

    遍历对象的时候,默认遍历对象的所有属性 class MyClass{    public $var1 = 'value 1';    public $var2 = 'value 2';    publ ...

  3. CQOI 2016 k远点对

    题目大意:n个点,求第k远的点对的距离 KD树裸题 注意要用堆维护第k远 #include<bits/stdc++.h> #define ll unsigned long long #de ...

  4. 尝试解决在构造函数中同步调用Dns.GetHostAddressesAsync()引起的线程死锁

    (最终采用的是方法4) 问题详情见:.NET Core中遇到奇怪的线程死锁问题:内存与线程数不停地增长 看看在 Linux 与 Windows 上发生线程死锁的后果. Linux: Microsoft ...

  5. ASP.NET安全

    ASP.NET 安全 概述 安全在web领域是一个永远都不会过时的话题,今天我们就来看一看一些在开发ASP.NET MVC应用程序时一些值得我们注意的安全问题.本篇主要包括以下几个内容 : 认证 授权 ...

  6. Hadoop学习笔记—3.Hadoop RPC机制的使用

    一.RPC基础概念 1.1 RPC的基础概念 RPC,即Remote Procdure Call,中文名:远程过程调用: (1)它允许一台计算机程序远程调用另外一台计算机的子程序,而不用去关心底层的网 ...

  7. 【完全开源】百度地图Web service API C#.NET版,带地图显示控件、导航控件、POI查找控件

    目录 概述 功能 如何使用 参考帮助 概述 源代码主要包含三个项目,BMap.NET.BMap.NET.WindowsForm以及BMap.NET.WinformDemo. BMap.NET 对百度地 ...

  8. 当MyEclipse突然异常关闭

    今天的博文主要记录一个问题,就是当MyEclipse异常关闭后,再次开启环境,导致Tomcat无法启动的问题解决方案 问题描述:在MyEclipse启动或者是tomcat启动的时候出现:Address ...

  9. 谁占了我的端口 for Windows

    这篇文章发布于我的 github 博客:原文 今天在本地调试 Blog 的时候意外的出现了一些错误:127.0.0.1 4000 端口已经被其他的进程占用了.如何找到占用端口的进程呢? Configu ...

  10. 学习RBAC 用户·角色·权限·表