Java Reference
In-Depth Information
Using Servlets to Create Dynamic Web Page s
Servlets are Java classes that run in a servlet engine and receive and service client requests. Although
they are not tied to a specific protocol, the most common use of servlets is to create dynamic Web
pages. An online catalog is a classic example of a dynamic Web application. Requests from a client can
be received by a servlet that gets the data from a database, formats it, and returns it to the client.
Note
The Tomcat servlet engine, from http://jakarta.apache.org/tomcat/ is used in
all the examples in this topic. Tomcat was chosen because it is the servlet container
used in the official reference implementation for the Java Servlet and Java Server
Pages technologies. Commercial servlet containers such as JRun should work just as
well.
Creating a Simple Servlet
Servlets are created by implementing javax.servlet.Servlet. All servlets implement this interface.
Servlets are typically created by extending javax.servlet.GenericServlet , which implements the
servlet interface, or by extending javax.servlet.http.HttpServlet, which is the base class for
servlets that service HTTP requests.
The servlet interface defines so called life-cycle methods, which are called by the servlet engine to
handle the major-life cycle tasks. These life-cycle tasks are initialization, client request service,
destruction, and garbage collection.
Much of the work a servlet does is handled in the client request service methods. These are the two
most important client request service methods of the HttpServlet class:
 
doGet , which must be overridden to support HTTP GET requests
 
doPost , which must be overridden to support HTTP POST requests
GET and POST are the CGI methods used to transfer request parameters to the server. The primary
difference between the two is that the parameters in the GET request are appended to the host URL,
whereas the parameters in the POST request are passed separately.
Another important reason for using the POST method is that it can transfer more data than the GET
method . The maximum length of the parameters in a GET request is specified as 256 characters.
Typical uses for HTTP servlets include the following:
 
Processing and/or storing data an HTML form submits
 
Creating dynamic Web pages
 
Managing state information for applications such as an online shopping cart
Servlets offer many advantages over traditional CGI scripts and are the backbone of today's application
servers. In spite of their power, however, they are relatively easy to write and deploy, as the simple
"Hello World" example of Listing 12-1 demonstrates.
Listing 12-1: A simple servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class HelloServlet extends HttpServlet{
protected void doGet(HttpServletRequest req,HttpServletResponse resp)
throws ServletException, IOException
{
Search WWH ::




Custom Search