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

时间:2021-10-11 21:43:34

app1

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

回顾我们上一章,我们开发了一个最最简单的web服务器,它可以使用户访问服务器内的静态资源。当然这是远远不够的,在这一节里,我们就试着让服务器在能相应静态资源的基础上继续支持servlet。

servlet接口

javax.servlet.Servlet接口定义了五个方法,如下:

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

我们所使用的servlet都是Servlet接口的间接实现类。

每当我们实例化一个servlet的时候,servlet容器都会先唯一的调用一次init()方法进行初始化,然后再调用service()方法来处理用户的需求,最后在销毁servlet前容器会调用destroy()方法。

我们看看,这一节我们要用的测试servlet。

import javax.servlet.*;
import com.jspsmart.upload.Request;

import java.io.IOException;
import java.io.PrintWriter;

public class PrimitiveServlet implements Servlet {

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

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

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

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

}

Servlet定义的5个方法,它都实现了(不过我们这一节要实现的servlet还没有能力自动调用init和destroy方法)。





再看看我们的主方法,程序就从这里开始(和上一节的HttpServer差别不是很大)

package ex02.pyrmont;

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

public class HttpServer1 {

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

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

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

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

    // Loop waiting for a request
    while (!shutdown) {
      Socket socket = null;
      InputStream input = null;
      OutputStream output = null;
      try {
        socket = serverSocket.accept();
        input = socket.getInputStream();
        output = socket.getOutputStream();

        // create Request object and parse
        Request request = new Request(input);
        request.parse();

        // create Response object
        Response response = new Response(output);
        response.setRequest(request);  //没有再这里直接处理静态资源
	                               //而是判断到底请求的事静态资源还是servlet

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

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

大家可以很清楚地看到,这部分和上一节的不同主要就在response部分,更准确的说就是在这

  

if (request.getUri().startsWith("/servlet/")) {
          ServletProcessor1 processor = new ServletProcessor1();
          processor.process(request, response);
        }
        else {
          StaticResourceProcessor processor = new StaticResourceProcessor();
          processor.process(request, response);
        }

我们看看,如果请求是以servlet开头的该如何处理。

package ex02.pyrmont;

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

public class ServletProcessor1 {

  public void process(Request request, Response response) {

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

    URLClassLoader loader = null;

    try {
      // create a URLClassLoader   //try部分的主要功能就是产生一个URLClassLoader
      URL[] urls = new URL[1];
      URLStreamHandler streamHandler = null;  

      File classPath = new File(Constants.WEB_ROOT);
      //下面的URL构造函数为
      //java.net.URL.URL(String protocol, String host, String file) throws MalformedURLException
      String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;

      System.out.println(servletName+"*****"+Constants.WEB_ROOT+"   "+repository);
      //下面的URL构造函数为
      //java.net.URL.URL(URL context, String spec, URLStreamHandler handler) throws MalformedURLException
      //至于 URLStreamHandler是什么东西 暂时不必理会
      urls[0] = new URL(null, repository, streamHandler);
      loader = new URLClassLoader(urls);
    }
    catch (IOException e) {
      System.out.println(e.toString() );
    }
    Class<?> myClass = null;
    try {
      myClass = loader.loadClass(servletName);   //加载请求的servlet

    }
    catch (ClassNotFoundException e) {
      System.out.println(e.toString());
    }

    Servlet servlet = null;

    try {
      servlet = (Servlet) myClass.newInstance();  //生成实例 并调用service方法
      servlet.service((ServletRequest) request, (ServletResponse) response);
    }
    catch (Exception e) {
      System.out.println(e.toString());
    }
    catch (Throwable e) {
      System.out.println(e.toString());
    }

  }

}

看看另一部分,如果请求的不是servlet(这一节就是静态资源)该如何处理

package ex02.pyrmont;

import java.io.IOException;

public class StaticResourceProcessor {

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

跟第一节没有什么区别。

我们的request类要实现ServletRequest接口

package ex02.pyrmont;

import java.io.InputStream;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;

import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class Request implements ServletRequest {

  private InputStream input;
  private String uri;

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

  public String getUri() {
    return uri;
  }

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

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

  public void removeAttribute(String attribute) {
  }

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

  public void setCharacterEncoding(String encoding)
    throws UnsupportedEncodingException {
  }

//缺少的方法 用Eclipse自动生成即可 不再赘述
}

同样的response也要实现ServletResponse接口

package ex02.pyrmont;

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

import com.sun.org.apache.bcel.internal.generic.NEW;

public class Response implements ServletResponse {

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

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

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

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

  public PrintWriter getWriter() throws IOException {
    // autoflush is true, println() will flush,
    // but print() will not.
    writer = new PrintWriter(output, true);
    return writer;
  }
  //一样 部分代码 直接让Eclipse 自动生成即可

}

试验一下

http://localhost:8080/servlet/PrimitiveServlet

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

控制台显示

GET /servlet/PrimitiveServlet HTTP/1.1

Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, 

Accept-Language: zh-cn

User-Agent: Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1)

Accept-Encoding: gzip, deflate

Host: localhost:8080

Connection: Keep-Alive





PrimitiveServlet*****D:\Java Code\UpLoad\webroot   file:D:\Java Code\UpLoad\webroot\

from service

大家仔细看看

Violets are blue. 这句话没有打印出来

大家看看Response类getWriter方法里的PrintWriter一行

上面的英文,我就不解释了

这个bug在以后的版本中会修改

app2

上面的代码其实还存在一个问题

在request部分中parseUri是private的,在这一节中这样其实是可以的,但问题是这个方法有可能在外部类中使用,应该是public的。

如果改成public,问题又出现了

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

我把servlet类中的service改成上面的样子,大家看看,其实request的parseUri方法在servlet里是不应该被使用的!

那怎么办?

第一种,将parseUri方法的public方法改成默认的访问修饰符,包外的类就不能访问了。

不过还有另一种方式

门面模式!!

在上面的例子中,我们写的request实现了ServletRequest,我们可以再写一个类RequestFacade类让他也实现ServletRequest(response 类似)

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

package ex02.pyrmont;

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

public class RequestFacade implements ServletRequest {

  private ServletRequest request = null;

  public RequestFacade(Request request) {
    this.request = request;
  }

    public String getRemoteHost() {
    return request.getRemoteHost();
  }

  //省略对ServletRequest接口的实现
  //servletrequest接口的方法 在RequestFacade 内部实现时 都调用类的属性request来实现

  public void setCharacterEncoding(String encoding)
    throws UnsupportedEncodingException {
    request.setCharacterEncoding(encoding);
  }

}
再看看  ServletProcessor 改成如下

    Servlet servlet = null;
    RequestFacade requestFacade = new RequestFacade(request);
    ResponseFacade responseFacade = new ResponseFacade(response);
    try {
      servlet = (Servlet) myClass.newInstance();
      servlet.service((ServletRequest) requestFacade, (ServletResponse) responseFacade);
    }
    catch (Exception e) {
      System.out.println(e.toString());
    }
    catch (Throwable e) {
      System.out.println(e.toString());
    }
httpServer 也改成如下
 if (request.getUri().startsWith("/servlet/")) {
          ServletProcessor2 processor = new ServletProcessor2();
          processor.process(requestFacade , responseFacade );
        }

app1给servlet里面传递的参数实际上是Request类型的,有调用parseUri方法的危险。

app2给servlet里面传递的参数实际上是RequestFacade,它根本就没有parseUri方法,自然就安全了。







这篇文章中 对书中的源码有删减 大家可以下载完整版本的

深入剖析tomcat 源码

http://down.51cto.com/data/486495