The Web|web service Sendstaticresource method is very simple. It first passes the parent path and subpath to the constructor of the file class, thus instantiating the Java.io.File class.
File File = new file (Httpserver.web_root, Request.geturi ());
It then checks to see if the file exists. If present, the Sendstaticresource method constructs a Java.io.FileInputStream object by passing the file object. The FileInputStream read method is then invoked to write a stream of bytes to the OutputStream output. Note that in this case, the contents of the static resource are also sent to the browser as raw data.
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);
}
}
If this file does not exist, the Sendstaticresource method sends an error message to the browser.
String errormessage = "http/1.1 404 File Not found\r\n" +
"Content-type:text/html\r\n" +
"Content-length:23\r\n" +
"\ r \ n" +
"Output.write (Errormessage.getbytes ());
Compiling and running the application
To compile and run the application, you first need to unzip the. zip file that contains the application in this article. The directory you unzipped becomes the working directory (working directory), which has three subdirectories: src/, classes/, and lib/. To compile the application, you need to enter the following statement in the working directory:
Javac-d. Src/ex01/pyrmont/*.java
This-d option parameter writes the result to the current directory instead of the src/directory.
To run the application, enter the following statement in the working directory:
Java ex01.pyrmont.HttpServer
To test your application, open the browser and enter the following URL in the address bar:
Http://localhost:8080/index.html
You will be able to see the index.html page displayed in the browser.
Figure 1. The output from the Web server
In the console, you can see the following:
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
Summary summaries
In this article, you learned about the working mechanism of a simple Web server. The application source code included with this article contains only three classes, but not all of them are useful. Nevertheless, it can be used as a good learning tool to serve us.