Section 18.2. Servlets: Program-Centric Server-Side Documents


18.2. Servlets: Program-Centric Server-Side Documents

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 address 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 HTMLwhat better thing to send to a browser?

Figure 18.1. Servlet diagram


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 requested 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)

  • doPost(HttpServletRequest request, HttpServletResponse response)

We hope that you've noticed the similarity between doGet(), doPost(), and the previously mentioned service() method. More on that in a minute.



    Java Application Development with Linux
    Java Application Development on Linux
    ISBN: 013143697X
    EAN: 2147483647
    Year: 2004
    Pages: 292

    flylib.com © 2008-2017.
    If you may any questions please contact us: flylib@qtcs.net