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.
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:
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.
The request includes the name of the file that you want to retrieve.
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:
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.
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 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:
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.
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.
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. |
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. |
The context.xml file is located in c: omcatconf. The second line is initially this:
Change it to:
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. |
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.)
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.
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.
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.)
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. |
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.
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.
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.
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:
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!.
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("
"); out.println(""); } }
Here the following HTML is sent to the browser (I added indentation to show the HTML's structure):
HelloWorld
When run, the HelloWorld servlet produces the page shown in Figure 2-3.
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. |
, ,,,
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); }
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(""); 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; } }
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.
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.
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.
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(""); 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
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.
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:
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 Wonderful194614.95 The Great Race196512.95 Young Frankenstein1974 16.95 The Return of the Pink Panther197511.95 Star Wars1977 17.95 The Princess Bride1987 16.95 Glory198914.95 Apollo 131995 19.95 The Game199714.95 The Lord of the Rings:The Fellowship of the Ring200119.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("
"); 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 |
Open table as spreadsheet
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