Sun Java System Web Server 7.0 Developer's Guide to Java Web Applications

About Servlets

Servlets, like applets, are reusable Java applications. Servlets, however, run on a web server rather than in a web browser.

Servlets provide a component-based, platform-independent method for building web-based applications without the performance overheads, process limitations, and platform-specific liabilities of CGI programs.

Servlets supported by the Sun Java System Web Server 7.0 are based on the Java Servlet 2.4 specification. Servlets are created compiled and packed into a Java web application archive WAR file and then deployed to the Web Server and managed at runtime by the servlet engine

Basic characteristics of servlets include the following:

Servlet Data Flow

When a user clicks a Submit button, information entered in a display page is sent to a servlet. The servlet processes the incoming data and responds to generate content. Once the content is generated, the servlet creates a response page, usually by forwarding the content to a JSP. The response is sent back to the client, which sets up the next user interaction.

Information flows to and from the servlet according to the following high-level process:

  1. The servlet processes the client request.

  2. The servlet generates content.

  3. The servlet creates a response and either sends back directly to the client or dispatches the task to JSP or to another servlet. The servlet remains in memory, available to process another request.

Servlet Types

The two main servlet types are, generic and HTTP.

For both servlet types, you must implement the initializer method init() to allocate and initialize the servlet, and the destructor method destroy() to deallocate resources.

All servlets must implement a service() method, which is responsible for handling servlet requests. For generic servlets, override the service method to provide routines for handling requests. HTTP servlets provide a service method that automatically routes the request to another method in the servlet based on which HTTP transfer method is used. For HTTP servlets, override doPost() to process POST requests, doGet() to process GET requests, and so on.