一个由Request和response组成的极简servlet web server

  说明与前提:服务主程序并没有把浏览器传递进来的数据全部解析给request对象的诸属性,仅仅是解析了uri请求路径。不关注具体的解析算法!另外response也没有对应的生命周          期,供主程序控制,比如init方法等初始化response的所有属性。

  代码结构:

  截图工具不好用,该项目不包含划黑线的类。另:给组件开发程序员开发的servlet子类组件,保存在该程序目录下的webroot目录中,截图没有体现出来。

  • HttpServer
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{
    /**
     * 在上一个server的基础上进行了演进,仍然是server主程序掌控所有的组件,此程序增加了处理servlet请求的功能。
     * server1直接调用reponse对象的响应静态请求资源,即响应体,而没有设置其他响应属性;(可能是对于socket和流一无所知,不清楚响应体其他内容在哪里)
     * server2主程序判断请求方式,然而response并不是直接处理,而是解耦出了专门的处理类:
     *               静态请求调用响应对象的响应方法;响应对象有必要聚合request吗?响应对象如何传递res/req给servlet?
     */

  /** 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);
    }
    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);

        // 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/")) {//请求方式以servlet开始,servletProcessor
            
          ServletProcessor1 processor = new ServletProcessor1();   
          processor.process(request, response);
          System.out.println("-------------进入处理动态流程");
        }
        else {//否则静态方式处理,staticprocessor
          System.out.println("进入静态资源处理程序");
          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);
      }
    }
  }
}
View Code
  •  Request
import java.io.InputStream;

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

public class Request implements ServletRequest {

  private InputStream input;
  private String uri;

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

  public String getUri() {
    return uri;
  }

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

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

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

  public Enumeration getAttributeNames() {
    return null;
  }

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

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

  public boolean isSecure() {
    return false;
  }

  public String getCharacterEncoding() {
    return null;
  }

  public int getContentLength() {
    return 0;
  }

  public String getContentType() {
    return null;
  }

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

  public Locale getLocale() {
    return null;
  }

  public Enumeration getLocales() {
    return null;
  }

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

  public Map getParameterMap() {
    return null;
  }

  public Enumeration getParameterNames() {
    return null;
  }

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

  public String getProtocol() {
    return null;
  }

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

  public String getRemoteAddr() {
    return null;
  }

  public String getRemoteHost() {
    return null;
  }

  public String getScheme() {
   return null;
  }

  public String getServerName() {
    return null;
  }

  public int getServerPort() {
    return 0;
  }

  public void removeAttribute(String attribute) {
  }

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

  public void setCharacterEncoding(String encoding)
    throws UnsupportedEncodingException {
  }

}
View Code
  • Response
import java.io.OutputStream;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.File;
import java.io.PrintWriter;
import java.util.Locale;
import javax.servlet.ServletResponse;
import javax.servlet.ServletOutputStream;

public class Response implements ServletResponse {

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

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

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

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


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

  public int getBufferSize() {
    return 0;
  }

  public String getCharacterEncoding() {
    return null;
  }

  public Locale getLocale() {
    return null;
  }

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

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

  public boolean isCommitted() {
    return false;
  }

  public void reset() {
  }

  public void resetBuffer() {
  }

  public void setBufferSize(int size) {
  }

  public void setContentLength(int length) {
  }

  public void setContentType(String type) {
  }

  public void setLocale(Locale locale) {
  }
}
View Code
  • ServletProcessor
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);//截取请求中的servletName
    URLClassLoader loader = null; 

    try {
      // create a URLClassLoader
      URL[] urls = new URL[1];
      URLStreamHandler streamHandler = null;
      File classPath = new File(Constants.WEB_ROOT); 
      // the forming of repository is taken from the createClassLoader method in
      // org.apache.catalina.startup.ClassLoaderFactory
      String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString() ;
      System.out.println("-----------------servelt放在哪里?"+repository);
      // the code for forming the URL is taken from the addRepository method in
      // org.apache.catalina.loader.StandardClassLoader class.
      urls[0] = new URL(null, repository, streamHandler);
      loader = new URLClassLoader(urls);//类加载器实例化
    }
    catch (IOException e) {
    System.out.println("---------------------没有找到servlet");
      System.out.println(e.toString() );
    }
    Class myClass = null;
    try {
      myClass = loader.loadClass(servletName);//加载请求的servlet类
    }
    catch (ClassNotFoundException e) {
        System.out.println("--------------------------------从指定路径中加载请求servlet失败");
      System.out.println(e.toString());
    }

    Servlet servlet = null;

    try {
      servlet = (Servlet) myClass.newInstance();//父类指向子类,即servlet已经融入进了程序中,貌似模板模式,让实现延迟,但使用在先。
      servlet.service((ServletRequest) request, (ServletResponse) response);//req、res在向上转型,暂不关注。由此依赖对象传递了进来!
    }
    catch (Exception e) {
      System.out.println(e.toString());
    }
    catch (Throwable e) {
      System.out.println(e.toString());
    }

  }
}
View Code
  • StaticResourceProcessor
import java.io.IOException;

public class StaticResourceProcessor {

  public void process(Request request, Response response) {
    try {
      response.sendStaticResource();//直接调用响应对象的静态处理,因为响应对象可以根据近请求路径直接获得静态请求的响应体
    }
    catch (IOException e) {
      e.printStackTrace();
    }
  }
}
View Code

  代码分析:

      类关系:HttpServer类控制其他组件(虽然还没有完整的生命周期);Request类演进为实现ServletRequest并依赖Socket的input,与其是聚合关系,说明很大程度上          依赖input解析出请求对象的固有属性;Response依赖socket的output和request,与其为聚合关系,除响应体外,好像响应头、行并没有很大程度上依赖            request;ServletProcessor在方法中依赖req/res两个对象,采用模版模式把它 们传递给servlet接口的实现类(即动态加载用户请求的组件开发程序员实现的          servlet);staticResourceProcessor同servletProcessor。

          对象关系:HttpServer作为主程序,控制所有组件:创建Request,传参input并控制其解析;创建reponse传参output。根据请求方式调用不同的processor(个人以为应          该对request/response完善生命周期,并且把周期的其他阶段交给processor控制,比如设置响应体并发送响应,以做到解耦)。

        代码精粹:ServletProcessor的Processor(res,req),利用了java的动态加载,这里简化了Tomcat根据部署描述符解析servlet子类组件的过程,去指定路径下加载请           求的servlet,并使用模版模式延迟servlet接口的实现给组件开发者,指向其实现类的同时processor传递req/res参数,得到了良好的解耦效果。只是res/req           在此次演进中虽然实现了req/res接口,但是并没有实现一些必要方法,比如getoutput,且res实现类的output参数不能被res接口的声明所访问,因此servlet              没能写入响应体。

        测试操作:编写servlet接口的实现类,即模拟组件开发程序员编写一个servlet程序,该servlet组件依赖res/req做出动态处理。可以单独创建文件,引进servlet.jar包,            编写servlet实现类,编译,复制到该程序的webroot,启动程序,浏览器请求该servlet,控制台输出servlet打印语句,测试通过!

        笔记一下:该程序还有一个演进,就是笔记起始处的代码结构中包含了划线的类,req、res都添加了一个门面facedRequest..同样是实现servletRequest,只是把req作      为参数传递进去,具体意义不是很清楚。在这里笔记一下,以其他时刻回头来看能作为回忆的依据。

           

  

原文地址:https://www.cnblogs.com/10000miles/p/9211407.html