Creating Servlets

Servlets are one of the most popular ways to develop Web applications today. Many of the best-known Web sites on the Internet are powered by servlets. In this chapter, I give you just the basics: what a servlet is, how to set up your computer so you can code and test servlets, and how to create a simple servlet. The next two chapters build on this chapter with additional Web programming techniques.

Understanding Servlets

Before you can understand what a servlet is and how it works, you need to understand the basics of how Web servers work. Web servers use a networking protocol called HTTP to send Web pages to users. (HTTP stands for HyperText Transfer Protocol, but that won't be on the test.) With HTTP, a client computer uses a URL to request a document that's located on the server computer. HTTP uses a request/response model, which means that client computers (Web users) send request messages to HTTP servers, which in turn send response messages back to the clients.

A basic HTTP interaction works something like this:

  1. Using a Web browser program running on a client computer, you specify the URL of a file that you want to access.

    In some cases, you actually type in the URL of the address. But most of the time, you click a link that specifies the URL.

  2. Your Web browser sends an HTTP request message to the server computer indicated by the URL.

    The request includes the name of the file that you want to retrieve.

  3. The server computer receives the file request, retrieves the requested file, and sends the file back to you in the form of an HTTP response message.
  4. The Web browser receives the file, interprets the HTML it contains, and displays the result on-screen.

The most important thing to note about normal Web interactions is that they are static. By that I mean that the contents of the file sent to the user is always the same. If the user requests the same file 20 times in a row, the same page displays 20 times.

In contrast, a servlet provides a way for the content to be dynamic. A servlet is simply a Java program that extends the javax.servlet.Servlet class. The Servlet class enables the program to run on a Web server in response to a user request, and output from the servlet is sent back to the Web user as an HTML page.

With servlets, Steps 1, 2, and 4 of the preceding procedure are the same. It's the fateful third step that sets servlets apart. If the URL specified by the user refers to a servlet rather than a file, Step 3 goes more like this:

  1. The server computer receives the servlet request, locates the Java program indicated by the request, runs it, and returns the output from the program in the form of an HTTP response message.

In other words, instead of sending the contents of a file, the server sends the output generated by the servlet program. Typically, the servlet program generates some HTML that's displayed by the browser.

Servlets are designed to get their work done quickly, and then end. Each time a servlet runs, it processes one request from a browser, generates one page that's sent back to the browser, and then ends. The next time that user or any other user requests the same servlet, the servlet is run again.


Using Tomcat

Unfortunately, you can't just run servlet programs on any old computer. First, you have to install a special program called a servlet engine to turn your computer into a server that's capable of running servlets. The best-known servlet engine is called Tomcat, and it's available free from the Apache Software Foundation at http://www.tomcat.apache.org.

Tomcat can also work as a basic Web server. In actual production environments, Tomcat is usually used in combination with a specialized Web server, such as Apache's HTTP Server.

Installing and configuring Tomcat

Installing Tomcat isn't rocket science, but it's not as easy as making toast. Here are the steps you can follow to set up Tomcat 5.5 on a Windows XP system:

  1. Download the Tomcat Zip file.

    You find the Zip file on the Apache Web site. Although Apache also offers an executable setup file for installing Tomcat, I suggest you download the Zip file instead.

  2. Extract the contents of the Zip file by right-clicking the file and choosing Extract All. Then specify c: as the location to extract the files to.

    I know you don't want to clutter up your root directory with a bunch of files, but the Tomcat Zip file contains a single folder named apachetomcat-5.5.20 (the version number may vary), so only this one folder is created. After all the files are extracted, rename this folder to something a little easier to type. I suggest c: omcat.

  3. Create an environment variable named JAVA_HOME that points to the location of your JDK.

    To create an environment variable, open the Control Panel, double-click the System icon, click the Advanced tab, and then click Environment Variables. Then click New and create a variable named JAVA_HOME. The value of this variable needs to be the complete path to your JDK installation folder. For example: c:Program FilesJavajdk1.6.0.

      Tip 

    A common mistake is to set this variable to the bin directory or to the directory for the JRE, not the JDK. If Tomcat doesn't start up later, double-check the JAVA_HOME directory.

  4. Copy the servlet-api.jar file to the jrelibext folder in your JDK root.

    For example, if your JDF is installed in c:Program FilesJava jdk1.6.0, copy this file to c:Program FilesJavajdk1.6.0 jrelibext.You find the servlet-api.jar file in c: omcat commonlib, assuming you extracted the Tomcat files to c: omcat.

      Tip 

    If you skip this step or copy the servlet-api.jar file to the wrong place, you can't compile your servlet programs. If you get compiler messages complaining that the javax.servlet package doesn't exist, double-check that you performed this step right.

  5. Edit the context.xml configuration file and add reloadable=“true” to the tag.

    The context.xml file is located in c: omcatconf. The second line is initially this:

    
     

    Change it to:

    
     
  6. Modify the web.xml file to enable the invoker servlet.

    Like context.xml, the web.xml file is located in c: omcatconf. It contains two groups of lines that configure a Tomcat feature called the invoker servlet that you need to modify. These lines are initially commented out to disable the invoker servlet; all you have to do is remove the comment lines that appear before and after each group of lines.

    The first group you want to de-comment looks like this:

     
    

    Simply remove the first () and last (–>) of these lines.

    The second group looks like this:

    
     
    

    Once again, you must remove the first and last lines so these lines aren't treated as comments.

      Tip 

    You can quickly find these lines by searching for the word invoker.

  7. Create the classes directory.

    By default, Tomcat looks for the class files for your servlets in the directory c: omcatwebappsROOTWEB-INFclasses. Unfortunately, the classes directory is missing. So you must navigate to c: omcat webappsROOTWEB-INF and create the classes directory. (Of course, the c:tomcat part of these paths varies if you installed Tomcat in some other location.)

Starting and stopping Tomcat

After you install and configure Tomcat, you can start it by opening a command window, changing to the c: omcatin directory, and typing startup. A batch file runs that starts Tomcat. When Tomcat starts, it opens up a second command window that displays various status messages. Figure 2-1 shows both of these windows in action.

image from book
Figure 2-1: Starting up Tomcat.

  Tip 

You know that Tomcat has successfully started up when you see a line such as the following indicating how long the startup took:


INFO: Server startup in 2817 ms
  Tip 

If the Tomcat window appears for a few seconds, and then an exception message flies by quickly and the window closes, the most likely problem is that you already have a Web server running on your system and that the server has already laid claim to the port Tomcat wants to use for HTTP communication. The solution to that problem is to edit the server.xml file in c: omcatconf and look for this tag:



Change the port number from 8080 to some other number, such as 18080. Later, when you display servlets in a browser window, you have to specify this number as the HTTP port number instead of 8080.

You don't need to shut down Tomcat once you start it up unless you make a change to one of its configuration files. If you do, you can shut down Tomcat by running the shutdown batch file from the c: omcatin directory. Then you can run the startup batch file to get Tomcat going again.

Testing Tomcat

To find out if you have installed Tomcat correctly, you can try running the test servlets that are automatically installed when you install Tomcat. Open a browser window and type this address:

http://localhost:8080/servlets-examples/index.html

(If you changed the port number by editing the server.xml file, use the port number you specified instead of 8080.) The page shown in Figure 2-2 appears. (If it doesn't, go to the earlier section "Installing and configuring Tomcat" and double-check that you did each step correctly.)

image from book
Figure 2-2: Testing Tomcat.

  Note 

If you scroll down this page, you find links to a variety of sample servlets you can run along with links to each servlet's source code. By all means play around with these samples to get an idea of how servlets work and what you can do with them.


Creating a Simple Servlet

Okay, enough of the configuration stuff; now you can start writing some code. The following sections go over the basics of creating a simple Hello, World! type servlet.

Importing the servlet packages

Most servlets need access to at least three packages-javax.servlet, javax.servlet.http, and java.io. As a result, you usually start with these import statements:


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

Depending on what other processing your servlet does, you may need additional import statements.

Extending the HttpServlet class

To create a servlet, you write a class that extends the HttpServlet class. Table 2-1 lists six methods you can override in your servlet class.

Table 2-1: The HttpServlet Class
Open table as spreadsheet

Method

When Called

Signature

doDelete

HTTP DELETE request

public void doDelete(Http ServletRequest request, HttpServletResponse response) throws IOException, ServletException

doGet

HTTP GET request

public void doGet(HttpServlet Request request, HttpServlet Response response) throws IOException, ServletException

doPost

HTTP POST request

public void doPost(HttpServlet Request request, HttpServlet Response response) throws IOException, ServletException

doPut

HTTP PUT request

public void doPut(HttpServlet Request request, HttpServlet Response response) throws IOException, ServletException

init()

First time servlet is run

public void init() throws ServletException

destroy()

Servlet is destroyed

public void destroy()

Most servlets override at least the doGet method. This method is called by the servlet engine when a user requests the servlet by typing its address into the browser's address bar or by clicking a link that leads to the servlet.

Two parameters are passed to the doGet method:

  • An HttpServletRequest object that represents the incoming request from the user. You use the request parameter primarily to retrieve data entered by the user into form fields. You find out how to do that later in this chapter.
  • An HttpServletResponse object that represents the response that is sent back to the user. You use the response parameter to compose the output that is sent back to the user. You find out how to do that in the next section.

Printing to a Web page

One of the main jobs of most servlets is writing HTML output that's sent back to the user's browser. To do that, you first call the getWriter method of the HttpServletResponse class. This returns a PrintWriter object that's connected to the response object. Thus you can use the familiar print and println methods to write HTML text.

For example, here's a doGet method for a simple HelloWorld servlet:


public void doGet(HttpServletRequest request,
 HttpServletResponse response)
 throws IOException, ServletException
{
 PrintWriter out = response.getWriter();
 out.println("Hello, World!");
}

Here the PrintWriter object returned by response.getWriter() is used to send a simple text string back to the browser. If you run this servlet, the browser displays the text Hello, World!.

Responding with HTML

In most cases, you don't want to send simple text back to the browser. Instead, you want to send formatted HTML. To do that, you must first tell the response object that the output is in HTML format. You can do that by calling the setContentType method, passing the string “text/html” as the parameter. Then you can use the PrintWriter object to send HTML. For example, Listing 2-1 shows a basic HelloWorld servlet that sends an HTML response.

Listing 2-1: The HelloWorld Servlet



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

public class HelloWorld extends HttpServlet
{
 public void doGet(HttpServletRequest request,
 HttpServletResponse response)
 throws IOException, ServletException
 {
 response.setContentType("text/html");
 PrintWriter out = response.getWriter();
 out.println("

"); out.println(""); out.println("HelloWorld"); out.println(""); out.println("

"); out.println("

Hello, World!

"); out.println(""); } }

Here the following HTML is sent to the browser (I added indentation to show the HTML's structure):


HelloWorld

Hello, World!

When run, the HelloWorld servlet produces the page shown in Figure 2-3.

image from book
Figure 2-3: The HelloWorld servlet displayed in a browser.

  Tip 

Obviously, you need a solid understanding of HTML to write servlets. If HTML is like a foreign language, you need to pick up a good HTML book, such as HTML 4 For Dummies, 5th Edition, by Ed Tittel and Mary Burmeister, before you go much further. For your reference, Table 2-2 summarizes all the HTML tags that I use in this book.

, ,,,

Table 2-2: Just Enough HTML to Get By
Open table as spreadsheet

HTML tag

Description

Marks the start and end of an HTML document.

Marks the start and end of the head section of an HTML document.

A title element. The text between the start and end tags is shown in the title bar of the browser window.

Marks the start and end of the body section of an HTML document. The content of the document is provided between these tags.

,

The text between these tags is formatted as a level-1 heading.

,

The text between these tags is formatted as a level-2 heading.

,

The text between these tags is formatted as a level-3 heading.

Marks the start of a form. The action attribute specifies the name of the page, servlet, or JSP the form is posted to. The method attribute can be GET or POST; it indicates the type of HTTP request sent to the server.

Marks the end of a form.

type“, name=” name

Creates an input field. Specify type=“text” to create a ”> text field or type=“submit” to create a Submit button. The name attribute provides the name you use in the program to retrieve data entered by the user.

 

A non-breaking space.


Running a Servlet

So how exactly do you run a servlet? First, you must move the compiled class file into a directory that Tomcat can run the servlet from. For testing purposes, you can move the servlet's class file to c: omcatwebapps ROOTWEB-INFclasses. Then type an address like this one in your browser's address bar:


http://localhost:8080/servlet/HelloWorld

You may also want to override the doPost method. This method is called if the user requests your servlet from a form. In many cases, you'll just call doGet from the doPost method, so that both get and post requests are processed in the same way.

As you know, the doGet method is called whenever the user enters the address of your servlet in the address bar or clicks a link that leads to your servlet. But many-if not most-servlets are associated with HTML forms, which provide fields the user can enter data into. The normal way to send form data from the browser to the server is with an HTTP POST request, not a GET request.

If you want a servlet to respond to POST requests, you can override the doPost method instead of, or in addition to, the doGet method. Other than the method name, doPost has the same signature as doGet. In fact, it's not uncommon to see servlets in which the doPost method simply calls doGet, so that both POST and GET requests are processed identically. To do that, code the doPost method like this:


public void doPost(HttpServletRequest request,
 HttpServletResponse response)
 throws IOException, ServletException
{
 doGet(request, response);
}


An Improved HelloWorld Servlet

The HelloWorld servlet that is shown earlier in Listing 2-1 isn't very interesting because it always sends the same text. Essentially, it's a static servlet-which pretty much defeats the purpose of using servlets in the first place. You could just as easily have provided a static HTML page.

Listing 2-2 shows the code for a more dynamic HelloWorld servlet. This version randomly displays one of six different greetings. It uses the random method of the Math class to pick a random number from 1 to 6, and then uses this number to decide which greeting to display. It also overrides the doPost method as well as the doGet method, so posts and gets are handled identically.

Listing 2-2: The HelloServlet Servlet


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

public class HelloServlet extends HttpServlet
{
 public void doGet(HttpServletRequest request,
 HttpServletResponse response)
 throws IOException, ServletException
 {
 response.setContentType("text/html");
 PrintWriter out = response.getWriter();
 String msg = getGreeting();
 out.println("

"); out.println(""); out.println( "HelloWorld Servlet"); out.println(""); out.println(""); out.println("

"); out.println(msg); out.println("

"); out.println(""); out.println(""); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } private String getGreeting() { String msg = ""; int rand = (int)(Math.random() * (6)) + 1; switch (rand) { case 1: return "Hello, World!"; case 2: return "Greetings!"; case 3: return "Felicitations!"; case 4: return "Yo, Dude!"; case 5: return "Whasssuuuup?"; case 6: return "Hark!"; } return null; } }


Getting Input from the User

If a servlet is called by an HTTP GET or POST request that came from a form, you can call the getParameter method of the request object to get the values entered by the user into each form field. Here's an example:


String name = request.getParameter("name");

Here the value entered into the form input field named name is retrieved and assigned to the String variable name.

Working with forms

As you can see, retrieving data entered by the user in a servlet is easy. The hard part is creating a form that the user can enter the data into. There are two basic approaches to doing that. One is to create the form using a separate HTML file. For example, Listing 2-3 shows an HTML file named InputServlet.html that displays the form shown in Figure 2-4.

image from book
Figure 2-4: A simple input form.

Listing 2-3: The InputServlet.html File


Input Servlet

Enter your name: 
 

The action attribute in the form tag of this form specifies that /servlet/InputServlet is called when the form is submitted, and the method attribute indicates that the form is submitted via a POST rather than a GET request.

The form itself consists of an input text field named name and a Submit button. Nothing fancy-just enough to get some text from the user and send it to a servlet.

The InputServlet servlet

Listing 2-4 shows a servlet that can retrieve the data from the form shown in Listing 2-3.

Listing 2-4: The InputServlet Servlet


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

public class InputServlet extends HttpServlet
{
 public void doGet(HttpServletRequest request,
 HttpServletResponse response)
 throws IOException, ServletException
 {
 String name = request.getParameter("Name");

 response.setContentType("text/html");
 PrintWriter out = response.getWriter();

 out.println("

"); out.println(""); out.println("Input Servlet"); out.println(""); out.println(""); out.println("

"); out.println("Hello " + name); out.println("

"); out.println(""); out.println(""); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } }

As you can see, this servlet really isn't that much different than the first HelloWorld servlet from Listing 2-1. The biggest difference is that it retrieves the value entered by the user into the name field and uses it in the HTML that's sent to the response PrintWriter object. For example, if the user enters Calvin Coolidge into the name input field, the following HTML is generated:


HelloWorld

Hello Calvin Coolidge

Thus the message Hello Calvin Coolidge is displayed on the page.

Although real-life servlets do a lot more than just parrot back information entered by the user, most of them follow this surprisingly simple structure, with a few variations of course. For example, real-world servlets validate input data and display error messages if the user enters incorrect data or omits important data. And most real-world servlets retrieve or update data in files or databases. Even so, the basic structure is pretty much the same.


Using Classes in a Servlet

When you develop servlets, you often want to access other classes you've created, such as I/O classes that retrieve data from files or databases, utility or helper classes that provide common functions such as data validation, and perhaps even classes that represent business objects such as customers or products. To do that, all you have to do is save the class files in the classes directory of the servlet's home directory that, for the purposes of this chapter, is c: omcatwebappsROOTWEB-INFclasses.

To illustrate a servlet that uses several classes, Figure 2-5 shows the output from a servlet that lists movies read from a text file. This servlet uses three classes:

  • Movie: A class that represents an individual movie.
  • MovieIO: A class that has a static public method named getMovies. This method returns an ArrayList object that contains all the movies read from the file.
  • ListFiles: The main servlet class. It calls the MovieIO.getMovies class to get an ArrayList of movies, and then displays the movies on the page.

image from book
Figure 2-5: The ListMovies servlet.

The code for the Movie class is shown in Listing 2-5. As you can see, this class doesn't have much: It defines three public fields (title, year, and price) and a constructor that lets you create a new Movie object and initialize the three fields. Note that the price field isn't used by this servlet.

Listing 2-5: The Movie Class


public class Movie
{
 public String title;
 public int year;
 public double price;
 public Movie(String title, int year,
 double price)
 {
 this.title = title;
 this.year = year;
 this.price = price;
 }
}

Listing 2-6 shows the MovieIO class. This class uses the file I/O features that are presented in Book VIII, Chapter 2 to read data from a text file. The text file uses tabs to separate the fields, and contains these lines:


It's a Wonderfulimage from book1946image from book14.95
The Great Raceimage from book1965image from book12.95
Young Frankensteinimage from book1974image from book 16.95
The Return of the Pink Pantherimage from book1975image from book11.95
Star Warsimage from book1977image from book 17.95
The Princess Brideimage from book1987image from book 16.95
Gloryimage from book1989image from book14.95
Apollo 13image from book1995image from book 19.95
The Gameimage from book1997image from book14.95
The Lord of the Rings:The Fellowship of the Ringimage from book2001image from book19.95

Here the arrows represent tab characters in the file. I'm not going to go over the details of this class here, except to point out that getMovies is the only public method in the class, and it's static so you don't have to create an instance of the MovieIO class to use it. For the details on how this class works, refer to Book VIII, Chapter 2.

Listing 2-6: The MovieIO Class



import java.io.*;
import java.util.*;

public class MovieIO
{
 public static ArrayList getMovies()
 {
 ArrayList movies =
 new ArrayList();
 BufferedReader in =
 getReader("c:\data\movies.txt");
 Movie movie = readMovie(in);
 while (movie != null)
 {
 movies.add(movie);
 movie = readMovie(in);
 }
 return movies;
 }

 private static BufferedReader getReader(
 String name)
 {
 BufferedReader in = null;
 try
 {
 File file = new File(name);
 in = new BufferedReader(
 new FileReader(file));
 }
 catch (FileNotFoundException e)
 {
 System.out.println(
 "The file doesn't exist.");
 System.exit(0);
 }
 catch (IOException e)
 {
 System.out.println("I/O Error");
 System.exit(0);
 }
 return in;
 }

 private static Movie readMovie(BufferedReader in)
 {
 String title;
 int year;
 double price;
 String line = "";
 String[] data;

 try
 {
 line = in.readLine();
 }
 catch (IOException e)
 {
 System.out.println("I/O Error");
 System.exit(0);
 }
 if (line == null)
 return null;
 else
 {
 data = line.split("	");
 title = data[0];
 year = Integer.parseInt(data[1]);
 price = Double.parseDouble(data[2]);
 return new Movie(title, year, price);
 }
 }
}

Listing 2-7 shows the code for the ListMovie servlet class.

Listing 2-7: The ListMovie Servlet Class


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

public class ListMovies extends HttpServlet
{
 public void doGet(HttpServletRequest request, →8
 HttpServletResponse response)
 throws IOException, ServletException
 {
 response.setContentType("text/html");
 PrintWriter out = response.getWriter();
 String msg = getMovieList();
 out.println("

"); out.println(""); out.println( "List Movies Servlet"); out.println(""); out.println(""); out.println("

Some of My Favorites

"); out.println("

"); out.println(msg); out.println("

"); out.println(""); out.println(""); } public void doPost(HttpServletRequest request, → 28 HttpServletResponse response) throws IOException, ServletException { doGet(request, response); } private String getMovieList() → 35 { String msg = ""; ArrayList movies = MovieIO.getMovies(); for (Movie m : movies) { msg += m.year + ": "; msg += m.title + "
"; } return msg; } }

The following paragraphs describe what each of its methods do:

8

The doGet method calls the getMovieList method to get a string that contains a list of all the movies separated by break tags. Then it uses a series of out.println statements to write HTML that displays this list.

28

The doPost method simply calls the doGet method. That way, the servlet works whether it is invoked by a GET or POST request.

35

The getMovieList method calls the MovieIO.getMovies method to get an ArrayList that contains all the movies read from the file. Then it uses an enhanced for loop to retrieve each Movie object. Each movie's year and title is added to the msg string, separated by
tags.

Open table as spreadsheet


Chapter 3 Using Java Server Pages

Book I - Java Basics

Book II - Programming Basics

Book III - Object-Oriented Programming

Book IV - Strings, Arrays, and Collections

Book V - Programming Techniques

Book VI - Swing

Book VII - Web Programming

Book VIII - Files and Databases

Book IX - Fun and Games



Java All-In-One Desk Reference For Dummies
Java All-In-One Desk Reference For Dummies
ISBN: 0470124512
EAN: 2147483647
Year: 2004
Pages: 332

Flylib.com © 2008-2020.
If you may any questions please contact us: flylib@qtcs.net