Servlet Basics

A good way to introduce servlets is to compare them to their more familiar counterparts—applets. A servlet is to a Web server what an applet is to a Web browser. An applet is a small Java program that is run by a Web browser via a simple, standard API. A servlet is a small Java program run by a Web server via simple, standard API. Table 9.1 compares the applet API to the servlet API.

Table 9.1. Applet API Versus Servlet API
Applet Class API Servlet Interface API Life Cycle
init() init() Called Once
start(), stop() service() Called Many times
Destroy() destroy() Called Once
getAppletInfo() getServletInfo()  
getAppletContext GetServletConfig()  

The applet API and servlet API are conceptually identical. Notice in the life cycle column that both have an init() and destroy() method that are called only one time. The servlet execution environment calls the init() method after the servlet is instantiated. The service() method is called to handle requests from the client. This method is called for every client request. When the Web server or servlet execution environment is being shut down it calls the servlet's destroy() method.

The servlet life cycle provides the framework for the execution of our small Java programs by a Web server but not the motivation for the execution. The service() method signifies the motivation for our server-side Java programs—to provide centralized services to multiple Web clients. A Web client for a servlet could be an applet running inside a Web browser or the browser itself via Hypertext Transfer Protocol (HTTP) requests. A client sends the servlet a request, and the servlet returns the appropriate response. Therefore, another way to view servlets is a Web-based server framework that abstracts the request/response paradigm. While RMI uses the method call to formalize and constrain the request/response model, servlets use streams and browser-to-Web server communication.

The Servlet API

While the servlet life cycle and API are modeled after the applet's, the servlet interface API requires more parameters. Listing 9.1 shows the complete servlet API including method parameters and return types.

Code Listing 9.1. The Servlet Interface API
package javax.servlet;
import java.io.IOException;

public interface Servlet
{
    public void init(servletConfig config) throws ServletException;
    public ServletConfig getServletConfig();
    public void service(servletRequest req, ServletResponse res)
    throws ServletException, IOException;
    public String getServletInfo();
    public void destroy();
}

The init() method is passed an object that implements the ServletConfig interface. ServletConfig contains a set of name/value pairs and an object that implements the ServletContext interface. The ServletConfig interface and ServletContext interface can be used to get information about the servlet execution environment, facilities such as logging, and other resources on the computer.

The service() method receives two parameters—ServletRequest and ServletResponse. A ServletRequest is an abstraction of a Multipurpose Internet Mail Extension (MIME) body request. A MIME body refers to the body of a message that contains MIME data. MIME data is specified by type and subtype, such as text/html or image/gif. A servlet request encapsulates MIME data by giving the servlet the MIME type, a binary or character stream to the data, and a set of name/value pairs that can be used to further describe the data. The servlet response is also a MIME body that is generated by the servlet for consumption by the connected client.

An abstract class, GenericServlet, implements the servlet interface. A GenericServlet defines a protocol-independent servlet meant to be subclassed with a protocol-specific implementation. Sun provides another abstract class that implements the HTTP protocol, the HttpServlet class, which extends GenericServlet. Listing 9.2 presents the HttpServlet API.

Code Listing 9.2. The HttpServlet Class API
public abstract class HttpServlet extends GenericServlet
    implements java.io.Serializable
{
    public HttpServlet () {  }  // abstract class
    protected void doGet (HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {  ... }
    protected long getLastModified (HttpServletRequest req)
    {  ... }

    protected void doPost (HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    {  ... }

    protected void doPut (HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    {  ... }

    protected void doDelete (HttpServletRequest req,
                 HttpServletResponse resp)
    throws ServletException, IOException
    {  ... }

    protected void doOptions (HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    {  ... }

    protected void doTrace (HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException
    {  ... }

    public void service(servletRequest req, ServletResponse res)
    throws ServletException, IOException
    {  ... }
}

The service method of the HttpServlet is not abstract as it is in the GenericServlet. In- stead, the HttpServlet's service() method dispatches the request to one of six handler methods corresponding to an appropriate HTTP request method. The six HTTP request types handled are

  • Get This method means return the data pointed to by the Uniform Resource Identifier (URI). If the URI refers to a data-producing process (such as a servlet or CGI program) the response is data from that process and not the process code. If an HTML form uses the GET method to transfer data to the Web server, the name value pairs are packaged at the end of the URI and separated by an ampersand (&). Some browsers limit the length of a URI to 256 characters.

  • Post This method sends an entity of any size as a subordinate to the resource specified in the URI. If the URI is a servlet or CGI program, the data is sent to the process on a separate stream. There is no limit on the amount of data that can be sent to the Post method. The CGI program or servlet is sent the length of the data in the request.

  • Put This method requests that the enclosed data be stored under the supplied request URI.

  • Delete This method requests that the resources referred to by the URI be deleted.

  • Options This method requests information about the capabilities and communication options of a specific resource specified by a URI or about the server.

  • Trace This method is an application-level loopback where the server echoes back what the client sent so the client can debug the application.

All of these options have a corresponding doXXX() method where XXX is replaced by the request type (for example, doPost() and doGet()). By far the most common methods you will override are doGet() and doPost().

Using the Java Server Web Development Kit (JSWDK)

To test your servlets, Sun Microsystems provides the JavaServer Web Development Kit (JSWDK), which comes with a simple Web server. In addition to a Web server, the JSWDK includes the reference implementation of servlets and Java server pages. You can download the JSWDK from http://java.sun.com/products/servlets. After selecting your target platform, you can download the distribution to your machine.

The JSWDK contains examples, JAR files of the classes in the distribution, source files of the servlet and jsp reference implementation, and Web pages including documentation. There are three JAR files: servlet.jar, jspengine.jar, and xml.jar. The files servlet.jar and xml.jar must be added to your classpath to develop servlets for the exercises in this chapter to work.

There are shell scripts and .bat files (depending on your target platform) for starting and stopping the JSWDK Web server. For windows, you double-click the startserver.bat file to start the server. Once started, you can access the server via a Web browser and the following URL:

http://localhost:8080

This will bring up the documentation Web pages and allow you to browse the sample servlet and JSP applications. The simplest way to add new servlets is to add them to the existing examples/web-inf/servlets directory under the JSWDK home directory (wherever it was installed). For example, if JSWDK is installed directly under the C drive on Windows, we add our servlets under c:jswdk1.0.1examplesweb-infservlets. We then access our servlet from the Web browser via a URL such as http://localhost:8080/examples/servlet/testservlet. For more details using the JSWDK, refer to the documentation provided with the kit.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.137.64