来源:《How Tomcat Works》

Servlet容器的工作原理:

1、创建一个request对象并填充那些有可能被所引用的servlet使用的信息,比如参数、头部、cookies、查询字符串、URL等。而一个request对象是javax.servlet.ServletRequest或javax.servlet.http.ServletRequest接口的一个实例对象。

2、创建一个response对象,所引用的servlet使用它给客户端发送响应。一个response对象javax.servlet.ServletResponse或javax.servlet.http.ServletResponse接口的一个实例。

3、调用servlet的service方法,并传入request和response对象,而servlet会从request对象中取值,给response对象写值。

Catalina:是tomcat所使用的Servlet的容器。由两个主要模块组成,连接器(connector)和容器(container),连接器用来连接容器里面的请求,工作是接收到每一个http请求,构造一个resquest对象和response对象。然后传递给容器。容器接收到对象之后,调用servlet的service方法用于响应。

一个简单的web服务器:超文本传输协议服务器(http),一个基于java的web服务器使用的是两个基本的类,java.net.Socket和java.net.ServerSOcket.

Http协议:在Http中,始终是客户端通过建立连接和发送一个http请求从而开启一个事务。web服务器不需要联系客户端或者对客户端做一个回调连接。无论客户端或者服务器都可以提前终止连接。

Socket类:在计算机网络中,socket是网络连接的端点,使得一个应用可以从网络中读取和写入数据。放在两个不同计算机上的应用可以通过连接发送和接收字节流。在java中,套接字是一个类。

  1. new Socket("ip地址"port);

Socket类是一个客户端类,创建了socket类之后,可以使用它来向服务器发送和接收字节流。首先要调用Socket类中的getOutputStream方法来获取java.io.OutputStream对象。要发送的对象是文本,需要构造一个printWrite对象。而要想从远程端接收对象,可以使用Socket类中的getInputStream,来返回对象。

本质上来说,socket发送的是OutputStream对象,接收的是InputStream。

  1. package test;
  2.  
  3. import java.io.*;
  4. import java.net.Socket;
  5.  
  6. public class MySocket {
  7.  
  8. public static void main(String[] args) {
  9. try{
  10. //向本机的4700端口发出客户请求
  11. Socket socket=new Socket("127.0.0.1",4700);
  12. //由系统标准输入设备构造BufferedReader对象
  13. BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
  14. //由Socket对象得到输出流,并构造PrintWriter对象
  15. PrintWriter os=new PrintWriter(socket.getOutputStream());
  16. //由Socket对象得到输入流,并构造相应的BufferedReader对象
  17. BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
  18. String readline;
  19. readline=sin.readLine(); //从系统标准输入读入一字符串
  20. //若从标准输入读入的字符串为 "bye"则停止循环
  21. while(!readline.equals("bye")){
  22. //将从系统标准输入读入的字符串输出到Server
  23. os.println(readline);
  24. //刷新输出流,使Server马上收到该字符串
  25. os.flush();
  26. //在系统标准输出上打印读入的字符串
  27. System.out.println("Client:"+readline);
  28. //从Server读入一字符串,并打印到标准输出上
  29. System.out.println("Server:"+is.readLine());
  30. readline=sin.readLine(); //从系统标准输入读入一字符串
  31. }
  32. os.close(); //关闭Socket输出流
  33. is.close(); //关闭Socket输入流
  34. socket.close(); //关闭Socket
  35. }catch(Exception e){
  36. e.printStackTrace();//出错,打印出错信息
  37. }
  38.  
  39. }
  40. }

ServerSocket类:是一个服务器类,绑定了端口号,等待连接,其中accept方法可以接收一个socket对象,然后和客户端交互。

  1. package test;
  2.  
  3. import java.io.*;
  4. import java.net.ServerSocket;
  5. import java.net.Socket;
  6.  
  7. public class MyServerSocket {
  8. public static void main(String args[]) {
  9. try{
  10. ServerSocket server=null;
  11. try{
  12. //创建一个ServerSocket在端口4700监听客户请求
  13. server=new ServerSocket(4700);
  14. }catch(Exception e){
  15. e.printStackTrace();//出错,打印出错信息
  16. }
  17. Socket socket=null;
  18. try{
  19. //使用accept()阻塞等待客户请求,有客户
  20. socket=server.accept();//请求到来则产生一个Socket对象,并继续执行
  21. }catch(Exception e){
  22. e.printStackTrace();//出错,打印出错信息
  23. }
  24. String line;
  25. //由Socket对象得到输入流,并构造相应的BufferedReader对象
  26. BufferedReader is=new BufferedReader(new InputStreamReader(socket.getInputStream()));
  27. //由Socket对象得到输出流,并构造PrintWriter对象
  28. PrintWriter os=new PrintWriter(socket.getOutputStream());
  29. //由系统标准输入设备构造BufferedReader对象
  30. BufferedReader sin=new BufferedReader(new InputStreamReader(System.in));
  31. //在标准输出上打印从客户端读入的字符串
  32. System.out.println("Client:"+is.readLine());
  33. //从标准输入读入一字符串
  34. line=sin.readLine();
  35. //如果该字符串为 "bye",则停止循环
  36. while(!line.equals("bye")){
  37. //向客户端输出该字符串
  38. os.println(line);
  39. //刷新输出流,使Client马上收到该字符串
  40. os.flush();
  41. //在系统标准输出上打印读入的字符串
  42. System.out.println("Server:"+line);
  43. //从Client读入一字符串,并打印到标准输出上
  44. System.out.println("Client:"+is.readLine());
  45. //从系统标准输入读入一字符串
  46. line=sin.readLine();
  47. }
  48.  
  49. os.close(); //关闭Socket输出流
  50. is.close(); //关闭Socket输入流
  51. socket.close(); //关闭Socket
  52. server.close(); //关闭ServerSocket
  53. }catch(Exception e){
  54. e.printStackTrace();//出错,打印出错信息
  55. }
  56. }
  57. }

下面定义一个应用程序,定义一个web服务器。来处理http请求。即HttpServer。

一个HttpServer类代表着一个web服务器。

这里实现一个简易的从服务器申请静态资源的服务器。

  1. package test.pyrmont;
  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. import java.io.File;
  10.  
  11. public class HttpServer {
  12.  
  13. /** WEB_ROOT is the directory where our HTML and other files reside.
  14. * For this package, WEB_ROOT is the "webroot" directory under the working
  15. * directory.
  16. * The working directory is the location in the file system
  17. * from where the java command was invoked.
  18. */
  19. public static final String WEB_ROOT =
  20. System.getProperty("user.dir") + File.separator + "webroot";
  21.  
  22. // shutdown command
  23. private static final String SHUTDOWN_COMMAND = "/SHUTDOWN";
  24.  
  25. // the shutdown command received
  26. private boolean shutdown = false;
  27.  
  28. public static void main(String[] args) {
  29. HttpServer server = new HttpServer();
  30. server.await();
  31. }
  32.  
  33. public void await() {
  34. ServerSocket serverSocket = null;
  35. int port = 8080;
  36. try {
  37. serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
  38. }
  39. catch (IOException e) {
  40. e.printStackTrace();
  41. System.exit(1);
  42. }
  43.  
  44. // Loop waiting for a request
  45. while (!shutdown) {
  46. Socket socket = null;
  47. InputStream input = null;
  48. OutputStream output = null;
  49. try {
  50. socket = serverSocket.accept();
  51. input = socket.getInputStream();
  52. output = socket.getOutputStream();
  53.  
  54. // create Request object and parse
  55. Request request = new Request(input);
  56. request.parse();
  57.  
  58. // create Response object
  59. Response response = new Response(output);
  60. response.setRequest(request);
  61. response.sendStaticResource();
  62.  
  63. // Close the socket
  64. socket.close();
  65.  
  66. //check if the previous URI is a shutdown command
  67. shutdown = request.getUri().equals(SHUTDOWN_COMMAND);
  68. System.out.println(request.getUri());
  69. }
  70. catch (Exception e) {
  71. e.printStackTrace();
  72. continue;
  73. }
  74. }
  75. }
  76. }

HttpServer

该服务器提供了一个静态的final变量WEB_ROOT所在的目录和它下面所有的子目录的静态资源。其目录是当前服务器的目录路径下的webroot目录。在该目录下的静态资源均可以被访问到。

同时定义了一个停止服务器的命令行,使用uri来停止服务器(这是比较危险的操作)。

创建一个ServerSocket,然后绑定端口,并使用accept来接收浏览器传来的input。使用request对象的函数对input进行解析,其实就是从浏览器的地址栏里拼接出静态资源的访问地址。然后,将request传给reponse,response根据传过来的地址,去寻找静态资源。找到后,利用socket的output,将文件响应给浏览器(这里chrome浏览器无法解析字节bytes数组,需要使用其他浏览器)

  1. package test.pyrmont;
  2.  
  3. import java.io.InputStream;
  4. import java.io.IOException;
  5.  
  6. public class Request {
  7.  
  8. private InputStream input;
  9. private String uri;
  10.  
  11. public Request(InputStream input) {
  12. this.input = input;
  13. }
  14.  
  15. public void parse() {
  16. // Read a set of characters from the socket
  17. StringBuffer request = new StringBuffer(2048);
  18. int i;
  19. byte[] buffer = new byte[2048];
  20. try {
  21. i = input.read(buffer);
  22. }
  23. catch (IOException e) {
  24. e.printStackTrace();
  25. i = -1;
  26. }
  27. for (int j=0; j<i; j++) {
  28. request.append((char) buffer[j]);
  29. }
  30. uri = parseUri(request.toString());
  31. }
  32.  
  33. private String parseUri(String requestString) {
  34. int index1, index2;
  35. index1 = requestString.indexOf(' ');
  36. if (index1 != -1) {
  37. index2 = requestString.indexOf(' ', index1 + 1);
  38. if (index2 > index1)
  39. return requestString.substring(index1 + 1, index2);
  40. }
  41. return null;
  42. }
  43.  
  44. public String getUri() {
  45. return uri;
  46. }
  47.  
  48. }

Request

  1. package test.pyrmont;
  2.  
  3. import com.sun.org.apache.xpath.internal.SourceTree;
  4.  
  5. import java.io.OutputStream;
  6. import java.io.IOException;
  7. import java.io.FileInputStream;
  8. import java.io.File;
  9. import java.util.Arrays;
  10.  
  11. /*
  12. HTTP Response = Status-Line
  13. *(( general-header | response-header | entity-header ) CRLF)
  14. CRLF
  15. [ message-body ]
  16. Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
  17. */
  18.  
  19. public class Response {
  20.  
  21. private static final int BUFFER_SIZE = 1024;
  22. Request request;
  23. OutputStream output;
  24.  
  25. public Response(OutputStream output) {
  26. this.output = output;
  27. }
  28.  
  29. public void setRequest(Request request) {
  30. this.request = request;
  31. }
  32.  
  33. public void sendStaticResource() throws IOException {
  34. byte[] bytes = new byte[BUFFER_SIZE];
  35. FileInputStream fis = null;
  36. try {
  37. File file = new File(HttpServer.WEB_ROOT, request.getUri());
  38.  
  39. if (file.exists()) {
  40. fis = new FileInputStream(file);
  41. int ch = fis.read(bytes, 0, BUFFER_SIZE);
  42.  
  43. while (ch!=-1) {
  44. output.write(bytes, 0, ch);
  45. ch = fis.read(bytes, 0, BUFFER_SIZE);
  46. }
  47. }
  48. else {
  49. // file not found
  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. }
  58. catch (Exception e) {
  59. // thrown if cannot instantiate a File object
  60. System.out.println(e.toString() );
  61. }
  62. finally {
  63. if (fis!=null)
  64. fis.close();
  65. }
  66. }
  67. }

Response

以上我们就实现了一个建议的web服务器,其功能是根据uri来请求服务器上的静态资源。


一个简单的Servlet容器

Servlet接口:

  1. void init(ServletConfig var1) throws ServletException;
  2.  
  3. ServletConfig getServletConfig();
  4.  
  5. void service(ServletRequest var1, ServletResponse var2) throws ServletException, IOException;
  6.  
  7. String getServletInfo();
  8.  
  9. void destroy();
  10. }

其中init()、service()、destroy()三个方法是servlet的生命周期方法。

在servlet类被初始化之后,init()方法被servlet所调用,且只调用一次,表明,servlet已经被加载进服务了。因此,init方法必须在servlet可以接受任何请求之前成功运行完毕。程序员可以在init方法里覆盖的写一些只运行一次的代码。或者留空。

servlet容器调用service方法来处理servlet请求。servlet容器会传递一个javax.servlet.ServletRequest对象和javax.servlet.ServletResponse对象。Request对象包括客户端的HTTP请求信息,而response对象封装servlet的响应。service方法会被调用很多次。

servlet容器调用destroy方法来移除一个servlet实例。如果servlet容器正在被关闭或者servlet容器需要空闲内存,当所有servlet线程的service方法退出了,该函数才会被调用。

实现一个简易的servlet类

  1. package test.servlet;
  2.  
  3. import javax.servlet.*;
  4. import java.io.IOException;
  5. import java.io.PrintWriter;
  6.  
  7. public class PrimitiveServlet implements Servlet {
  8.  
  9. public void init(ServletConfig servletConfig) throws ServletException {
  10. System.out.println("init");
  11. }
  12.  
  13. public ServletConfig getServletConfig() {
  14. return null;
  15. }
  16.  
  17. public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
  18. System.out.println("from service");
  19. PrintWriter out = servletResponse.getWriter();
  20. out.println("Hello. Roses are red.");
  21. out.print("Violets are blue.");
  22. }
  23.  
  24. public String getServletInfo() {
  25. return null;
  26. }
  27.  
  28. public void destroy() {
  29. System.out.println("destroy");
  30. }
  31. }

PrimitiveServlet

这是一个很简单的servlet的实现类,其中service方法只向浏览器输出一句话。

然后实现一个简单的servlet容器。HttpServer1

  1. package test.servlet;
  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. }

HttpServer1

和之前写的服务器代码一样,之前写的服务器可以申请静态资源,而该服务器可以申请servlet资源。

  1. if (request.getUri().startsWith("/servlet/")) {
  2. ServletProcessor1 processor = new ServletProcessor1();
  3. processor.process(request, response);
  4. }
  5. else {
  6. StaticResourceProcessor processor = new StaticResourceProcessor();
  7. processor.process(request, response);
  8. }

上面的代码就是,当申请地址有servlet目录的时候,我们需要申请一个servlet资源,如果没有,就申请静态资源。

  1. package test.servlet;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.net.URL;
  6. import java.net.URLClassLoader;
  7. import java.net.URLStreamHandler;
  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))
  28. .toString();
  29. // the code for forming the URL is taken from the addRepository method in
  30. // org.apache.catalina.loader.StandardClassLoader class.
  31. urls[0] = new URL(null, repository, streamHandler);
  32. loader = new URLClassLoader(urls);
  33. } catch (IOException e) {
  34. System.out.println(e.toString());
  35. }
  36. Class myClass = null;
  37. try {
  38. myClass = loader.loadClass(servletName);
  39. } catch (ClassNotFoundException e) {
  40. System.out.println(e.toString());
  41. }
  42.  
  43. Servlet servlet = null;
  44.  
  45. try {
  46. servlet = (Servlet) myClass.newInstance();
  47. servlet.service((ServletRequest) request, (ServletResponse) response);
  48. } catch (Exception e) {
  49. System.out.println(e.toString());
  50. } catch (Throwable e) {
  51. System.out.println(e.toString());
  52. }
  53.  
  54. }
  55. }

ServletProcessor1

上面代码是封装了一个servlet资源申请的类,首先需要得到请求的地址,以及servlet的名称。然后创建一个类加载器,类加载器里面需要一个URL对象的数组,URL对象指向了加载类时的查找位置。而URL被认为是一个要被下载的jar包。

而URL的构建,需要一个表示资源的字符串,最后,调用类加载器的loadClass方法来得到该Servlet类,然后使用newInstance方法新建一个Servlet对象,然后调用其service方法。

但上面的ServletProcessor1中有一个问题,我们传request和response对象的时候,可以将Servletrequest对象往下转成Request对象,这样,在处理servlet的类中也可以处理访问静态资源的方法,会造成一定的危害。因此,我们可以创建额外的RequestFacade对象和ResponseFacade对象,然后继承servlet来处理servlet。

  1. package test.servlet2;
  2.  
  3. import java.io.IOException;
  4. import java.io.BufferedReader;
  5. import java.io.UnsupportedEncodingException;
  6. import java.util.Enumeration;
  7. import java.util.Locale;
  8. import java.util.Map;
  9. import javax.servlet.RequestDispatcher;
  10. import javax.servlet.ServletInputStream;
  11. import javax.servlet.ServletRequest;
  12.  
  13. public class RequestFacade implements ServletRequest {
  14.  
  15. private ServletRequest request = null;
  16.  
  17. public RequestFacade(Request request) {
  18. this.request = request;
  19. }
  20.  
  21. /* implementation of the ServletRequest*/
  22. public Object getAttribute(String attribute) {
  23. return request.getAttribute(attribute);
  24. }
  25.  
  26. public Enumeration getAttributeNames() {
  27. return request.getAttributeNames();
  28. }
  29.  
  30. public String getRealPath(String path) {
  31. return request.getRealPath(path);
  32. }
  33.  
  34. public int getRemotePort() {
  35. return request.getRemotePort();
  36. }
  37.  
  38. public String getLocalName() {
  39. return request.getLocalName();
  40. }
  41.  
  42. public String getLocalAddr() {
  43. return request.getLocalAddr();
  44. }
  45.  
  46. public int getLocalPort() {
  47. return request.getLocalPort();
  48. }
  49.  
  50. public RequestDispatcher getRequestDispatcher(String path) {
  51. return request.getRequestDispatcher(path);
  52. }
  53.  
  54. public boolean isSecure() {
  55. return request.isSecure();
  56. }
  57.  
  58. public String getCharacterEncoding() {
  59. return request.getCharacterEncoding();
  60. }
  61.  
  62. public int getContentLength() {
  63. return request.getContentLength();
  64. }
  65.  
  66. public String getContentType() {
  67. return request.getContentType();
  68. }
  69.  
  70. public ServletInputStream getInputStream() throws IOException {
  71. return request.getInputStream();
  72. }
  73.  
  74. public Locale getLocale() {
  75. return request.getLocale();
  76. }
  77.  
  78. public Enumeration getLocales() {
  79. return request.getLocales();
  80. }
  81.  
  82. public String getParameter(String name) {
  83. return request.getParameter(name);
  84. }
  85.  
  86. public Map getParameterMap() {
  87. return request.getParameterMap();
  88. }
  89.  
  90. public Enumeration getParameterNames() {
  91. return request.getParameterNames();
  92. }
  93.  
  94. public String[] getParameterValues(String parameter) {
  95. return request.getParameterValues(parameter);
  96. }
  97.  
  98. public String getProtocol() {
  99. return request.getProtocol();
  100. }
  101.  
  102. public BufferedReader getReader() throws IOException {
  103. return request.getReader();
  104. }
  105.  
  106. public String getRemoteAddr() {
  107. return request.getRemoteAddr();
  108. }
  109.  
  110. public String getRemoteHost() {
  111. return request.getRemoteHost();
  112. }
  113.  
  114. public String getScheme() {
  115. return request.getScheme();
  116. }
  117.  
  118. public String getServerName() {
  119. return request.getServerName();
  120. }
  121.  
  122. public int getServerPort() {
  123. return request.getServerPort();
  124. }
  125.  
  126. public void removeAttribute(String attribute) {
  127. request.removeAttribute(attribute);
  128. }
  129.  
  130. public void setAttribute(String key, Object value) {
  131. request.setAttribute(key, value);
  132. }
  133.  
  134. public void setCharacterEncoding(String encoding)
  135. throws UnsupportedEncodingException {
  136. request.setCharacterEncoding(encoding);
  137. }
  138.  
  139. }

RequestFacade

  1. package test.servlet2;
  2.  
  3. import java.io.IOException;
  4. import java.io.PrintWriter;
  5. import java.util.Locale;
  6. import javax.servlet.ServletOutputStream;
  7. import javax.servlet.ServletResponse;
  8.  
  9. public class ResponseFacade implements ServletResponse {
  10.  
  11. private ServletResponse response;
  12.  
  13. public ResponseFacade(Response response) {
  14. this.response = response;
  15. }
  16.  
  17. public void flushBuffer() throws IOException {
  18. response.flushBuffer();
  19. }
  20.  
  21. public int getBufferSize() {
  22. return response.getBufferSize();
  23. }
  24.  
  25. public String getCharacterEncoding() {
  26. return response.getCharacterEncoding();
  27. }
  28.  
  29. public String getContentType() {
  30. return response.getContentType();
  31. }
  32.  
  33. public Locale getLocale() {
  34. return response.getLocale();
  35. }
  36.  
  37. public ServletOutputStream getOutputStream() throws IOException {
  38. return response.getOutputStream();
  39. }
  40.  
  41. public PrintWriter getWriter() throws IOException {
  42. return response.getWriter();
  43. }
  44.  
  45. public void setCharacterEncoding(String s) {
  46.  
  47. }
  48.  
  49. public boolean isCommitted() {
  50. return response.isCommitted();
  51. }
  52.  
  53. public void reset() {
  54. response.reset();
  55. }
  56.  
  57. public void resetBuffer() {
  58. response.resetBuffer();
  59. }
  60.  
  61. public void setBufferSize(int size) {
  62. response.setBufferSize(size);
  63. }
  64.  
  65. public void setContentLength(int length) {
  66. response.setContentLength(length);
  67. }
  68.  
  69. public void setContentType(String type) {
  70. response.setContentType(type);
  71. }
  72.  
  73. public void setLocale(Locale locale) {
  74. response.setLocale(locale);
  75. }
  76.  
  77. }

ResponseFacade

  1. package test.servlet2;
  2.  
  3. import java.io.File;
  4. import java.io.IOException;
  5. import java.net.URL;
  6. import java.net.URLClassLoader;
  7. import java.net.URLStreamHandler;
  8. import javax.servlet.Servlet;
  9. import javax.servlet.ServletRequest;
  10. import javax.servlet.ServletResponse;
  11.  
  12. public class ServletProcessor2 {
  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))
  28. .toString();
  29. // the code for forming the URL is taken from the addRepository method in
  30. // org.apache.catalina.loader.StandardClassLoader class.
  31. urls[0] = new URL(null, repository, streamHandler);
  32. loader = new URLClassLoader(urls);
  33. } catch (IOException e) {
  34. System.out.println(e.toString());
  35. }
  36. Class myClass = null;
  37. try {
  38. myClass = loader.loadClass(servletName);
  39. } catch (ClassNotFoundException e) {
  40. System.out.println(e.toString());
  41. }
  42.  
  43. Servlet servlet = null;
  44. RequestFacade requestFacade = new RequestFacade(request);
  45. ResponseFacade responseFacade = new ResponseFacade(response);
  46. try {
  47. servlet = (Servlet) myClass.newInstance();
  48. servlet.service((ServletRequest) requestFacade, (ServletResponse) responseFacade);
  49. } catch (Exception e) {
  50. System.out.println(e.toString());
  51. } catch (Throwable e) {
  52. System.out.println(e.toString());
  53. }
  54.  
  55. }
  56. }

ServletProcessor2

到目前为止,可以总结一下:一个简单的Web服务器,需要有申请静态资源和动态资源的功能,我们在浏览器上发出请求,然后服务器响应。服务器响应主要用到ServerSocket,通过接收intput,响应output来处理数据。我们通过封装request和response对象,将input和out封装起来,最后响应回去。对于request来说,它接收到了浏览器传过来的input字节流,需要将字节流转换为字节数组,然后转换为字符串。得到请求的地址。然后我们根据这个地址字符串来判断该请求是请求静态资源还是servlet,如果请求静态资源,那么直接调用response的发送资源函数即可,该函数将通过地址来寻找文件,找到后将其转换为out字节流传回浏览器,浏览器会自行渲染。如果请求的是servlet,那么服务器会得到该servlet的地址以及名字,然后创建一个类加载器,根据地址来寻找该servlet的字节码文件,找到后加载为一个类,然后根据newInstance方法来创建一个servlet对象,该servlet对象的类型是我们自己定义的servlet类的对象,然后调用servlet对象的service方法来执行。


连接器:

三个模块:

startup模块,Bootstrap,用来启动应用。

connector模块:连接器和其支撑类(HttpConnector和HttpProcessor)、指代HTTP请求的类(HttpRequest)和它的辅助类、指代HTTP响应的类(HttpResponse)和它的辅助类、Facade类(HttpRequestFacade和HttpResponseFacade)、

Constant类

core模块:ServletProcessor和StaticResourceProcessor。

将HttpServer类分为HttpConnector和HttpProcessor。其中HttpConnector类用来等待http请求,而HttpProcessor用来创建请求和响应对象。

而且Http请求对象实现了javax.servlet.http.HttpServletRequest接口。一个HttpRequest对象会被转换为HttpServletRequest实例,然后传递给被调用的servlet的service方法。HttpRequest对象,包括URI,查询字符串,参数,cookies和其他

的头部等等。连接器不会先去解析request的所有字段,而是等servlet需要的时候才会去解析。

启动应用程序:Bootstrap类。其实就是开启连接器,因为连接器等待http请求。

  1. package test.servlet3.startup;
  2.  
  3. import test.servlet3.connector.http.HttpConnector;
  4.  
  5. public final class Bootstrap {
  6.  
  7. public static void main(String[] args) {
  8. HttpConnector connector = new HttpConnector();
  9. connector.start();
  10. }
  11. }

这个启动类很简单,HttpConnector继承了Runnable接口,然后自己开了一个线程,启动类开启此线程即可。

接下来看 HttpConnector类,此类负责等待客户端请求,拿到socket。

  1. package test.servlet3.connector.http;
  2.  
  3. import java.io.IOException;
  4. import java.net.InetAddress;
  5. import java.net.ServerSocket;
  6. import java.net.Socket;
  7.  
  8. public class HttpConnector implements Runnable {
  9.  
  10. boolean stopped;
  11. private String scheme = "http";
  12.  
  13. public void run() {
  14.  
  15. ServerSocket serverSocket = null;
  16. int port = 8080;
  17. try {
  18. serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
  19. }
  20. catch (IOException e) {
  21. e.printStackTrace();
  22. System.exit(1);
  23. }
  24. while (!stopped) {
  25. // Accept the next incoming connection from the server socket
  26. Socket socket = null;
  27. try {
  28. socket = serverSocket.accept();
  29. }
  30. catch (Exception e) {
  31. continue;
  32. }
  33.  
  34. //这里实际上就是将服务器接收到的套接字交给配套的函数,让其去创建request和response对象。
  35. HttpProcessor processor = new HttpProcessor(this);
  36. processor.process(socket);
  37. }
  38.  
  39. }
  40.  
  41. public void start() {
  42. Thread thread = new Thread(this);
  43. thread.start();
  44. }
  45. }

HttpConnector

其中重要的是

  1. HttpProcessor processor = new HttpProcessor(this);
  2. processor.process(socket);

这个一个处理类,将socket传过去去处理,主要是创建Request对象和Response对象。

  1. package test.servlet3.connector.http;
  2.  
  3. import org.apache.catalina.util.RequestUtil;
  4. import org.apache.catalina.util.StringManager;
  5.  
  6. import javax.servlet.ServletException;
  7. import javax.servlet.http.Cookie;
  8. import java.io.IOException;
  9. import java.io.OutputStream;
  10. import java.net.Socket;
  11.  
  12. /* this class used to be called HttpServer */
  13. public class HttpProcessor {
  14.  
  15. public HttpProcessor(HttpConnector connector) {
  16. this.connector = connector;
  17. }
  18. /**
  19. * The HttpConnector with which this processor is associated.
  20. */
  21. private HttpConnector connector = null;
  22. private HttpRequest request;
  23. private HttpRequestLine requestLine = new HttpRequestLine(); //请求行使用默认
  24. private HttpResponse response;
  25.  
  26. protected String method = null;
  27. protected String queryString = null;
  28.  
  29. /**
  30. * The string manager for this package.
  31. */
  32. protected StringManager sm =
  33. StringManager.getManager("test.servlet3.connector.http");
  34.  
  35. public void process(Socket socket) {
  36. SocketInputStream input = null; //自己定义了一个继承InputStream的流处理类
  37. OutputStream output = null;
  38. try {
  39. input = new SocketInputStream(socket.getInputStream(), 2048); //初始化input,得到请求传过来的数据。
  40. output = socket.getOutputStream();//为响应做准备
  41.  
  42. // create HttpRequest object and parse
  43. request = new HttpRequest(input); //根据input来创建一个request对象。
  44.  
  45. // create HttpResponse object
  46. response = new HttpResponse(output);//根据output来创建一个response对象。
  47.  
  48. //设置response对象。
  49. response.setRequest(request); //将请求传入
  50.  
  51. response.setHeader("Server", "Pyrmont Servlet Container"); //设置响应头
  52.  
  53. //响应里面很多都留空。
  54.  
  55. parseRequest(input, output); //解析请求
  56. parseHeaders(input);
  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.getRequestURI().startsWith("/servlet/")) {
  61. ServletProcessor processor = new ServletProcessor();
  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. // no shutdown for this application
  72. }
  73. catch (Exception e) {
  74. e.printStackTrace();
  75. }
  76. }
  77.  
  78. /**
  79. * This method is the simplified version of the similar method in
  80. * org.apache.catalina.connector.http.HttpProcessor.
  81. * However, this method only parses some "easy" headers, such as
  82. * "cookie", "content-length", and "content-type", and ignore other headers.
  83. * @param input The input stream connected to our socket
  84. *
  85. * @exception IOException if an input/output error occurs
  86. * @exception ServletException if a parsing error occurs
  87. */
  88. private void parseHeaders(SocketInputStream input)
  89. throws IOException, ServletException {
  90. while (true) {
  91. HttpHeader header = new HttpHeader();;
  92.  
  93. // Read the next header
  94. input.readHeader(header);
  95. if (header.nameEnd == 0) {
  96. if (header.valueEnd == 0) {
  97. return;
  98. }
  99. else {
  100. throw new ServletException
  101. (sm.getString("httpProcessor.parseHeaders.colon"));
  102. }
  103. }
  104.  
  105. String name = new String(header.name, 0, header.nameEnd);
  106. String value = new String(header.value, 0, header.valueEnd);
  107. request.addHeader(name, value);
  108. // do something for some headers, ignore others.
  109. if (name.equals("cookie")) {
  110. Cookie cookies[] = RequestUtil.parseCookieHeader(value);
  111. for (int i = 0; i < cookies.length; i++) {
  112. if (cookies[i].getName().equals("jsessionid")) {
  113. // Override anything requested in the URL
  114. if (!request.isRequestedSessionIdFromCookie()) {
  115. // Accept only the first session id cookie
  116. request.setRequestedSessionId(cookies[i].getValue());
  117. request.setRequestedSessionCookie(true);
  118. request.setRequestedSessionURL(false);
  119. }
  120. }
  121. request.addCookie(cookies[i]);
  122. }
  123. }
  124. else if (name.equals("content-length")) {
  125. int n = -1;
  126. try {
  127. n = Integer.parseInt(value);
  128. }
  129. catch (Exception e) {
  130. throw new ServletException(sm.getString("httpProcessor.parseHeaders.contentLength"));
  131. }
  132. request.setContentLength(n);
  133. }
  134. else if (name.equals("content-type")) {
  135. request.setContentType(value);
  136. }
  137. } //end while
  138. }
  139.  
  140. //解析请求
  141. private void parseRequest(SocketInputStream input, OutputStream output)
  142. throws IOException, ServletException {
  143.  
  144. // Parse the incoming request line
  145. input.readRequestLine(requestLine); //阅读请求行
  146. String method =
  147. new String(requestLine.method, 0, requestLine.methodEnd); //得到请求行的方法,get还是post
  148. String uri = null;
  149. String protocol = new String(requestLine.protocol, 0, requestLine.protocolEnd);//得到请求行的协议。
  150.  
  151. // Validate the incoming request line
  152. if (method.length() < 1) {
  153. throw new ServletException("Missing HTTP request method");
  154. }
  155. else if (requestLine.uriEnd < 1) {
  156. throw new ServletException("Missing HTTP request URI");
  157. }
  158. // Parse any query parameters out of the request URI
  159. int question = requestLine.indexOf("?");
  160. if (question >= 0) {
  161. request.setQueryString(new String(requestLine.uri, question + 1,
  162. requestLine.uriEnd - question - 1)); //给request设置查询字符串。
  163. uri = new String(requestLine.uri, 0, question); //得到uri
  164. }
  165. else {
  166. request.setQueryString(null);
  167. uri = new String(requestLine.uri, 0, requestLine.uriEnd);
  168. }
  169.  
  170. // Checking for an absolute URI (with the HTTP protocol) 查看是不是一个绝对路径
  171. if (!uri.startsWith("/")) {
  172. int pos = uri.indexOf("://");
  173. // Parsing out protocol and host name
  174. if (pos != -1) {
  175. pos = uri.indexOf('/', pos + 3);
  176. if (pos == -1) {
  177. uri = "";
  178. }
  179. else {
  180. uri = uri.substring(pos);
  181. }
  182. }
  183. }
  184.  
  185. // Parse any requested session ID out of the request URI 从uri中解析会话id
  186. String match = ";jsessionid=";
  187. int semicolon = uri.indexOf(match);
  188. if (semicolon >= 0) {
  189. String rest = uri.substring(semicolon + match.length());
  190. int semicolon2 = rest.indexOf(';');
  191. if (semicolon2 >= 0) {
  192. request.setRequestedSessionId(rest.substring(0, semicolon2));
  193. rest = rest.substring(semicolon2);
  194. }
  195. else {
  196. request.setRequestedSessionId(rest);
  197. rest = "";
  198. }
  199. request.setRequestedSessionURL(true);
  200. uri = uri.substring(0, semicolon) + rest;
  201. }
  202. else {
  203. request.setRequestedSessionId(null);
  204. request.setRequestedSessionURL(false); //最终给request设置了一个会话id
  205. }
  206.  
  207. // Normalize URI (using String operations at the moment)
  208. String normalizedUri = normalize(uri);
  209.  
  210. // Set the corresponding request properties
  211. ((HttpRequest) request).setMethod(method);
  212. request.setProtocol(protocol); //给request设置method和协议。
  213. if (normalizedUri != null) {
  214. ((HttpRequest) request).setRequestURI(normalizedUri);
  215. }
  216. else {
  217. ((HttpRequest) request).setRequestURI(uri);//给request设置uri
  218. }
  219.  
  220. if (normalizedUri == null) {
  221. throw new ServletException("Invalid URI: " + uri + "'");
  222. }
  223. }
  224.  
  225. /**
  226. * Return a context-relative path, beginning with a "/", that represents
  227. * the canonical version of the specified path after ".." and "." elements
  228. * are resolved out. If the specified path attempts to go outside the
  229. * boundaries of the current context (i.e. too many ".." path elements
  230. * are present), return <code>null</code> instead.
  231. *
  232. * @param path Path to be normalized
  233. */
  234. protected String normalize(String path) {
  235. if (path == null)
  236. return null;
  237. // Create a place for the normalized path
  238. String normalized = path;
  239.  
  240. // Normalize "/%7E" and "/%7e" at the beginning to "/~"
  241. if (normalized.startsWith("/%7E") || normalized.startsWith("/%7e"))
  242. normalized = "/~" + normalized.substring(4);
  243.  
  244. // Prevent encoding '%', '/', '.' and '\', which are special reserved
  245. // characters
  246. if ((normalized.indexOf("%25") >= 0)
  247. || (normalized.indexOf("%2F") >= 0)
  248. || (normalized.indexOf("%2E") >= 0)
  249. || (normalized.indexOf("%5C") >= 0)
  250. || (normalized.indexOf("%2f") >= 0)
  251. || (normalized.indexOf("%2e") >= 0)
  252. || (normalized.indexOf("%5c") >= 0)) {
  253. return null;
  254. }
  255.  
  256. if (normalized.equals("/."))
  257. return "/";
  258.  
  259. // Normalize the slashes and add leading slash if necessary
  260. if (normalized.indexOf('\\') >= 0)
  261. normalized = normalized.replace('\\', '/');
  262. if (!normalized.startsWith("/"))
  263. normalized = "/" + normalized;
  264.  
  265. // Resolve occurrences of "//" in the normalized path
  266. while (true) {
  267. int index = normalized.indexOf("//");
  268. if (index < 0)
  269. break;
  270. normalized = normalized.substring(0, index) +
  271. normalized.substring(index + 1);
  272. }
  273.  
  274. // Resolve occurrences of "/./" in the normalized path
  275. while (true) {
  276. int index = normalized.indexOf("/./");
  277. if (index < 0)
  278. break;
  279. normalized = normalized.substring(0, index) +
  280. normalized.substring(index + 2);
  281. }
  282.  
  283. // Resolve occurrences of "/../" in the normalized path
  284. while (true) {
  285. int index = normalized.indexOf("/../");
  286. if (index < 0)
  287. break;
  288. if (index == 0)
  289. return (null); // Trying to go outside our context
  290. int index2 = normalized.lastIndexOf('/', index - 1);
  291. normalized = normalized.substring(0, index2) +
  292. normalized.substring(index + 3);
  293. }
  294.  
  295. // Declare occurrences of "/..." (three or more dots) to be invalid
  296. // (on some Windows platforms this walks the directory tree!!!)
  297. if (normalized.indexOf("/...") >= 0)
  298. return (null);
  299.  
  300. // Return the normalized path that we have completed
  301. return (normalized);
  302.  
  303. }
  304.  
  305. }

HttpProcessor

这个类比较复杂,主要就是创建Request对象和Response对象,在实现上,使用了process方法。可以依次解释:

首先,这个类需要字段,毋庸置疑,有Request对象和Response对象,其他不是很重要。

可以先来看Request对象:

  1. package test.servlet3.connector.http;
  2.  
  3. import org.apache.catalina.util.Enumerator;
  4. import org.apache.catalina.util.ParameterMap;
  5. import org.apache.catalina.util.RequestUtil;
  6.  
  7. import javax.servlet.RequestDispatcher;
  8. import javax.servlet.ServletInputStream;
  9. import javax.servlet.http.Cookie;
  10. import javax.servlet.http.HttpServletRequest;
  11. import javax.servlet.http.HttpSession;
  12. import java.io.*;
  13. import java.net.InetAddress;
  14. import java.net.Socket;
  15. import java.security.Principal;
  16. import java.text.SimpleDateFormat;
  17. import java.util.*;
  18.  
  19. public class HttpRequest implements HttpServletRequest {
  20.  
  21. private String contentType;
  22. private int contentLength;
  23. private InetAddress inetAddress;
  24. private InputStream input;
  25. private String method;
  26. private String protocol;
  27. private String queryString;
  28. private String requestURI;
  29. private String serverName;
  30. private int serverPort;
  31. private Socket socket;
  32. private boolean requestedSessionCookie;
  33. private String requestedSessionId;
  34. private boolean requestedSessionURL;
  35.  
  36. /**
  37. * The request attributes for this request.
  38. */
  39. protected HashMap attributes = new HashMap();
  40. /**
  41. * The authorization credentials sent with this Request.
  42. */
  43. protected String authorization = null;
  44. /**
  45. * The context path for this request.
  46. */
  47. protected String contextPath = "";
  48. /**
  49. * The set of cookies associated with this Request.
  50. */
  51. protected ArrayList cookies = new ArrayList();
  52. /**
  53. * An empty collection to use for returning empty Enumerations. Do not
  54. * add any elements to this collection!
  55. */
  56. protected static ArrayList empty = new ArrayList();
  57. /**
  58. * The set of SimpleDateFormat formats to use in getDateHeader().
  59. */
  60. protected SimpleDateFormat formats[] = {
  61. new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US),
  62. new SimpleDateFormat("EEEEEE, dd-MMM-yy HH:mm:ss zzz", Locale.US),
  63. new SimpleDateFormat("EEE MMMM d HH:mm:ss yyyy", Locale.US)
  64. };
  65.  
  66. /**
  67. * The HTTP headers associated with this Request, keyed by name. The
  68. * values are ArrayLists of the corresponding header values.
  69. */
  70. protected HashMap headers = new HashMap();
  71. /**
  72. * The parsed parameters for this request. This is populated only if
  73. * parameter information is requested via one of the
  74. * <code>getParameter()</code> family of method calls. The key is the
  75. * parameter name, while the value is a String array of values for this
  76. * parameter.
  77. * <p>
  78. * <strong>IMPLEMENTATION NOTE</strong> - Once the parameters for a
  79. * particular request are parsed and stored here, they are not modified.
  80. * Therefore, application level access to the parameters need not be
  81. * synchronized.
  82. */
  83. protected ParameterMap parameters = null;
  84.  
  85. /**
  86. * Have the parameters for this request been parsed yet?
  87. */
  88. protected boolean parsed = false;
  89. protected String pathInfo = null;
  90.  
  91. /**
  92. * The reader that has been returned by <code>getReader</code>, if any.
  93. */
  94. protected BufferedReader reader = null;
  95.  
  96. /**
  97. * The ServletInputStream that has been returned by
  98. * <code>getInputStream()</code>, if any.
  99. */
  100. protected ServletInputStream stream = null;
  101.  
  102. public HttpRequest(InputStream input) {
  103. this.input = input;
  104. }
  105.  
  106. public void addHeader(String name, String value) {
  107. name = name.toLowerCase();
  108. synchronized (headers) {
  109. ArrayList values = (ArrayList) headers.get(name);
  110. if (values == null) {
  111. values = new ArrayList();
  112. headers.put(name, values);
  113. }
  114. values.add(value);
  115. }
  116. }
  117.  
  118. /**
  119. * Parse the parameters of this request, if it has not already occurred.
  120. * If parameters are present in both the query string and the request
  121. * content, they are merged.
  122. */
  123. protected void parseParameters() {
  124. if (parsed)
  125. return;
  126. ParameterMap results = parameters;
  127. if (results == null)
  128. results = new ParameterMap();
  129. results.setLocked(false);
  130. String encoding = getCharacterEncoding();
  131. if (encoding == null)
  132. encoding = "ISO-8859-1";
  133.  
  134. // Parse any parameters specified in the query string
  135. String queryString = getQueryString();
  136. try {
  137. RequestUtil.parseParameters(results, queryString, encoding);
  138. }
  139. catch (UnsupportedEncodingException e) {
  140. ;
  141. }
  142.  
  143. // Parse any parameters specified in the input stream
  144. String contentType = getContentType();
  145. if (contentType == null)
  146. contentType = "";
  147. int semicolon = contentType.indexOf(';');
  148. if (semicolon >= 0) {
  149. contentType = contentType.substring(0, semicolon).trim();
  150. }
  151. else {
  152. contentType = contentType.trim();
  153. }
  154. if ("POST".equals(getMethod()) && (getContentLength() > 0)
  155. && "application/x-www-form-urlencoded".equals(contentType)) {
  156. try {
  157. int max = getContentLength();
  158. int len = 0;
  159. byte buf[] = new byte[getContentLength()];
  160. ServletInputStream is = getInputStream();
  161. while (len < max) {
  162. int next = is.read(buf, len, max - len);
  163. if (next < 0 ) {
  164. break;
  165. }
  166. len += next;
  167. }
  168. is.close();
  169. if (len < max) {
  170. throw new RuntimeException("Content length mismatch");
  171. }
  172. RequestUtil.parseParameters(results, buf, encoding);
  173. }
  174. catch (UnsupportedEncodingException ue) {
  175. ;
  176. }
  177. catch (IOException e) {
  178. throw new RuntimeException("Content read fail");
  179. }
  180. }
  181.  
  182. // Store the final results
  183. results.setLocked(true);
  184. parsed = true;
  185. parameters = results;
  186. }
  187.  
  188. public void addCookie(Cookie cookie) {
  189. synchronized (cookies) {
  190. cookies.add(cookie);
  191. }
  192. }
  193.  
  194. /**
  195. * Create and return a ServletInputStream to read the content
  196. * associated with this Request. The default implementation creates an
  197. * instance of RequestStream associated with this request, but this can
  198. * be overridden if necessary.
  199. *
  200. * @exception IOException if an input/output error occurs
  201. */
  202. public ServletInputStream createInputStream() throws IOException {
  203. return (new RequestStream(this));
  204. }
  205.  
  206. public InputStream getStream() {
  207. return input;
  208. }
  209. public void setContentLength(int length) {
  210. this.contentLength = length;
  211. }
  212.  
  213. public void setContentType(String type) {
  214. this.contentType = type;
  215. }
  216.  
  217. public void setInet(InetAddress inetAddress) {
  218. this.inetAddress = inetAddress;
  219. }
  220.  
  221. public void setContextPath(String path) {
  222. if (path == null)
  223. this.contextPath = "";
  224. else
  225. this.contextPath = path;
  226. }
  227.  
  228. public void setMethod(String method) {
  229. this.method = method;
  230. }
  231.  
  232. public void setPathInfo(String path) {
  233. this.pathInfo = path;
  234. }
  235.  
  236. public void setProtocol(String protocol) {
  237. this.protocol = protocol;
  238. }
  239.  
  240. public void setQueryString(String queryString) {
  241. this.queryString = queryString;
  242. }
  243.  
  244. public void setRequestURI(String requestURI) {
  245. this.requestURI = requestURI;
  246. }
  247. /**
  248. * Set the name of the server (virtual host) to process this request.
  249. *
  250. * @param name The server name
  251. */
  252. public void setServerName(String name) {
  253. this.serverName = name;
  254. }
  255. /**
  256. * Set the port number of the server to process this request.
  257. *
  258. * @param port The server port
  259. */
  260. public void setServerPort(int port) {
  261. this.serverPort = port;
  262. }
  263.  
  264. public void setSocket(Socket socket) {
  265. this.socket = socket;
  266. }
  267.  
  268. /**
  269. * Set a flag indicating whether or not the requested session ID for this
  270. * request came in through a cookie. This is normally called by the
  271. * HTTP Connector, when it parses the request headers.
  272. *
  273. * @param flag The new flag
  274. */
  275. public void setRequestedSessionCookie(boolean flag) {
  276. this.requestedSessionCookie = flag;
  277. }
  278.  
  279. public void setRequestedSessionId(String requestedSessionId) {
  280. this.requestedSessionId = requestedSessionId;
  281. }
  282.  
  283. public void setRequestedSessionURL(boolean flag) {
  284. requestedSessionURL = flag;
  285. }
  286.  
  287. /* implementation of the HttpServletRequest*/
  288. public Object getAttribute(String name) {
  289. synchronized (attributes) {
  290. return (attributes.get(name));
  291. }
  292. }
  293.  
  294. public Enumeration getAttributeNames() {
  295. synchronized (attributes) {
  296. return (new Enumerator(attributes.keySet()));
  297. }
  298. }
  299.  
  300. public String getAuthType() {
  301. return null;
  302. }
  303.  
  304. public String getCharacterEncoding() {
  305. return null;
  306. }
  307.  
  308. public int getContentLength() {
  309. return contentLength ;
  310. }
  311.  
  312. public String getContentType() {
  313. return contentType;
  314. }
  315.  
  316. public String getContextPath() {
  317. return contextPath;
  318. }
  319.  
  320. public Cookie[] getCookies() {
  321. synchronized (cookies) {
  322. if (cookies.size() < 1)
  323. return (null);
  324. Cookie results[] = new Cookie[cookies.size()];
  325. return ((Cookie[]) cookies.toArray(results));
  326. }
  327. }
  328.  
  329. public long getDateHeader(String name) {
  330. String value = getHeader(name);
  331. if (value == null)
  332. return (-1L);
  333.  
  334. // Work around a bug in SimpleDateFormat in pre-JDK1.2b4
  335. // (Bug Parade bug #4106807)
  336. value += " ";
  337.  
  338. // Attempt to convert the date header in a variety of formats
  339. for (int i = 0; i < formats.length; i++) {
  340. try {
  341. Date date = formats[i].parse(value);
  342. return (date.getTime());
  343. }
  344. catch (ParseException e) {
  345. ;
  346. }
  347. }
  348. throw new IllegalArgumentException(value);
  349. }
  350.  
  351. public String getHeader(String name) {
  352. name = name.toLowerCase();
  353. synchronized (headers) {
  354. ArrayList values = (ArrayList) headers.get(name);
  355. if (values != null)
  356. return ((String) values.get(0));
  357. else
  358. return null;
  359. }
  360. }
  361.  
  362. public Enumeration getHeaderNames() {
  363. synchronized (headers) {
  364. return (new Enumerator(headers.keySet()));
  365. }
  366. }
  367.  
  368. public Enumeration getHeaders(String name) {
  369. name = name.toLowerCase();
  370. synchronized (headers) {
  371. ArrayList values = (ArrayList) headers.get(name);
  372. if (values != null)
  373. return (new Enumerator(values));
  374. else
  375. return (new Enumerator(empty));
  376. }
  377. }
  378.  
  379. public ServletInputStream getInputStream() throws IOException {
  380. if (reader != null)
  381. throw new IllegalStateException("getInputStream has been called");
  382.  
  383. if (stream == null)
  384. stream = createInputStream();
  385. return (stream);
  386. }
  387.  
  388. public int getIntHeader(String name) {
  389. String value = getHeader(name);
  390. if (value == null)
  391. return (-1);
  392. else
  393. return (Integer.parseInt(value));
  394. }
  395.  
  396. public Locale getLocale() {
  397. return null;
  398. }
  399.  
  400. public Enumeration getLocales() {
  401. return null;
  402. }
  403.  
  404. public String getMethod() {
  405. return method;
  406. }
  407.  
  408. public String getParameter(String name) {
  409. parseParameters();
  410. String values[] = (String[]) parameters.get(name);
  411. if (values != null)
  412. return (values[0]);
  413. else
  414. return (null);
  415. }
  416.  
  417. public Map getParameterMap() {
  418. parseParameters();
  419. return (this.parameters);
  420. }
  421.  
  422. public Enumeration getParameterNames() {
  423. parseParameters();
  424. return (new Enumerator(parameters.keySet()));
  425. }
  426.  
  427. public String[] getParameterValues(String name) {
  428. parseParameters();
  429. String values[] = (String[]) parameters.get(name);
  430. if (values != null)
  431. return (values);
  432. else
  433. return null;
  434. }
  435.  
  436. public String getPathInfo() {
  437. return pathInfo;
  438. }
  439.  
  440. public String getPathTranslated() {
  441. return null;
  442. }
  443.  
  444. public String getProtocol() {
  445. return protocol;
  446. }
  447.  
  448. public String getQueryString() {
  449. return queryString;
  450. }
  451.  
  452. public BufferedReader getReader() throws IOException {
  453. if (stream != null)
  454. throw new IllegalStateException("getInputStream has been called.");
  455. if (reader == null) {
  456. String encoding = getCharacterEncoding();
  457. if (encoding == null)
  458. encoding = "ISO-8859-1";
  459. InputStreamReader isr =
  460. new InputStreamReader(createInputStream(), encoding);
  461. reader = new BufferedReader(isr);
  462. }
  463. return (reader);
  464. }
  465.  
  466. public String getRealPath(String path) {
  467. return null;
  468. }
  469.  
  470. public int getRemotePort() {
  471. return 0;
  472. }
  473.  
  474. public String getLocalName() {
  475. return null;
  476. }
  477.  
  478. public String getLocalAddr() {
  479. return null;
  480. }
  481.  
  482. public int getLocalPort() {
  483. return 0;
  484. }
  485.  
  486. public String getRemoteAddr() {
  487. return null;
  488. }
  489.  
  490. public String getRemoteHost() {
  491. return null;
  492. }
  493.  
  494. public String getRemoteUser() {
  495. return null;
  496. }
  497.  
  498. public RequestDispatcher getRequestDispatcher(String path) {
  499. return null;
  500. }
  501.  
  502. public String getScheme() {
  503. return null;
  504. }
  505.  
  506. public String getServerName() {
  507. return null;
  508. }
  509.  
  510. public int getServerPort() {
  511. return 0;
  512. }
  513.  
  514. public String getRequestedSessionId() {
  515. return null;
  516. }
  517.  
  518. public String getRequestURI() {
  519. return requestURI;
  520. }
  521.  
  522. public StringBuffer getRequestURL() {
  523. return null;
  524. }
  525.  
  526. public HttpSession getSession() {
  527. return null;
  528. }
  529.  
  530. public HttpSession getSession(boolean create) {
  531. return null;
  532. }
  533.  
  534. public String getServletPath() {
  535. return null;
  536. }
  537.  
  538. public Principal getUserPrincipal() {
  539. return null;
  540. }
  541.  
  542. public boolean isRequestedSessionIdFromCookie() {
  543. return false;
  544. }
  545.  
  546. public boolean isRequestedSessionIdFromUrl() {
  547. return isRequestedSessionIdFromURL();
  548. }
  549.  
  550. public boolean isRequestedSessionIdFromURL() {
  551. return false;
  552. }
  553.  
  554. public boolean isRequestedSessionIdValid() {
  555. return false;
  556. }
  557.  
  558. public boolean isSecure() {
  559. return false;
  560. }
  561.  
  562. public boolean isUserInRole(String role) {
  563. return false;
  564. }
  565.  
  566. public void removeAttribute(String attribute) {
  567. }
  568.  
  569. public void setAttribute(String key, Object value) {
  570. }
  571.  
  572. /**
  573. * Set the authorization credentials sent with this request.
  574. *
  575. * @param authorization The new authorization credentials
  576. */
  577. public void setAuthorization(String authorization) {
  578. this.authorization = authorization;
  579. }
  580.  
  581. public void setCharacterEncoding(String encoding) throws UnsupportedEncodingException {
  582. }
  583. }

HttpRequest

这个类也比较复杂,主要来说,它存储了被解析好的各种字段,

  1. private String contentType;
  2. private int contentLength;
  3. private InetAddress inetAddress;
  4. private InputStream input;
  5. private String method;
  6. private String protocol;
  7. private String queryString;
  8. private String requestURI;

通过get/set函数,我们能得到这些字段。

回到HttpProcessor类,继续往下看,此类是如何创建并封装Request类和Response类的。

  1. response.setRequest(request); //将请求传入
  2. response.setHeader("Server", "Pyrmont Servlet Container"); //设置响应头
  3. //响应里面很多都留空。
  4. parseRequest(input, output); //解析请求
  5. parseHeaders(input);

关键是parseRequest方法和parseHeaders方法。

parseRequest:作用是解析请求,然后封装Request。

封装好request和response对象之后,可以去申请静态资源和servlet资源。此处不讲了。


Tomcat的默认连接器

一个Tomcat连接器必须满以下条件:

Connector接口:重要的三个方法,getContainer,setContainer, createRequest和createResponse。

HttpConnector类:是Connector接口的一个实现。在tomcat后面版本中此实现已经不存在了。

在默认连接器中,HttpConnector拥有一个HttpProcessor对象池,每个HttpProcessor实例拥有一个独立线程。因此,HttpConnector可以同时处理多个HTTP请求。HttpConnector维护一个HttpProcessor的实例池,从而避免每次创建HttpProcessor实例。这些HttpProcessor实例是存放在一个叫processors的java.io.Stack中:

  1. private Stack processors = new Stack();

每个HttpProcessor实例负责解析HTTP请求行和头部,并填充请求对象。因此,每个实例关联着一个请求对象和响应对象。类HttpProcessor 的构造方法包括了类HttpConnector 的createRequest和createResponse方法的调用。

HttpConnector类 为Http请求服务,

  1. while (!stopped) {
  2. Socket socket = null;
  3. try {
  4. socket = serverSocket.accept();
  5. ...

对于每一个前来的http请求,会通过createProcessor方法来获取一个HttpProcessor实例。这里大多数情况HttpProcessor实例并不是创建一个新的实例,而是从池子里面获取。如果已经达到池子的最大数量,没有实例可取,那么套接字就会简单关闭,前来的请求不会被处理。

  1. if (processor == null) {
  2. try {
  3. log(sm.getString("httpConnector.noProcessor"));
  4. socket.close();
  5. }
  6. ...
  7. continue;

而得到的HttpProcessor实例实例用于读取套接字的输入流,解析http请求的工作。

  1. processor.assign(socket);

assign方法不会等到HttpProcessor完成解析工作,而是必须马上返回,以便下一个前来的HTTP请求可以被处理。每个HttpProcessor实例有自己的线程用于解析。

HttpProcessor类让assign方法异步化,HttpProcessor 类实现了java.lang.Runnable 接口,并且每个HttpProcessor 实例运行在称作处理器线程(processor thread)的自身线程上,对HttpConnector 创建的每个HttpProcessor 实例,它的start 方法将被调用,有效的启动了HttpProcessor实例的处理线程。

  1. public void run() { // Process requests until we receive a shutdown signal
  2. while (!stopped) { // Wait for the next socket to be assigned
  3. Socket socket = await();
  4. if (socket == null)
  5. continue; // Process the request from this socket
  6. try { process(socket);
  7. }
  8. catch (Throwable t) {
  9. log("process.invoke", t); } // Finish up this request
  10. connector.recycle(this); } // Tell threadStop() we have shut ourselves down successfully
  11. synchronized (threadSync) {
  12. threadSync.notifyAll();
  13. }
  14. }

run方法中的while循环,先去获取一个套接字,处理它,然后调用连接器的recycle方法把当前的HttpProcessor实例退回栈中,

  1. void recycle(HttpProcessor processor) {
  2. processors.push(processor);
  3. }

此处,run方法中while循环在await方法中结束。await方法持有处理线程的控制流,直到从HttpConnector中获取到一个新的套接字。而await方法和assign方法运行在不同的线程上。assign方法从HttpConnector的run方法中调用。我们就说这个线程是HttpConnector实例的run方法运行的处理线程。assign方法是如何通知已经被调用的await方法的?就是通过一个布尔变量available并且使用java.lang.Object的wait和notifyAll方法。

请求对象:

默认连接器哩变得HTTP请求对象指代org.apache.catalina.Request接口。这个接口被类RequestBase直接实现了,也是HttpRequest的父接口。最终的实现是继承于HttpRequest的HttpRequestImpl。

处理请求:在HttpProcessor类的run方法中调用的。process方法会做下面这些工作:


容器:容器是一个处理用户servlet请求并返回对象给web用户的模块,org.apache.catalina.Container接口定义了容器的形式。有四种容器:Engine(引擎), Host(主机), Context(上下文), 和Wrapper(包装器)

容器接口:org.apache.catalina.Container。

容器分类:

Engine:表示整个Catalina的servlet引擎

Host:表示一个拥有数个上下文的虚拟主机

Context:表示一个Web应用,一个context包含一个或多个wrapper

Wrapper:表示一个独立的servlet

每一个概念之上是用org.apache.catalina包来表示的。Engine、Host、Context和Wrapper接口都实现了Container即可。它们的标准实现是StandardEngine,StandardHost, StandardContext, and StandardWrapper,它们都是org.apache.catalina.core包的一部分。

所有的类都扩展自抽象类ContainerBase。

一个容器可以有一个或多个低层次上的子容器。例如,一个Context有一个或多
个wrapper,而wrapper作为容器层次中的最底层,不能包含子容器。一个容器添加到另一容器中可以使用在Container接口中定义的addChild()方法。

  1. public void addChild(Container child);

删除一个容器可以使用Container接口中定义的removeChild()方法。

  1. public void removeChild(Container child);
  1.  

另外容器接口支持子接口查找和获得所有子接口集合的方法findChild和findChildren方法。

  1. public Container findChild(String name);
  2. public Container[] findChildren();

一个容器还包含一系列的部分如Lodder、Loggee、Manager、Realm和Resources。

connector调用容器的Invoke方法后做的工作

Pipelining Tasks(流水线任务):一个pipeline包含了改容器要唤醒的所有任务。每一个阀门表示了一个特定的任务。一个容器的流水线有一个基本的阀门,但是你可以添加任意你想要添加的阀门。阀门的数目定义为添加的阀门的个数(不包括基本阀门)。有趣的是,阀门可以痛苦编辑Tomcat的配置文件server.xml来动态的添加。

一个流水线就像一个过滤链,每一个阀门像一个过滤器。跟过滤器一样,一个阀门可以操作传递给它的request和response方法。让一个阀门完成了处理,则进一步处理流水线中的下一个阀门,基本阀门总是在最后才被调用。

当连接器调用容器的invoke()方法后,容器中要执行的任务并没有硬编码在invoke()方法中,而是容器会调用pipeline中的invoke()方法。管道必须保证添加到其中的所有阀及基础阀都必须被调用一次。通过创建一个ValveContext接口实例来实现的。其中ValveContext重要的方法是invokeNext(),这样管道会遍历所有的阀。

阀是实现了Valve接口的实例。用来处理收到的请求,该接口有两个方法,invoke()方法和getInfo()方法。getInfo方法返回阀的实现信息。

Wrapper接口:

Wrapper级容器的servlet容器表示独立servlet定义。其接口的实现类要负责管理其基础servlet类的servlet生命周期。即调用servlet的init()、service()、destroy()等方法。由于Wrapper已经是最低级的servlet容器,因此不能往里添加子容器。若Wrapper的addChild()方法被调用,则抛异常。

Wrapper接口中比较重要的方法是load()和allocate()方法。allocate()方法会分配一个已经初始化的servlet实例。load方法加载并初始化servlet类。

Context接口:

Context接口的实例表示一个Web应用程序。一个Context实例可以有一个或者多个Wrapper实例作为其子容器。

Context接口中比较重要的方法是addWrapper()和createWrapper()。

Wrapper应用程序:

展示如何编写一个最小的servlet容器。其核心是实现了Wrapper接口的SimpleWrapper类。SimpleWrapper类包含一个Pipeline实例(SimplePipeline),并使用一个Loader实例(SimpleLoader)来载入servlet类。Pipeline实例包含了一个基础阀和两个额外的阀。

SimpleLoader类:在servlet容器中载入相关servlet类的工作由Loader接口的实例完成。它知道servlet类的位置,通过调用其getClassLoader方法可以返回一个ClassLoader实例。可用来搜索servlet类的位置。

  1. public SimpleLoader() {
  2. try {
  3. URL[] urls = new URL[1];
  4. URLStreamHandler streamHandler = null;
  5. File classPath = new File(WEB_ROOT);
  6. String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;
  7. urls[0] = new URL(null, repository, streamHandler);
  8. classLoader = new URLClassLoader(urls);
  9. }
  10. catch (IOException e) {
  11. System.out.println(e.toString() );
  12. }
  13. }

构造函数中的代码会初始化一个类加载器,其中的变量container指向了与该servlet容器相关联的类加载器。

SimplePipeline类:其中最重要的方法invoke()方法。该方法包含一个内部类SimplePipelineValveContext,实现了ValveContext接口。其中一个重要的方法是:invokeNext()。遍历整个pipeline。

SimpleWrapper类:实现了Wrapper接口,提供了allocate方法和load方法的实现。声明了两个变量:loader和parent。load而变量指明了载入servlet类要使用的载入器,parent指明了该Wrapper实例的父容器。

  1. private Loader loader;
  2. protected Container parent = null;
  1. public Loader getLoader() {
  2. if (loader != null)
  3. return (loader);
  4. if (parent != null)
  5. return (parent.getLoader());
  6. return (null);
  7. }

SimpleWrapper类有一个Pipeline实例,并为该Pipeline实例设置了基础阀,

  1. public SimpleWrapper() {
  2. pipeline.setBasic(new SimpleWrapperValve());
  3. }

SimpleWrapperValve类:是一个基础阀,专门用于处理对SimpleWrapper类的请求。实现了Valve, Contained接口。其中最主要的方法是invoke()方法。

  1. public void invoke(Request request, Response response, ValveContext valveContext)
  2. throws IOException, ServletException {
  3.  
  4. SimpleWrapper wrapper = (SimpleWrapper) getContainer();
  5. ServletRequest sreq = request.getRequest();
  6. ServletResponse sres = response.getResponse();
  7. Servlet servlet = null;
  8. HttpServletRequest hreq = null;
  9. if (sreq instanceof HttpServletRequest)
  10. hreq = (HttpServletRequest) sreq;
  11. HttpServletResponse hres = null;
  12. if (sres instanceof HttpServletResponse)
  13. hres = (HttpServletResponse) sres;
  14.  
  15. // Allocate a servlet instance to process this request
  16. try {
  17. servlet = wrapper.allocate();
  18. if (hres!=null && hreq!=null) {
  19. servlet.service(hreq, hres);
  20. }
  21. else {
  22. servlet.service(sreq, sres);
  23. }
  24. }
  25. catch (ServletException e) {
  26. }
  27. }

该方法直接调用wrapper实例的allocate(),获取servlet,然后直接调用service。

另外两个阀是ClientIPLoggerValve和HeaderLoggerValve。

其中ClientIPLoggerValve类所表示的阀用来将客户端的IP地址输出到控制台上。其中也是调用invoke()。invoke()方法中使用invokeNext()方法来调用管道的下一个阀。

其中HeaderLoggerValve类把请求头信息输出到控制台。其中也是调用invoke()。invoke()方法中使用invokeNext()方法来调用管道的下一个阀。

  1. HttpConnector connector = new HttpConnector();
  2. Wrapper wrapper = new SimpleWrapper();
  3. wrapper.setServletClass("ModernServlet");
  4. Loader loader = new SimpleLoader();
  5. Valve valve1 = new HeaderLoggerValve();
  6. Valve valve2 = new ClientIPLoggerValve();
  7.  
  8. wrapper.setLoader(loader);
  9. ((Pipeline) wrapper).addValve(valve1);
  10. ((Pipeline) wrapper).addValve(valve2);
  11.  
  12. connector.setContainer(wrapper);
  13.  
  14. try {
  15. connector.initialize();
  16. connector.start();
  17.  
  18. // make the application wait until we press a key.
  19. System.in.read();
  20. }
  21. catch (Exception e) {
  22. e.printStackTrace();
  23. }

整体来介绍一下该应用:

首先是Bootstrap1类,在该类中创建一个Wrapper实例(SimpleWrapper())。将字符串"Modernservlet"赋值给SimpleWrapper类的setservletClass()方法。告诉Wrapper实例要载入的servlet类的名称。

然后创建了一个载入器和两个阀。并将载入器设置到Wrapper实例中。再将创建的两个阀添加到Wrapper实例的管道中。

最后将Wrapper实例设置为连接器的servlet容器。初始化并启动连接器。

Context应用程序:对于大部分web应用来说,是需要多个servlet合作的,这类应用程序需要的是Context容器。

接下来,展示包含了两个Wrapper实例的Context实例来构建Web应用程序,当应用程序中有多个Wrapper实例的时候,需要使用一个映射器,映射器是组件,帮助servlet容器选择一个子容器来处理某个指定的请求。

SimpleContextMapper类是实现了Mapper接口的映射器。servlet容器可以使用多个映射器来支持不同的协议。在此处,一个映射器支持一个请求协议。例如servlet容器中可以使用一个映射器对HTTP协议的请求进行映射,使用另一个对HTTPS协议的请求进行映射。

Mapper接口的getContainer()方法返回与该映射器相关联的servlet容器的实例。而setContainer()方法则用来将某个servlet容器与该映射器相关联。getProtocol()方法返回该映射器负责处理的协议。setProtocol()方法可以指定该映射器负责处理哪种协议。map()方法返回要处理某个特定请求的子容器的实例。

Context容器是一个SimpleContext类的实例。SimpleContext类使用SimpleContextMapper类的实例作为其映射器,将SimpleContextValve的实例作为其基础阀。Context容器中额外添加两个阀。HeaderLoggerValve和ClientIPLoggerValve。并包含两个Wrapper实例作为其子容器。

  1. HttpConnector connector = new HttpConnector();
  2. Wrapper wrapper1 = new SimpleWrapper();
  3. wrapper1.setName("Primitive");
  4. wrapper1.setServletClass("PrimitiveServlet");
  5. Wrapper wrapper2 = new SimpleWrapper();
  6. wrapper2.setName("Modern");
  7. wrapper2.setServletClass("ModernServlet");
  8.  
  9. Context context = new SimpleContext();
  10. context.addChild(wrapper1);
  11. context.addChild(wrapper2);
  12.  
  13. Valve valve1 = new HeaderLoggerValve();
  14. Valve valve2 = new ClientIPLoggerValve();
  15.  
  16. ((Pipeline) context).addValve(valve1);
  17. ((Pipeline) context).addValve(valve2);
  18.  
  19. Mapper mapper = new SimpleContextMapper();
  20. mapper.setProtocol("http");
  21. context.addMapper(mapper);
  22. Loader loader = new SimpleLoader();
  23. context.setLoader(loader);
  24. // context.addServletMapping(pattern, name);
  25. context.addServletMapping("/Primitive", "Primitive");
  26. context.addServletMapping("/Modern", "Modern");
  27. connector.setContainer(context);
  28. try {
  29. connector.initialize();
  30. connector.start();
  31.  
  32. // make the application wait until we press a key.
  33. System.in.read();
  34. }
  35. catch (Exception e) {
  36. e.printStackTrace();
  37. }

可以看到,启动类创建了一个连接器HttpConnector,然后创建两个 Wrapper实例,并设置servlet名称;然后创建一个Context实例,将两个Wrapper实例添加到Context里面。然后创建两个阀,也添加到这两个容器里面。然后创建一个映射器,将其加到Context容器里面,创建一个Loader 类,将其加到Context容器里面。

SimpleContext类的invoke()方法调用管道的invoke()方法。

  1. public void invoke(Request request, Response response)
  2. throws IOException, ServletException {
  3. pipeline.invoke(request, response);
  4. }

来看一下SimplePipeline类的invoke()方法:

  1. public void invoke(Request request, Response response)
  2. throws IOException, ServletException {
  3. // Invoke the first Valve in this pipeline for this request
  4. (new SimplePipelineValveContext()).invokeNext(request, response);
  5. }

来看一下SimplePipelineValveContext的invokeNext()方法。

  1. public void invokeNext(Request request, Response response)
  2. throws IOException, ServletException {
  3. int subscript = stage;
  4. stage = stage + 1;
  5. // Invoke the requested Valve for the current request thread
  6. if (subscript < valves.length) {
  7. valves[subscript].invoke(request, response, this);
  8. }
  9. else if ((subscript == valves.length) && (basic != null)) {
  10. basic.invoke(request, response, this);
  11. }
  12. else {
  13. throw new ServletException("No valve");
  14. }
  15. }

以上就是Context容器的实现。


生命周期:

Catalina包含很多组件,当Catalina启动时,组件也会一起启动,当Catalina关闭的时候,组件也会一起关闭。例如:当Servlet容器关闭的时候,它必须调用所有已经载入到容器中的servlet类中的destroy()方法,而Session管理器必须将Session对象保存到辅助存储器中。通过实现Lifecycle接口,可以达到统一启动/关闭这些组件的效果。

实现了Lifecycle接口的组件可以触发一个或者多个下面的事件:

  1. String INIT_EVENT = "init";
  2. String START_EVENT = "start";
  3. String BEFORE_START_EVENT = "before_start";
  4. String AFTER_START_EVENT = "after_start";
  5. String STOP_EVENT = "stop";
  6. String BEFORE_STOP_EVENT = "before_stop";
  7. String AFTER_STOP_EVENT = "after_stop";
  8. String DESTROY_EVENT = "destroy";
  9. String PERIODIC_EVENT = "periodic";

当组件启动时,正常会触发3个事件(start、before_start、after_start)。当组件关闭的时候,会触发后3个事件(before_stop、stop、after_stop)。但需要编写相应的事件监听器对这些事件进行响应,事件监听器是LifecycleListener接口。因此生命周期会有三个类型:Lifecycle、LifecycleEvent和LifecycleListener。

Lifecycle接口:Catalina在设计上允许一个组件包含其他组件。servlet容器可以包含载入器、管理器等。父组件负责启动/关闭它的子组件。Catalina的设计使所有的组件都置于其父组件的监护之下,而Catalina的启动类只需要启动一个组件就可以将全部的应用的组件都启动起来了。这种单一启动/关闭机制是通过Lifecycle接口实现的。

Lifecycle接口中最重要的方法是start方法和stop方法。组件必须提供这两个方法的实现,供父组件调用,实现对其的启动和关闭。其他的addLifecycleListener、findLifecycleListeners、removeLifecycleListener三个方法都与该组件上的事件监听器有关。

LifecycleEvent是一个实例,被final修饰。其中三个字段:

  1. private Object data;
  2. private Lifecycle lifecycle;
  3. private String type;

LifecycleListener接口:只有一个lifecycleEvent方法,当事件监听器监听到相关事件发生,就会调用该方法。

LifecycleSupport类:一个事件监听类的管理类,LifecycleSupport类将所有的生命周期监听器存储在一个名为listeners的数组中,并初始化为一个没有元素的数组对象。当调用addLifecycleListener方法时,会创建一个新数组,大小为原来数组的长度+1,然后将原来的所有元素复制在新数组中,并将新的事件监听器添加在新数组中。removeLifecycleListener方法的过程正好相反。fireLifecycleEvent方法会触发一个生命周期事件,首先它会复制监听器的数组,然后调用数组中的每个成员的lifecycleEvent方法,并传入要触发的事件。

建立在Lifecycle接口基础上的应用程序:

SimpleContext类与之前的相比实现了 Lifecycle接口,SimpleContext类引用LifecycleSupport实例,

  1. protected LifecycleSupport lifecycle = new LifecycleSupport(this);

然后去实现Lifecycle接口的方法:

  1. public void addLifecycleListener(LifecycleListener listener) {
  2. lifecycle.addLifecycleListener(listener);
  3. }
  1. public void removeLifecycleListener(LifecycleListener listener) {
  2. lifecycle.removeLifecycleListener(listener);
  3. }

start()

  1. public synchronized void start() throws LifecycleException {
  2. if (started)
  3. throw new LifecycleException("SimpleContext has already started");
  4.  
  5. // Notify our interested LifecycleListeners
  6. lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);
  7. started = true;
  8. try {
  9. // Start our subordinate components, if any
  10. if ((loader != null) && (loader instanceof Lifecycle))
  11. ((Lifecycle) loader).start();
  12.  
  13. // Start our child containers, if any
  14. Container children[] = findChildren();
  15. for (int i = 0; i < children.length; i++) {
  16. if (children[i] instanceof Lifecycle)
  17. ((Lifecycle) children[i]).start();
  18. }
  19.  
  20. // Start the Valves in our pipeline (including the basic),
  21. // if any
  22. if (pipeline instanceof Lifecycle)
  23. ((Lifecycle) pipeline).start();
  24. // Notify our interested LifecycleListeners
  25. lifecycle.fireLifecycleEvent(START_EVENT, null);
  26. }
  27. catch (Exception e) {
  28. e.printStackTrace();
  29. }
  30.  
  31. // Notify our interested LifecycleListeners
  32. lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);
  33. }

start()方法会检查组件是否已经启动过了,如果是,则抛出异常。 如果没有,则去触发事件:

  1. lifecycle.fireLifecycleEvent(BEFORE_START_EVENT, null);

这样SimpleContext实例中对该事件进行监听的所有监听器都会收到通知。接下来,start方法将started的布尔值设置为true,表明组件已经启动。

然后继续去启动SimpleContext实例的组件,Loader组件、pipeline组件、以及Wrapper子容器都实现了Lifecycle接口,都可以运行其start方法去启动。当所有组件都启动完毕,start方法会触发两个事件,

  1. lifecycle.fireLifecycleEvent(START_EVENT, null);
  1. lifecycle.fireLifecycleEvent(AFTER_START_EVENT, null);

而stop方法的实现与start逻辑相同。

SimpleContextLifecycleListener类实现了LifecycleListener接口,实现了lifecycleEvent方法,

  1. public void lifecycleEvent(LifecycleEvent event) {
  2. Lifecycle lifecycle = event.getLifecycle();
  3. System.out.println("SimpleContextLifecycleListener's event " +
  4. event.getType().toString());
  5. if (Lifecycle.START_EVENT.equals(event.getType())) {
  6. System.out.println("Starting context.");
  7. }
  8. else if (Lifecycle.STOP_EVENT.equals(event.getType())) {
  9. System.out.println("Stopping context.");
  10. }
  11. }

输出已触发事件的类型。


日志记录器:用来记录消息的组件。

Logger接口:Tomcat的日志记录器都必须实现该接口。暂时不说,此接口已不存在


载入器:一个标准的web应用程序的载入器。servlet容器需要实现一个自定义的载入器,而不能简单的使用系统的载入器。因为servlet容器不应该完全信任它正在运行的servlet类,如果使用一个系统类的载入器载入某个servlet类所使用的全部类,那么servlet就能访问所有的类,包括当前运行的java虚拟机中环境变量指明的路径下的所有类和库。而servlet只允许载入WEB-INF/classes目录下及其子目录下的类或者WEB-INF/lib下的类。tomcat需要实现自定义载入器的另一个原因是,为了提高自动重载的功能。当WEB-INF/classes目录和WEB-INF/lib目录下的类发生变化的时候,web应用程序会重新载入这些类。

先介绍java的类载入器:每次创建java实例的时候,都必须将类载入到内存去,jvm使用类载入器来载入需要的类,一般情况下,类载入器会在java核心库里面和classpath中指明的目录中搜索相关类。如果找不到这些类,它会抛出类找不到异常。

jvm使用了3中类载入器:引导类载入器(bootstrap class loader)、扩展类载入器(extension class loader)、系统类载入器(system class loader)。3个类载入器之间是父子继承关系。其中引导类在最上层。系统类在最下层。

Tomcat要使用自定义载入器的原因:

在载入web应用程序中需要的servlet类及其相关类时需要遵守一些明确的规则,应用程序中的servlet类只能引用部署在WEB_INF/calsses目录下的类。但是servelt不能访问其他路径的类,即使这些类在包含运行tomcat的jvm的环境变量下,而servlet类只能访问WEB-INF/lib目录下的库。

Loader接口:

Tomcat中的载入器指的是web应用程序的载入器,而不仅仅是指类载入器。载入器必须实现Loader接口。在实现中,会使用一个自定义的类载入器。是WebappClassLoader类的实例,可以使用Loader接口的getclassloader方法来获取web载入器中classLoader类的实例。

Loader接口还定义了一些方法来对仓库的集合进行操作,web程序的WEB-INF/classes目录下及其子目录下的类或者WEB-INF/lib目录是作为仓库添加到类载入器的,使用Loader接口的addRepository方法来添加一个新仓库,而findRepositories方法所有已添加仓库的数组对象。

Catalina提供了WebappLoader类作为Loader接口的实现,其中WebappLoader对象中使用了WebappClassLoader类的实例作为其类载入器,该类继承于URLclassLoader类。

ReLoader接口:支持类的自动重载功能。

WebappLoader类:

当调用WebappLoader类的start方法时,

1.创建一个类载入器

2.设置仓库

3.设置类路径

4.设置访问权限

5.启动一个新线程来支持自动重载。

WebappClassLoader类,是负责载入类的类加载器,继承于URLClassLoader类。


Session管理:Catalina通过session管理器的组件来管理建立的session对象。该组件由Manager接口表示。Session管理器需要与一个Context容器相关联。Session管理器负责创建、更新、销毁session对象,当有请求到来时,要返回一个有效的session对象。

Session对象:

Session接口:作为catalina内部的Facade类使用

 
 

Tomcat之如何自己做一个tomcat的更多相关文章

  1. 【tomcat ecplise】新下载一个tomcat,无法成功启动,或者启动了无法访问localhost:8080页面/ecplise无法添加新的tomcat/ecplise启动tomcat启动不起来

    今天转头使用ecplise,于是新下载一个tomcat7来作为服务器使用 但是问题来了: [问题1:全新的tomcat启动即消耗了不可思议的时间,并且启动了之前其他tomcat中的很多项目] [注意: ...

  2. tomcat 7 用mod_jk做 负载均衡

    在Win7中使用apache为tomcat做负载均衡,各组件及版本如下: 两个tomcat v 7.0.57 一个apache v 2.2.14 一个mod_jk v 1.2.33(for windo ...

  3. 一个tomcat部署多个应用实例总结

    项目组有好几个项目需要运行,之前项目少,一个tomcat对应一个项目还能应付,但现在项目多了,要是再一个tomcat对应一个项目的话,一方面看起来很业余,一方面也加大服务器的维护难度.所以现在需要对t ...

  4. 构建Logstash+tomcat镜像(让logstash收集tomcat日志)

    1.首先pull logstash镜像作为父镜像(logstash的Dockerfile在最下面): 2.构建my-logstash镜像,使其在docker镜像实例化时,可以使用自定义的logstas ...

  5. 做一个有产品思维的研发:部署(Tomcat配置,Nginx配置,JDK配置)

    每天10分钟,解决一个研发问题. 如果你想了解我在做什么,请看<做一个有产品思维的研发:课程大纲>传送门:https://www.cnblogs.com/hunttown/p/104909 ...

  6. 一个Tomcat及一个ip,绑定不同的域名,各个域名访问各自不同应用程序的配置方法

    http://nickandmiles.blog.163.com/blog/static/23422123201110151492166/ 条件是:这样一种实际情况是,就一台服务器,当公网的IP地址也 ...

  7. 通过一个tomcat端口访问多个tomcat项目 tomcat转发

    需求是这样的,有一个tomcat,是80端口,现在我要通过这个tomcat转发到服务器其他tomcat,其他tomcat的端口不是80.这样做就可以避免这样www.baidu.com:8081的情况. ...

  8. Docker实战之创建一个tomcat容器

    一.Docker与虚拟机的区别 二.Docker学习步骤 2.1:安装宿主操作系统 在VMVare中安装了Ubuntu 16.04.2 LTS (GNU/Linux 4.4.0-62-generic ...

  9. 一个Tomcat配置参数引发的血案

    转载:https://mp.weixin.qq.com/s/3IuTcDCTB3yIovp6o_vuKA 一.现象 有用户反馈访问PC首页偶尔会出现白页情况,也偶尔会收到听云的报警短信 二.监控(听云 ...

随机推荐

  1. 用Python来搞副业?这届大学生到底有多野……

    最近,我在知乎上偶然发现一个有意思的问题: 「大学生实习被当作廉价劳动力,你怎么看?」 很多人学习python,不知道从何学起.很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手.很 ...

  2. Linux学习笔记之ubuntu安装与配置

    1.打开虚拟机,点击新建虚拟机 2.安装向导 选择自定义安装 点击包含一个空白的硬盘 选择linux操作系统,版本是ubuntu 设置虚拟机的名称,可以自己写,还有保存的位置也可自选 根据自己电脑性能 ...

  3. 2020-05-26:TCP四次挥手过程?

    福哥答案2020-05-26:

  4. Android 开发学习进程0.16 layout_weight属性 R文件关联XML Module

    layout_weight属性 layout_weight属性我们常常用到,但有时候会发现它还有一些奇怪的属性,比如大多数使用时会把宽度设置成0,但要是宽度不设置成0会有什么效果? layout_we ...

  5. 调试备忘录-RS485 MODBUS RTU协议简述

    目录--点击可快速直达 目录 写在前面 先简单说下什么是MODBUS? 参考文章 写在前面 最近在做和物联网有关的小项目,有一个传感器通讯用到了RS485 MODBUS RTU协议,所以就写个随笔记录 ...

  6. 使用Axure设计基于中继器的左侧导航菜单

    实现效果: 使用组件: 设计详解: 一.设计外层菜单 1.拖一个矩形,在属性栏中命名cd1,设置宽高为200*45,背景色#393D49,双击设置按钮名称为“默认展开”,字体大小16,字体颜色#C2C ...

  7. 走正确的路 - IT业没有护城河 - 机器翻译新锐Deepl

    最近发生了一件很令我震惊的事情:新的一个机器翻译网站出现了 - www.deepl.com (DeepL 或许会成为你今年首选的翻译工具) 机器翻译早就是红海市场了.我就不从1954年IBM发布俄翻英 ...

  8. 关于MapReduce默认分区策略

    MapReduce默认分区策略 mapreduce 默认的分区方式是hashPartition,在这种分区方式下,KV对根据key的hashcode值与reduceTask个数进行取模,决定该键值对该 ...

  9. Java 泛型(参数化类型)

    Java 泛型 Java 泛型(generics)是 JDK 5 中引入的一个新特性, 泛型提供了编译时类型安全检测机制,该机制允许程序员在编译时检测到非法的类型. 泛型的本质是参数化类型,也就是说所 ...

  10. JavaScript学习系列博客_20_JavaScript 作用域

    作用域 - 作用域指一个变量的作用的范围 - 在JS中一共有两种作用域 1.全局作用域 - 直接编写在script标签中的JS代码,都在全局作用域- 全局作用域在页面打开时创建,在页面关闭时销毁 - ...