File file = new File(HttpServer.WEB_ROOT, request.getUri());
然后它檢查文件是否存在。如果存在,sendStaticResource 方法通過(guò)傳遞File對(duì)象來(lái)構(gòu)造一個(gè)java.io.FileInputStream對(duì)象。然后調(diào)用FileInputStream 的read方法,將字節(jié)流寫(xiě)如到OutputStream輸出。注意這種情況下, 靜態(tài)資源的內(nèi)容也被作為原始數(shù)據(jù)被發(fā)送給了瀏覽器。
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);
}
}
如果這個(gè)文件不存在,sendStaticResource 方法發(fā)送一個(gè)錯(cuò)誤消息給瀏覽器。
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());
編譯和運(yùn)行應(yīng)用程序
為了編譯和運(yùn)行應(yīng)用,你首先需要解壓包含本文應(yīng)用程序的.zip文件。你解壓的目錄成為工作目錄(working directory),它有三個(gè)子目錄: src/, classes/, 和 lib/。 要編譯應(yīng)用程序需要在工作目錄輸入如下語(yǔ)句:
javac -d . src/ex01/pyrmont/*.java
這個(gè)-d 選項(xiàng)參數(shù)將結(jié)果寫(xiě)到當(dāng)前目錄,而不是src/ 目錄。
要運(yùn)行應(yīng)用程序,在工作目錄中輸入如下語(yǔ)句:
java ex01.pyrmont.HttpServer
要測(cè)試你的應(yīng)用程序,打開(kāi)瀏覽器,在地址欄中輸入如下URL:
http://localhost:8080/index.html
你將可以看到瀏覽器中顯示的index.html 頁(yè)面。
Figure 1. The output from the web server
在控制臺(tái)(Console),你能看到如下內(nèi)容:
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
概要總結(jié)
在本文中,你了解了一個(gè)簡(jiǎn)單的Web服務(wù)器的工作機(jī)制。本文附帶的應(yīng)用程序源代碼只包含三個(gè)類(lèi),但并不是所有的都有用。盡管如此,它還是能被作為一種很好的學(xué)習(xí)工具為我們服務(wù)。
新聞熱點(diǎn)
疑難解答
圖片精選