日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

How Tomcat Works(三)

系統(tǒng) 2314 0

上文中描述的簡單的服務(wù)器是不符合Servlet規(guī)范的,所以本文進(jìn)一步描述一個(gè)簡單的Servlet容器是怎么實(shí)現(xiàn)的

所以我們首先要明白Servlet接口規(guī)范,規(guī)范有不同版本,本人就先一視同仁了:

      
        public
      
      
        interface
      
      
         Servlet {
    
      
      
        public
      
      
        void
      
       init(ServletConfig config) 
      
        throws
      
      
         ServletException;      
      
      
        public
      
      
         ServletConfig getServletConfig();
      
      
        public
      
      
        void
      
      
         service(ServletRequest req, ServletResponse res)
    
      
      
            throws
      
      
         ServletException, IOException;
        
public String getServletInfo(); public void destroy(); }

上面的方法中,init() 、service()和 destroy()是與Servlet的生命周期密切相關(guān)的方法,熟悉Servlet生命周期的童鞋是比較清楚的

Servlet容器通常只調(diào)用Servlet實(shí)例的init()方法一次,用于初始化相關(guān)信息;

service()方法用于響應(yīng)客戶端請(qǐng)求,傳入ServletRequest和ServletResponse參數(shù),service()方法會(huì)被多次調(diào)用

當(dāng)Servlet容器關(guān)閉或Servlet容器需要釋放內(nèi)存時(shí),會(huì)調(diào)用Servlet實(shí)例的destroy()方法,用于清理自身持有的資源,如內(nèi)存、文件句柄和線程等,確保所有的持久化狀態(tài)與內(nèi)存中該Servlet對(duì)象的當(dāng)前狀態(tài)同步。

下面我們來看一個(gè)簡單的Servlet容器怎么實(shí)現(xiàn):

HttpServer1類:

      
        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);

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

上面方法中,Servlet容器根據(jù)請(qǐng)求的路徑分發(fā)到不同的處理類進(jìn)行處理,servlet請(qǐng)求交給ServletProcessor1類處理,靜態(tài)資源交給StaticResourceProcessor類處理

注:本文中的Servlet容器跟上文相比,將響應(yīng)請(qǐng)求的功能解耦, 由處理器類(ServletProcessor1類和StaticResourceProcessor類)來承擔(dān)

Request類(注意我們這里的Request類已經(jīng)實(shí)現(xiàn)了ServletRequest 接口,已經(jīng)是按照規(guī)范來搞的了)

      
        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
      
      
        ;
  }
        
      
          /
      
      
        /省略后面的代碼
      
    
      
        }
      
    

Response類(實(shí)現(xiàn)ServletResponse接口)

      
        public
      
      
        class
      
       Response 
      
        implements
      
      
         ServletResponse {

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

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

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

  
      
      
        /*
      
      
         This method is used to serve a static page 
      
      
        */
      
      
        public
      
      
        void
      
       sendStaticResource() 
      
        throws
      
      
         IOException {
    
      
      
        byte
      
      [] bytes = 
      
        new
      
      
        byte
      
      
        [BUFFER_SIZE];
    FileInputStream fis 
      
      = 
      
        null
      
      
        ;
    
      
      
        try
      
      
         {
      
      
      
        /*
      
      
         request.getUri has been replaced by request.getRequestURI 
      
      
        */
      
      
        
      File file 
      
      = 
      
        new
      
      
         File(Constants.WEB_ROOT, request.getUri());
      fis 
      
      = 
      
        new
      
      
         FileInputStream(file);
      
      
      
        /*
      
      
        
         HTTP Response = Status-Line
           *(( general-header | response-header | entity-header ) CRLF)
           CRLF
           [ message-body ]
         Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
      
      
      
        */
      
      
        int
      
       ch = fis.read(bytes, 0
      
        , BUFFER_SIZE);
      
      
      
        while
      
       (ch!=-1
      
        ) {
        output.write(bytes, 
      
      0
      
        , ch);
        ch 
      
      = fis.read(bytes, 0
      
        , BUFFER_SIZE);
      }
    }
    
      
      
        catch
      
      
         (FileNotFoundException e) {
      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;
  }
  
        
           /
        
        
          /省略后面的代碼
        
      
      
        
}
      
    

上面實(shí)現(xiàn)了獲取?PrintWriter對(duì)象的方法

StaticResourceProcessor類(靜態(tài)資源處理)

      
        public
      
      
        class
      
      
         StaticResourceProcessor {

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

方法中僅僅簡單的調(diào)用了response對(duì)象的sendStaticResource()方法

ServletProcessor1類(servlet資源處理類)

      
        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
      
      
      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() ;
      
      
      
        //
      
      
         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(e.toString() );
    }
    Class myClass 
      
      = 
      
        null
      
      
        ;
    
      
      
        try
      
      
         {
      myClass 
      
      =
      
         loader.loadClass(servletName);
    }
    
      
      
        catch
      
      
         (ClassNotFoundException e) {
      System.out.println(e.toString());
    }

    Servlet servlet 
      
      = 
      
        null
      
      
        ;

    
      
      
        try
      
      
         {
      servlet 
      
      =
      
         (Servlet) myClass.newInstance();
      servlet.service((ServletRequest) request, (ServletResponse) response);
    }
    
      
      
        catch
      
      
         (Exception e) {
      System.out.println(e.toString());
    }
    
      
      
        catch
      
      
         (Throwable e) {
      System.out.println(e.toString());
    }

  }
}
      
    

上面的步驟是首先根據(jù)客戶端請(qǐng)求路徑獲取請(qǐng)求的servlet名稱,然后根據(jù)servlet類路徑(類載入器倉庫)創(chuàng)建類載入器,進(jìn)一步根據(jù)servlet名稱載入該servlet類并實(shí)例化,最后調(diào)用該servlet的serice()方法

其中Constants類保持工作目錄常量(Servlet類路徑)

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

我們繼續(xù)分析,其實(shí)上面的ServletProcessor1類的process()方法是存在問題的,在下面的代碼段

      Servlet servlet = 
      
        null
      
      
        ;

    
      
      
        try
      
      
         {
      servlet 
      
      =
      
         (Servlet) myClass.newInstance();
      servlet.service((ServletRequest) request, (ServletResponse) response);
    }
    
      
      
        catch
      
      
         (Exception e) {
      System.out.println(e.toString());
    }
    
      
      
        catch
      
      
         (Throwable e) {
      System.out.println(e.toString());
    }
      
    

這里的Request對(duì)象與Resposne對(duì)象分別向上轉(zhuǎn)型為ServletRequest實(shí)例和ServletResponse實(shí)例

如果了解這個(gè)servlet容器內(nèi)部原理的servlet程序員就可以(在自己實(shí)現(xiàn)的serlet類中)將ServletRequest實(shí)例和 ServletResponse實(shí)例分別向下轉(zhuǎn)型為真實(shí)的Request實(shí)例和Response實(shí)例,就可以調(diào)用各自的公有方法了(Request實(shí)例的 parse()方法和Response實(shí)例的sendStaticResource()方法),而servlet容器又不能將這些公有方法私有化,因?yàn)槠?他外部類還要調(diào)用它們,一個(gè)比較完美的解決方法是分別為Request類和Response類創(chuàng)建外觀類,分別為RequestFacade類與 ResponseFacade類,與前者實(shí)現(xiàn)共同的接口,然后保持對(duì)前者的引用,相關(guān)的接口實(shí)現(xiàn)方法分別調(diào)用其引用實(shí)例的方法,于是世界從此清靜了

注:其實(shí)本人認(rèn)為這里不應(yīng)該叫做外觀類,可能叫包裝器類更合適吧(因?yàn)楸救藳]聽過外觀類有實(shí)現(xiàn)共同接口的說法)

RequestFacade類

      
        public
      
      
        class
      
       RequestFacade 
      
        implements
      
      
         ServletRequest {

  
      
      
        private
      
       ServletRequest request = 
      
        null
      
      
        ;

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

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

  
      
      
        public
      
      
         Enumeration getAttributeNames() {
    
      
      
        return
      
      
         request.getAttributeNames();
  }

  
      
      
        public
      
      
         String getRealPath(String path) {
    
      
      
        return
      
      
         request.getRealPath(path);
  }

        
           /
        
        
          /省略后面的代碼
        
      
      
        
}
      
    

ResponseFacade類

      
        public
      
      
        class
      
       ResponseFacade 
      
        implements
      
      
         ServletResponse {

  
      
      
        private
      
      
         ServletResponse response;
  
      
      
        public
      
      
         ResponseFacade(Response response) {
    
      
      
        this
      
      .response =
      
         response;
  }

  
      
      
        public
      
      
        void
      
       flushBuffer() 
      
        throws
      
      
         IOException {
    response.flushBuffer();
  }

  
      
      
        public
      
      
        int
      
      
         getBufferSize() {
    
      
      
        return
      
      
         response.getBufferSize();
  }
  
        
           /
        
        
          /省略后面的代碼
          
}

---------------------------------------------------------------------------?

本系列How Tomcat Works系本人原創(chuàng)?

轉(zhuǎn)載請(qǐng)注明出處 博客園 刺猬的溫馴?

本人郵箱: chenying998179 # 163.com ( #改為@

本文鏈接 http://www.cnblogs.com/chenying99/p/3231637.html

How Tomcat Works(三)


更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號(hào)聯(lián)系: 360901061

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對(duì)您有幫助就好】

您的支持是博主寫作最大的動(dòng)力,如果您喜歡我的文章,感覺我的文章對(duì)您有幫助,請(qǐng)用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會(huì)非常 感謝您的哦!!!

發(fā)表我的評(píng)論
最新評(píng)論 總共0條評(píng)論
主站蜘蛛池模板: 乐安县| 大庆市| 六安市| 湖南省| 即墨市| 松滋市| 永州市| 永兴县| 嘉善县| 乌兰察布市| 馆陶县| 肃北| 永靖县| 都兰县| 孝昌县| 体育| 濮阳市| 屏东市| 齐河县| 手游| 五常市| 长垣县| 子长县| 屏南县| 瑞金市| 临泉县| 高青县| 太康县| 景德镇市| 万年县| 宜良县| 志丹县| 龙陵县| 罗甸县| 彭阳县| 博爱县| 凌源市| 正宁县| 广南县| 汝南县| 玉屏|