[ Team LiB ] Previous Section Next Section

A "Hello World" Servlet

Servlets are a little more involved than JSP, but in simple cases they aren't too bad. Listing 2.1 shows you the "Hello World" program in servlet form.

Listing 2.1 Source Code for HelloWorldServlet.java
package examples;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HelloWorldServlet extends HttpServlet
{
    public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
        throws IOException
    {
// Tell the Web server that the response is HTML.
        response.setContentType("text/html");

// Get the PrintWriter for writing out the response.
        PrintWriter out = response.getWriter();

// Write the HTML back to the browser.
        out.println("<html>");
        out.println("<body>");
        out.println("<h1>Hello World!</h1>");
        out.println("</body>");
        out.println("</html>");
    }
}

The HTML portion of HelloWorldServlet is probably the most recognizable part. The browser's view of HelloWorldServlet is shown in Figure 2.1.

Figure 2.1. A servlet can generate HTML code.

graphics/02fig01.gif

As mentioned earlier, unlike JSPs, servlets are pure Java classes. The good news is that you don't have to learn any additional syntax to create a servlet; the bad news is that you have to do a bit more work in your programs. Although, as you can see from the "Hello World" servlet, the amount of work isn't really that great.

Compiling the Servlet

Before you compile the servlet, make sure the servlet classes are in your classpath. The location of the servlet classes varies depending on which servlet container you are using. For example, if you are using the Apache Tomcat server, the servlet-api.jar file is located in the common\lib directory underneath your main Tomcat installation. To compile HelloWorldServlet.java on a system where you have Tomcat installed, you might set your CLASSPATH variable this way under Windows:


set CLASSPATH=.;c:\jakarta-tomcat\common\lib\servlet-api.jar;%CLASSPATH%

Under Unix or Linux, you might set it this way:


export CLASSPATH=.:/usr/local/jakarta-tomcat/common/lib/servlet-api.jar:$CLASSPATH

Of course, you can also add the classpath to the command line using the –classpath option of javac, the java compiler.

Where Are the Classes in Tomcat 5?

graphics/bytheway_icon.gif

In past versions of Tomcat, the classes that support servlet development have been located in servlet.jar, located in the common\lib directory. For Tomcat 5.0, which includes support for the Servlet 2.4 and JSP 2.0 specifications, the class is named servlet-api.jar—at least for the moment.


Where Are the Classes in the J2EE SDK?

graphics/bytheway_icon.gif

If you are using the J2EE SDK, the JAR file that includes support for servlets and JSPs is named J2EE.jar and is located in the lib directory off of the J2EE home directory. This book will be using Tomcat for its examples, so if you decide to use the J2EE SDK, you may have to adjust the procedures slightly for compiling and running the examples.


Tomcat Is Part of the Standard

graphics/bytheway_icon.gif

Tomcat is the official playground for servlet and JSP reference implementation development. Once the specifications start to firm up, development on a new version of Tomcat begins right away. A release of Tomcat is ultimately bundled with Sun's J2EE SDK when the SDK is finalized. Tomcat itself is a production quality implementation and is continually refined. Tomcat 5.0 supports the Java Servlet 2.4 and JavaServer Pages 2.0 specifications; it is the version used throughout this book.


Then, to compile the servlet, enter the following command:


javac -d . HelloWorldServlet.java

The reason for the -d . in the javac command is that the source for HelloWorldServlet.java specifies a Java package. When you specify a destination directory with the -d option, Java creates the necessary package directories. For example, when you compile HelloWorldServlet.java, you won't see a HelloWorldServlet.class file in your current directory, but you should see a directory named examples (corresponding to the package that HelloWorldServlet belongs to), which should contain the HelloWorldServlet.class file.

Having Trouble with the Example?

graphics/bytheway_icon.gif

If you are having trouble compiling HelloWorldServlet, see the "Q&A" at the end of this hour.


HelloWorldServlet In-Depth

The first thing your servlet must do is implement the Servlet interface. There are two ways to do it: Create a subclass from a class that implements the Servlet interface or implement the Servlet interface directly in the servlet. HelloWorldServlet, shown earlier in Listing 2.1, takes the easier approach by subclassing an existing class, HttpServlet, which implements Servlet. Other classes also implement the Servlet interface, and they will be discussed shortly.

When a request comes in for a particular servlet, the servlet container loads the servlet (if it has not yet been loaded) and invokes the servlet's service method. The method takes two arguments: an object containing information about the request from the browser and an object containing information about the response going back to the browser. The HttpServlet class provides the implementation of this method for us. Looking at the HTTP request header, it will determine that the HTTP request method was GET and will invoke the method doGet, which has been overridden in the example.

As you will see in Hour 3, "Creating HTML Forms," there are actually several different methods that handle incoming requests. The doGet method is specific to the HttpServlet class and handles HTTP GET requests. The GenericServlet class provides a more general service method that handles all kinds of requests.

Next the servlet must tell the Web browser what kind of content is being returned. Most of the time, you are returning HTML content, so the content type is set to text/html. As you will see in Hour 19, "Creating an XML Application," you can also set the content type to text/xml to return data in XML. In the example we set the response's content type by invoking setContentType in the response object that was passed to us as a parameter of doGet.

After you have set the content type, you are ready to start sending text back to the browser. Of course, you need some sort of output object to send the text back. Again the response object has the methods necessary to get an output stream for writing a response. Because the "Hello World" servlet is writing out text, it needs only a PrintWriter object, so it calls the getWriter method in the response object. If you need to send binary data back to the browser, you should use the getOutputStream method in the response object.

Having read Hour 1, "Getting Started with JavaServer Pages," the final part of HelloWorldServlet probably looks familiar to you by now. HelloWorldServlet uses the println method in the PrintWriter to send HTML back to the browser. Remember, in Hour 1 you saw a portion of the servlet code generated by the "Hello World" JSP. Aside from some extra comments, that code is almost identical to the code at the end of HelloWorldServlet. After all, JSPs eventually become servlets, and there are only so many ways to send output from a servlet, so why shouldn't they be similar?

    [ Team LiB ] Previous Section Next Section