The servlet specification defines a server-side component model that can be implemented by web server vendors. Servlets provide a simple but powerful API for generating web pages dynamically. (Although servlets can be used for many different request-response protocols, they are predominantly used to process HTTP requests for web pages.)

Servlets are developed in the same fashion as enterprise beans; they are Java classes that extend a base component class and have a deployment descriptor. Once a servlet is developed and packaged in a JAR file, it can be deployed in a web server. When a servlet is deployed, it is assigned to handle requests for a specific web page or to assist other servlets in handling page requests. The following servlet, for example, might be assigned to handle any request for the helloworld.html page on a web server:

import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorld extends HttpServlet 

    protected void doGet(HttpServletRequest 
        throws ServletException, {

    try {
        ServletOutputStream writer = response.getWriter( );
        writer.println("<h1>Hello World!!</h1>");
    } catch(Exception e) {
        // handle exception

When a browser sends a request for the page to the web server, the server delegates the request to the appropriate servlet instance by invoking the servlet's doGet( ) method.[*] The servlet is provided with information about the request in the HttpServletRequest object and can use the HttpServletResponse object to reply to the request. This simple servlet sends a short HTML document (including the text "Hello World!!") back to the browser, which displays it. Figure illustrates how a request is sent by a browser and serviced by a servlet running in a web server.

[*] HttpServlets also have a doPost( ) method that handles requests for forms.

Servlet servicing an HTTP request

Servlets are similar to session beans because both perform a service and can directly access backend resources (e.g., databases) through JDBC, but they do not represent persistent data. Unlike session beans, however, servlets do not have support for container-managed transactions and are not composed of business methods. Servlets deal with very specific (usually HTTP) requests and respond by writing to an output stream.

The servlet specification is extensive and robust but also simple and elegant. To learn more about servlets, read Java Servlet Programming (O'Reilly).

 Python   SQL   Java   php   Perl 
 game development   web development   internet   *nix   graphics   hardware 
 telecommunications   C++ 
 Flash   Active Directory   Windows