Java Reference
In-Depth Information
18.2
S ERVLETS : P ROGRAM -C ENTRIC S ERVER -S IDE D OCUMENTS
Servlets are Java programs that are run by a Web server. At its simplest, a servlet
is a Java class that is invoked by a Web server (referred to in some contexts as
the servlet's container ). A servlet is run not from the command line as a regular
Java program, but by visiting its URL. Point a Web browser at a servlet's ad-
dress and the Web server (the one which serves up that address) will run the
servlet and send its output back to the browser (see Figure 18.1). So you can
see that typical output for a servlet is HTML—what better thing to send to
a browser?
Now, more and more servlets are using XML as their output and then
converting it to HTML via XSLT stylesheets, but we're trying to keep things
simple here.
In their most generic form, servlets are classes which implement the
Servlet interface. That means that they provide three methods:
init(ServletConfig config)
service(ServletRequest request, ServletResponse response)
destroy()
The init() method gets called when the Web server starts up the class.
(Think of the init() method as a constructor; Java doesn't allow constructors
to be defined for interfaces, so init() plays that role.)
The destroy() method gets called whenever the Web server takes the
servlet out of service. This might happen when a system administrator wants
to shut down the system, or shut down just that particular Web service.
Naturally, the service() method is the method that gets called whenever
requests for this servlet arrive at the Web server. The server knows that the re-
quested service is provided by this servlet, so it packages up certain data and
sends it along as a request to the servlet. Thus, servlets can provide data in this
generic request/response kind of protocol. Simple, but vague, right now.
Servlets get a bit more interesting when we look at the HttpServlet class.
This class extends Servlet and adds two more methods that must be
implemented:
doGet(HttpServletRequest request, HttpServletResponse
response)
Search WWH ::




Custom Search