Java Reference
In-Depth Information
Developing Servlets
Java servlets are created and compiled just like any other Java class. After you install the
servlet packages and add them to your computer's Classpath , you can compile servlets
with the JDK's Java compiler or any other current compiler.
Every servlet is a subclass of the HttpServlet class, which is part of the javax.servlet
package. This class includes methods that represent the life cycle of a servlet and collect
information from the web server running the servlet.
A servlet's life cycle methods function similarly to the life cycle methods of applets.
The init( ServletConfig ) method is called automatically when a web server first brings
a servlet online to handle a user's request. As mentioned earlier, one Java servlet can han-
dle multiple requests from different web users. The init() method is called only once,
when a servlet comes online. If a servlet is already online when another request to use the
servlet is received, the init() method won't be called again.
The init() method has one argument— ServletConfig , an interface in the
javax.servlet package that contains methods to find out more about the environment in
which a servlet is running.
The destroy() method is called when a web server takes a servlet offline. Like the
init() method, this is called only once, when all users have finished receiving informa-
tion from the servlet. If this doesn't take place in a specified amount of time, destroy()
is called automatically, preventing a servlet from being hung up while it waits for infor-
mation to be exchanged with a user.
One of the main tasks of a servlet is to collect information from a web user and present
something back in response. You can collect information from a user by using a form , which
is a group of text boxes, radio buttons, text areas, and other input fields on a web page.
Figure 21.1 shows a web form on a page loaded with the Mozilla web browser.
The form displayed in Figure 21.1 contains two fields: a text area and a clickable
Translate button. The HTML tags used to display this page are the following:
<html>
<body>
<head><title>ROT-13 Translator</title></head>
<h1>ROT-13 Translator</h1>
<p>Text to translate:
<form action=”Rot13” method=”post”>
<textarea name=”text” rows=”8” cols=”55”>
</textarea>
<p><input type=”submit” value=”translate”>
</form>
</body>
</html>
21
 
Search WWH ::




Custom Search