• <ruby id="5koa6"></ruby>
    <ruby id="5koa6"><option id="5koa6"><thead id="5koa6"></thead></option></ruby>

    <progress id="5koa6"></progress>

  • <strong id="5koa6"></strong>
  • 基于Jave的Web服務工作機制(7)

    發表于:2007-05-25來源:作者:點擊數: 標簽:
    sendStaticResource 方法是非常簡單的。它首先傳遞父路徑和子路徑給File類的構造器,從而對java.io.File類進行了實例化。 File file = new File(HttpServer.WEB_ROOT, request.getUri()); 然后它檢查文件是否存在。如果存在,sendStaticResource 方法通過傳
    sendStaticResource 方法是非常簡單的。它首先傳遞父路徑和子路徑給File類的構造器,從而對java.io.File類進行了實例化。

      File file = new File(HttpServer.WEB_ROOT, request.getUri());
      然后它檢查文件是否存在。如果存在,sendStaticResource 方法通過傳遞File對象來構造一個java.io.FileInputStream對象。然后調用FileInputStream 的read方法,將字節流寫如到OutputStream輸出。注意這種情況下, 靜態資源的內容也被作為原始數據被發送給了瀏覽器。

    if (file.exists()) {
      fis  = new FileInputStream(file);
      int ch = fis.read(bytes, 0, BUFFER_SIZE);

      while (ch != -1) {
        output.write(bytes, 0, ch);
        ch = fis.read(bytes, 0, BUFFER_SIZE);
      }
    }

      如果這個文件不存在,sendStaticResource 方法發送一個錯誤消息給瀏覽器。

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

      編譯和運行應用程序

      為了編譯和運行應用,你首先需要解壓包含本文應用程序的.zip文件。你解壓的目錄成為工作目錄(working directory),它有三個子目錄: src/, classes/, 和 lib/。 要編譯應用程序需要在工作目錄輸入如下語句:

      javac -d . src/ex01/pyrmont/*.java
      這個-d 選項參數將結果寫到當前目錄,而不是src/ 目錄。

      要運行應用程序,在工作目錄中輸入如下語句:

      java ex01.pyrmont.HttpServer
      要測試你的應用程序,打開瀏覽器,在地址欄中輸入如下URL:

      http://localhost:8080/index.html
      你將可以看到瀏覽器中顯示的index.html 頁面。

      Figure 1. The output from the web server

      在控制臺(Console),你能看到如下內容:

      GET /index.html HTTP/1.1
      Accept: */*
      Accept-Language: en-us
      Accept-Encoding: gzip, deflate
      User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)
      Host: localhost:8080
      Connection: Keep-Alive

      GET /images/logo.gif HTTP/1.1
      Accept: */*
      Referer: http://localhost:8080/index.html
      Accept-Language: en-us
      Accept-Encoding: gzip, deflate
      User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)
      Host: localhost:8080
      Connection: Keep-Alive

      概要總結

      在本文中,你了解了一個簡單的WEB服務器的工作機制。本文附帶的應用程序源代碼只包含三個類,但并不是所有的都有用。盡管如此,它還是能被作為一種很好的學習工具為我們服務。

    原文轉自:http://www.kjueaiud.com

    老湿亚洲永久精品ww47香蕉图片_日韩欧美中文字幕北美法律_国产AV永久无码天堂影院_久久婷婷综合色丁香五月

  • <ruby id="5koa6"></ruby>
    <ruby id="5koa6"><option id="5koa6"><thead id="5koa6"></thead></option></ruby>

    <progress id="5koa6"></progress>

  • <strong id="5koa6"></strong>