Java Reference
In-Depth Information
formatting to be changed (e.g., to apply a new corporate look to the pages)
without changing the content or the programs that generate the content.
Since a Web server (e.g., Apache Tomcat) is typically configured to run
constantly, that is, to always be around, then a servlet is also always around.
(The Web server keeps a reference to the class, so the class is not garbage collect-
ed—hence its persistence.) Well, “always” here means “as long as the Web
server and the operating system are up and running.”
An aside: Not all servlets are for Web browsing. Sometimes servlets can
be used as daemons that hang around in the background doing other tasks
(e.g., background processing of some database records). The browser interface,
if any, may only be for the purpose of providing an administrative interface to
the daemon. The administrator would then have a Web page to which to go,
in order to see how many records have been processed. This page may also have
buttons to reset, restart, or shut down the process. While we typically think of
servlets being for the production of dynamic Web pages, here the Web pages
would only be an aside to the real purpose, that of processing database records.
18.4
H OW TO W RITE A S ERVLET
So how do you write a servlet? You may already have figured it out, from what
we've described so far. You need to:
• Write a Java class that extends HttpServlet
• In that class, write the following methods:
init()
destroy()
doGet() and/or doPost()
That's the basic idea. There are lots of details about what arguments are
supplied, what other resources are available, what methods can be used to get
at parameters, and so on. We'll discuss some of those in our example servlet.
Let's start with a simplistic servlet, one that will dynamically generate the
“Hello, world” string as a Web page (Example 18.1).
Search WWH ::




Custom Search