img
A Simple Ser vlet
To become familiar with the key servlet concepts, we will begin by building and testing
a simple servlet. The basic steps are the following:
1. Create and compile the servlet source code. Then, copy the servlet's class file to the
proper directory, and add the servlet's name and mappings to the proper web.xml file.
2. Start Tomcat.
3. Start a web browser and request the servlet.
Let us examine each of these steps in detail.
Create and Compile the Ser vlet Source Code
To begin, create a file named HelloServlet.java that contains the following program:
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet {
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}
Let's look closely at this program. First, note that it imports the javax.servlet package.
This package contains the classes and interfaces required to build servlets. You will learn
more about these later in this chapter. Next, the program defines HelloServlet as a subclass of
GenericServlet. The GenericServlet class provides functionality that simplifies the creation
of a servlet. For example, it provides versions of init( ) and destroy( ), which may be used
as is. You need supply only the service( ) method.
Inside HelloServlet, the service( ) method (which is inherited from GenericServlet) is
overridden. This method handles requests from a client. Notice that the first argument is a
ServletRequest object. This enables the servlet to read data that is provided via the client
request. The second argument is a ServletResponse object. This enables the servlet to formulate
a response for the client.
The call to setContentType( ) establishes the MIME type of the HTTP response. In this
program, the MIME type is text/html. This indicates that the browser should interpret the
content as HTML source code.
Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is
sent to the client as part of the HTTP response. Then println( ) is used to write some simple
HTML source code as the HTTP response.
Compile this source code and place the HelloServlet.class file in the proper Tomcat
directory as described in the previous section. Also, add HelloServlet to the web.xml file,
as described earlier.
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home