Java Reference
In-Depth Information
This is an HTTP/1.0 response code that tells the client to expect to be redirected. The
second line is a
Date
: header that gives the current time at the server. This line is optional.
The third line is the name and version of the server; this line is also optional but is used
by spiders that try to keep statistics about the most popular web servers. The next line
is the
Location
: header, which is required for this response type. It tells the client where
it is being redirected to. Last is the standard
Content-type
: header. You send the content
type
text/html
to indicate that the client should expect to see HTML. Finally, a blank
line is sent to signify the end of the header data.
Everything after this will be HTML, which is processed by the browser and displayed
to the user. The next several lines print a message for browsers that do not support
redirection, so those users can manually jump to the new site. That message looks like:
<
HTML
><
HEAD
><
TITLE
>
Document
moved
</
TITLE
></
HEAD
>
<
BODY
><
H1
>
Document
moved
</
H1
>
The
document
/
has
moved
to
<
A
HREF
=
"http://www.cafeconleche.org/"
>
http:
//www.cafeconleche.org/</A>.
Please
update
your
bookmarks
<
P
></
BODY
></
HTML
>
Finally, the connection is closed and the thread dies.
A Full-Fledged HTTP Server
Enough special-purpose HTTP servers. This next section develops a full-blown HTTP
server, called
JHTTP
, that can serve an entire document tree, including images, applets,
HTML files, text files, and more. It will be very similar to the
SingleFileHTTPServer
,
except that it pays attention to the GET requests. This server is still fairly lightweight;
after looking at the code, we'll discuss other features you might want to add.
Because this server may have to read and serve large files from the filesystem over
potentially slow network connections, you'll change its approach. Rather than processā
ing each request as it arrives in the main thread of execution, you'll place incoming
connections in a pool. Separate instances of a
RequestProcessor
class will remove the
connections from the pool and process them.
Example 9-12
shows the main
JHTTP
class.
As in the previous two examples, the
main()
method of
JHTTP
handles initialization,
but other programs can use this class to run basic web servers.
Example 9-12. The JHTTP web server
import
java.io.*
;
import
java.net.*
;
import
java.util.concurrent.*
;
import
java.util.logging.*
;
public
class
JHTTP
{
private
static
final
Logger
logger
=
Logger
.
getLogger
(
JHTTP
.
class
.
getCanonicalName
());