Contents /
Previous /
Next
Servlets
A servlet can almost be thought of as an applet that runs on the
server side -- without a face.
Servlets take over the functionality of CGI scripts.
Servlets versus CGI Scripts
What can be done with a servlet can also
be done with a CGI script, but servlets have a distinct, important
advantage--once a servlet is invoked, it is NOT necessary to start a
new server process with each request since the servlet stays in
memory.
CGI scripts, on the other hand, use heavyweight server
processes for each request.
Each time a CGI script is called, an entire operating system
process is created.
Sites with heavy
traffic loads have a noticeable performance improvement by using
servlets instead of CGI scripts.
Implementing Servlets
The javax.servlet package and the javax.servlet.http package provide
the classes and interfaces to define servlets.
HTML servlet classes
extend the javax.servlet.http.HttpServlet abstract class, which
provides a framework for handling HTTP protocol.
The Servlet's Service Methods
Because HttpServlet
is abstract your servlet must extend it and override at least one of
the following interaction methods:
-
doGet():
For handling GET requests.
-
doPost ():
For handling POST requests.
Get and POST information are
strings passed from the browser,
such as data to be stored in a database or user login
and password information.
-
doPut():
Places documents directly on the server.
-
doDelete ():
Deletes information or documents from the server.
-
getServletInfo():
Returns descriptive information about the servlet, possibly its
purpose, author, or version number.
These methods are the heart of the servlet, where instructions and the
purpose of the servlet are carried out.
Servlet Methods (Life Cycle)
init(): Called once
by the server for initialization and not again for each user
request.
service():
Next, the service method is called, performing the work of the
servlet, and passing ServletRequest and ServletResponse objects as
needed.
When a client calls a servlet by typing the URL in the browser,
submitting a form, or clicking a button on a menu, the servlet's
service method checks the HTTP request type, such as POST or GET. This
in turn calls doGet, doPOST, doPUT, or doDelete as needed.
destroy():
Remove a previously loaded servlet instance.
This gives
the servlet a chance to close database connections, save information
to a log file, or perform other clean-up tasks before it is shut
down.
Evaluation HTML Forms with Servlets
The following servlet example processes data POSTed by an HTML form:
Send Form Parameter to Servlet