Tải bản đầy đủ (.pdf) (89 trang)

Java All-in-One Desk Reference For Dummies phần 8 ppsx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.88 MB, 89 trang )


Book VI
Chapter 5
Using Layout
Managers
Using GridBag Layout
597
✦ You also want to set the anchor field to indicate where you want the
component placed if it doesn’t fill the cell or cells allotted to it.
Working with GridBagConstraints
To create a GridBagConstraint object, you call the GridBagConstraint
constructor, and then set any of the fields that you want to vary from the
default values. For example, here’s code that creates a
GridBagConstraint
object to add the name text field that is shown earlier in Figure 5-5:
GridBagConstraints nameConstraints
= new GridBagConstraints();
nameConstraints.gridx = 1;
nameConstraints.gridy = 0;
nameConstraints.gridwidth = 2;
nameConstraints.gridheight = 1;
nameConstraints.weightx = 100.0;
nameConstraints.weighty = 100.0;
nameConstraints.insets = new Insets(5, 5, 5, 5);
nameConstraints.anchor = GridBagConstraints.WEST;
nameConstraints.fill = GridBagConstraints.NONE;
Then, you can call the add method to add the name text field to the panel:
panel1.add(name, nameConstraints);
Obviously, this approach to controlling constraints is going to require a lot
of coding. You have two common alternatives to creating a new constraint
object for every component you add to the panel. The first is to create a


single constraint object and reuse it for all the components in the panel.
Then, you simply change the fields that need to be changed for each compo-
nent. For example, here’s code that adds all three text fields using a single
constraint object:
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = 0;
gc.gridy = 0;
gc.gridwidth = 1;
gc.gridheight = 1;
gc.weightx = 100.0;
gc.weighty = 100.0;
gc.insets = new Insets(5, 5, 5, 5);
gc.anchor = GridBagConstraints.WEST;
gc.fill = GridBagConstraints.NONE;
gc.gridy = 0;
gc.gridwidth = 2;
43_58961X bk06ch05.qxd 3/29/05 3:41 PM Page 597
Using GridBag Layout
598
add(name, gc);
gc.gridy = 1;
gc.gridwidth = 1;
add(phone, gc);
gc.gridy = 2;
gc.gridwidth = 2;
add(address, gc);
Here, the first group of statements creates a GridBagConstraints object
named
gc and sets its values to the defaults that I want to apply to most of
the components in the panel. Then, the second group of statements sets the

gridy and gridwidth fields before adding each text field to the panel.
The second option is to create a helper method that you can call, passing
just the values that vary for each component. For example, here’s a method
named
addItem that adds a component and left aligns it within the speci-
fied cells:
private void addItem(JPanel p, JComponent c, int x, int y,
int width, int height, int align)
{
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = x;
gc.gridy = y;
gc.gridwidth = width;
gc.gridheight = height;
gc.weightx = 100.0;
gc.weighty = 100.0;
gc.insets = new Insets(5, 5, 5, 5);
gc.anchor = align;
gc.fill = GridBagConstraints.NONE;
p.add(c, gc);
}
Then, you can call this method to add a component to the panel. You must
pass the panel and the component, its x and y position, and its width and
height. For example, here’s how you add the name text field:
addItem(panel1, name, 0, 1, 2, 1,
GridBagConstraints.WEST);
A GridBag layout example
Listing 5-1 shows the code for a program that displays the frame that I drew
in Figure 5-5, and Figure 5-6 shows how this frame appears when the pro-
gram is run. As you can see, the final appearance of this frame is pretty close

to the way I sketched it out at McDonald’s. I could probably fix a few minor
variations with a little tweaking.
43_58961X bk06ch05.qxd 3/29/05 3:41 PM Page 598
Book VI
Chapter 5
Using Layout
Managers
Using GridBag Layout
599
LISTING 5-1:THE PIZZA ORDER APPLICATION
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Pizza extends JFrame
{
public static void main(String [] args)
{
new Pizza();
}
JTextField name, phone, address;
JRadioButton small, medium, large, thick, thin;
JCheckBox pepperoni, mushrooms, anchovies;
JButton okButton, closeButton;
public Pizza()
{
this.setTitle(“Pizza Order”);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel1 = new JPanel();
panel1.setLayout(new GridBagLayout());


23
addItem(panel1, new JLabel(“Name:”),

25
0, 0, 1, 1, GridBagConstraints.EAST);
addItem(panel1, new JLabel(“Phone:”),
0, 1, 1, 1, GridBagConstraints.EAST);
addItem(panel1, new JLabel(“Address:”),
0, 2, 1, 1, GridBagConstraints.EAST);
name = new JTextField(20);
phone = new JTextField(10);
address = new JTextField(20);
addItem(panel1, name, 1, 0, 2, 1,

36
GridBagConstraints.WEST);
addItem(panel1, phone, 1, 1, 1, 1,
continued
Figure 5-6:
The Pizza
Order
application
in action.
43_58961X bk06ch05.qxd 3/29/05 3:41 PM Page 599
Using GridBag Layout
600
LISTING 5-1 (CONTINUED)
GridBagConstraints.WEST);
addItem(panel1, address, 1, 2, 2, 1,
GridBagConstraints.WEST);

Box sizeBox = Box.createVerticalBox();

43
small = new JRadioButton(“Small”);
medium = new JRadioButton(“Medium”);
large = new JRadioButton(“Large”);
ButtonGroup sizeGroup = new ButtonGroup();
sizeGroup.add(small);
sizeGroup.add(medium);
sizeGroup.add(large);
sizeBox.add(small);
sizeBox.add(medium);
sizeBox.add(large);
sizeBox.setBorder(
BorderFactory.createTitledBorder(“Size”));
addItem(panel1, sizeBox, 0, 3, 1, 1,
GridBagConstraints.NORTH);
Box styleBox = Box.createVerticalBox();

59
thin = new JRadioButton(“Thin”);
thick = new JRadioButton(“Thick”);
ButtonGroup styleGroup = new ButtonGroup();
styleGroup.add(thin);
styleGroup.add(thick);
styleBox.add(thin);
styleBox.add(thick);
styleBox.setBorder(
BorderFactory.createTitledBorder(“Style”));
addItem(panel1, styleBox, 1, 3, 1, 1,

GridBagConstraints.NORTH);
Box topBox = Box.createVerticalBox();

72
pepperoni = new JCheckBox(“Pepperoni”);
mushrooms = new JCheckBox(“Mushrooms”);
anchovies = new JCheckBox(“Anchovies”);
ButtonGroup topGroup = new ButtonGroup();
topGroup.add(pepperoni);
topGroup.add(mushrooms);
topGroup.add(anchovies);
topBox.add(pepperoni);
topBox.add(mushrooms);
topBox.add(anchovies);
topBox.setBorder(
BorderFactory.createTitledBorder(“Toppings”));
addItem(panel1, topBox, 2, 3, 1, 1,
GridBagConstraints.NORTH);
Box buttonBox = Box.createHorizontalBox();

88
okButton = new JButton(“OK”);
closeButton = new JButton(“Close”);
buttonBox.add(okButton);
buttonBox.add(Box.createHorizontalStrut(20));
buttonBox.add(closeButton);
43_58961X bk06ch05.qxd 3/29/05 3:41 PM Page 600
Book VI
Chapter 5
Using Layout

Managers
Using GridBag Layout
601
addItem(panel1, buttonBox, 2, 4, 1, 1,
GridBagConstraints.NORTH);
this.add(panel1);
this.pack();
this.setVisible(true);
}
private void addItem(JPanel p, JComponent c,
int x, int y, int width, int height, int align)
{
GridBagConstraints gc = new GridBagConstraints();
gc.gridx = x;
gc.gridy = y;
gc.gridwidth = width;
gc.gridheight = height;
gc.weightx = 100.0;
gc.weighty = 100.0;
gc.insets = new Insets(5, 5, 5, 5);
gc.anchor = align;
gc.fill = GridBagConstraints.NONE;
p.add(c, gc);
}
}
Note that this application doesn’t include any event listeners, so the buttons
don’t do anything other than demonstrate how to use the GridBag layout.
The following paragraphs point out the highlights:

23 This line creates a GridBag layout manager for the panel.


25 These lines add the labels to the panel.

36 These lines add the text fields to the panel.

43 These lines use a vertical Box object to create the radio buttons that
let the user select the size.

59 These lines use a vertical Box object to create the radio buttons that
let the user select the crust style.

72 These lines use a vertical Box object to create the check boxes that
let the user select check boxes.

88 These lines use a horizontal Box object to hold the OK and Close
buttons.
43_58961X bk06ch05.qxd 3/29/05 3:41 PM Page 601
Book VI: Swing
602
43_58961X bk06ch05.qxd 3/29/05 3:41 PM Page 602
Book VII
Web Programming
44_58961X pt07.qxd 3/29/05 3:40 PM Page 603
Contents at a Glance
Chapter 1: Creating Applets 605
Chapter 2: Creating Servlets 613
Chapter 3: Using Java Server Pages 633
Chapter 4: Using JavaBeans 647
44_58961X pt07.qxd 3/29/05 3:40 PM Page 604
Chapter 1: Creating Applets

In This Chapter
ߜ Looking at applets
ߜ Creating an applet
ߜ Creating HTML to display applets
ߜ Testing applets with the applet viewer
A
n applet is not a small piece of fruit. Rather, it’s a Java application
that’s designed to run in a browser window on an Internet user’s com-
puter. When an Internet user visits a Web page that contains an applet, the
Java applet class is downloaded to the user’s computer and run there. The
applet takes over a portion of the page and, within that space, can do any-
thing it wants.
Applets are, at least in most cases, Swing applications. As a result, every-
thing that’s covered in Book VI applies to applets. In this chapter, you create
applets that include Swing components. Then, you add an applet to a Web
page so anyone who views the page can use it.
Understanding Applets
An applet is similar to a Swing application, with several crucial differences:
✦ Instead of extending the
JFrame class, applets extend the JApplet
class. Both JFrame and JApplet provide a “space” for your Swing
application to operate in:
• With
JFrame, that space is a window that’s managed by the host
operating system’s windowing system.
• With
JApplet, the space is a rectangular area of a Web page that’s
managed by a Web browser.
✦ Stand-alone Swing applications are started when the JVM calls the static
main method. Thus, a Swing application typically starts by creating an

instance of the class that extends
JFrame. In contrast, the browser auto-
matically creates an instance of the class that extends
JApplet when the
applet is started. As a result, applets don’t have a static
main method.
Instead, a method named
init is called to get the applet started. As a
result, the
init method is where you put the code that you’d put in the
constructor for a class that extends
JFrame.
45_58961X bk07ch01.qxd 3/29/05 3:40 PM Page 605
The JApplet Class
606
✦ Stand-alone Swing methods need a way to let the user shut them down.
Typically, Swing applications include an Exit button or an Exit menu
command. Applets don’t. An applet remains alive as long as the page
that contains it is displayed.
✦ Applets aren’t displayed in windows; they’re displayed in a region of a
Web page. As a result, you can’t set the text for an applet’s title bar, and
you can’t set the
DefaultCloseOperation, because there’s no Close
button for the user to click. In addition, the user can’t resize the applet.
✦ For security reasons, applets are prohibited from doing certain things. In
particular, an applet is not allowed to do anything that affects the client
computer’s file system, including reading or writing files, or running pro-
grams on the client computer.
Other than these differences and restrictions, an applet works pretty much
the same as a Swing application. In fact, the Swing components inside the

applet look and behave exactly like they do in a stand-alone Swing applica-
tion. Thus, applets let you create Swing applications and run them on any
computer, anywhere in the world. Right?
Would that it were so. Unfortunately, the company that makes the world’s
most popular Web browser, whose name I won’t mention but whose initials
are MICROSOFT, hasn’t played nice with Sun. Or maybe Sun hasn’t played
nice with Microsoft. Who knows. Either way, the result has been a mess
when it comes to whether or not users’ computers can run applets, and if
they can, what version of Java they support. Users can download the Java
plug-in from Sun, but the download is large, and most users either don’t
want to take the time, don’t understand the process, or don’t trust it.
As a result, applets aren’t the best way to create Web-based applications that
you expect to be used by the masses. The biggest sites on the Internet, such
as eBay and Amazon, are not implemented with applets; instead, they’re built
using tools such as servlets and Java Server Pages as described in the other
chapters of Book VII.
The JApplet Class
As I’ve already mentioned, an applet extends the JApplet class rather than
the
JFrame class. For the most part, the JApplet class works pretty much
the same as the
JFrame class. As a result, you can add panels and other
components to it, create menus, doodle on it, and so on. Table 1-1 lists the
most commonly used methods of the
JApplet class.
45_58961X bk07ch01.qxd 3/29/05 3:40 PM Page 606
Book VII
Chapter 1
Creating Applets
Looking At a Sample Applet

607
Table 1-1 Useful JApplet Constructors and Methods
Constructor Description
JApplet()
Creates a new applet. You don’t usually need
to call the
JApplet constructor because it’s
called automatically when the browser loads
the applet.
Method Description
void add
Adds the specified component to the applet.
(Component c)
void destroy()
Called by the browser to inform the applet that
its memory is about to be reclaimed by the
JVM. Most applets don’t need to override this
method.
void init() Called by the browser to inform the applet that
it has been loaded. This method takes the
place of the
JFrame constructor for a Swing
application.
void setLayout Sets the layout manager used to control how
(LayoutManager layout) components are arranged when the applet is
displayed. The default is the Border Layout
manager.
void setLocation Sets the x and y position of the applet
(int x, int y) on-screen. The top left corner of the screen
is 0, 0.

void setLocationRelativeTo Centers the applet on-screen if the parameter
(Component c) is null.
void setSize(int width, Sets the size of the applet to the specified
int height) width and height.
void setJMenuBar Sets the menu for this applet.
(JMenuBar menu)
void start()
Called by the browser to inform the applet to
start its execution.
void stop() Called by the browser when the applet tem-
porarily leaves view. Override this method if
you need to stop activities while the applet is
hidden.
Looking At a Sample Applet
To see how a complete applet works, Listing 1-1 shows the complete code
for an applet that lets the user order a pizza in one of three sizes (Small,
Medium, and Large) with one of three toppings (Pepperoni, Mushrooms,
and Anchovies). Figure 1-1 shows this applet in action on a Web page.
45_58961X bk07ch01.qxd 3/29/05 3:40 PM Page 607
Looking At a Sample Applet
608
LISTING 1-1:THE PIZZA ORDER APPLET
import javax.swing.*;
import java.awt.event.*;
import javax.swing.border.*;
public class PizzaApplet extends JApplet

5
{
private JButton buttonOK;

private JRadioButton small, medium, large;
private JCheckBox pepperoni, mushrooms, anchovies;
public void init()

12
{
this.setSize(320,200);

14
ButtonListener bl = new ButtonListener();
JPanel mainPanel = new JPanel();
JPanel sizePanel = new JPanel();
Border b1 =
BorderFactory.createTitledBorder(“Size”);
sizePanel.setBorder(b1);
ButtonGroup sizeGroup = new ButtonGroup();
Figure 1-1:
The pizza
applet in
action.
45_58961X bk07ch01.qxd 3/29/05 3:40 PM Page 608
Book VII
Chapter 1
Creating Applets
Looking At a Sample Applet
609
small = new JRadioButton(“Small”);
small.setSelected(true);
sizePanel.add(small);
sizeGroup.add(small);

medium = new JRadioButton(“Medium”);
sizePanel.add(medium);
sizeGroup.add(medium);
large = new JRadioButton(“Large”);
sizePanel.add(large);
sizeGroup.add(large);
mainPanel.add(sizePanel);
JPanel topPanel = new JPanel();
Border b2 =
BorderFactory.createTitledBorder(“Toppings”);
topPanel.setBorder(b2);
pepperoni = new JCheckBox(“Pepperoni”);
topPanel.add(pepperoni);
mushrooms = new JCheckBox(“Mushrooms”);
topPanel.add(mushrooms);
anchovies = new JCheckBox(“Anchovies”);
topPanel.add(anchovies);
mainPanel.add(topPanel);
buttonOK = new JButton(“OK”);
buttonOK.addActionListener(bl);
mainPanel.add(buttonOK);
this.add(mainPanel);
this.setVisible(true);
}
private class ButtonListener implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == buttonOK)
{

String tops = “”;
if (pepperoni.isSelected())
tops += “Pepperoni\n”;
if (mushrooms.isSelected())
tops += “Mushrooms\n”;
continued
45_58961X bk07ch01.qxd 3/29/05 3:40 PM Page 609
Looking At a Sample Applet
610
LISTING 1-1 (CONTINUED)
if (anchovies.isSelected())
tops += “Anchovies\n”;
String msg = “You ordered a “;
if (small.isSelected())
msg += “small pizza with “;
if (medium.isSelected())
msg += “medium pizza with “;
if (large.isSelected())
msg += “large pizza with “;
if (tops.equals(“”))
msg += “no toppings.”;
else
msg += “the following toppings:\n”
+ tops;
JOptionPane.showMessageDialog(buttonOK,
msg, “Your Order”,
JOptionPane.INFORMATION_MESSAGE);
pepperoni.setSelected(false);
mushrooms.setSelected(false);
anchovies.setSelected(false);

small.setSelected(true);
}
}
}
}
This is an applet version of a Swing program that is in Book VI, Chapter 3. For
the details on how the Swing components work, you can refer to that chapter.
Here, I just want to point out a few details that are specific to applets:

5 The class extends JApplet instead of JFrame.

12 The init method is overridden, and the code that ordinarily is in
the constructor for the
JFrame class is placed in the init method.

14 The setSize method is called to set the size of the applet.
Several methods that appeared in the Swing version of this
program, however, are removed. In particular, the
setTitle and
setDefaultCloseAction methods are deleted, because those
methods don’t apply to applets. From the rest of this method, how-
ever, you can see that most of this code is exactly the same as it is
for a stand-alone Swing application.
45_58961X bk07ch01.qxd 3/29/05 3:40 PM Page 610
Book VII
Chapter 1
Creating Applets
Testing an Applet
611
Creating an HTML Page for an Applet

To run an applet, you must create an HTML page that includes an APPLET
tag that specifies the name of the applet and the size of the region you want
to let the applet run inside. The
APPLET tag also includes text that’s dis-
played if the Web browser isn’t capable of running the applet.
The basic form of the
APPLET tag is this:
<APPLET code=”classname” width=width height=height>
Text to display if applet can’t be loaded
</APPLET>
For example, here’s the HTML file that I used to display the page shown in
Figure 1-1:
<html>
<head>
<title>The Pizza Applet</title>
</head>
<body>
<H1>Welcome to the Pizza Applet!</H1>
<APPLET code=”PizzaApplet” width=”300” height=”180”>
Sorry, your browser isn’t able to run Java applets.
</APPLET>
</body>
</html>
Testing an Applet
Java comes with a special program called the applet viewer that lets you
quickly run an applet after you compile it. Figure 1-2 shows the pizza applet
displayed in the applet viewer.
Figure 1-2:
The pizza
applet

displayed in
the applet
viewer.
45_58961X bk07ch01.qxd 3/29/05 3:40 PM Page 611
Testing an Applet
612
If you’re using TextPad, you can invoke the viewer by pressing Ctrl+3 after
you compile the applet. From a command prompt, you must first create an
HTML file as described in the previous section. Then, navigate to the direc-
tory that contains the HTML file and type this command:
appletviewer filename
For example, to display the pizza applet with an HTML file named
PizzaApplet.html, use this command:
Appletviewer PizzaApplet.html
45_58961X bk07ch01.qxd 3/29/05 3:40 PM Page 612
Chapter 2: Creating Servlets
In This Chapter
ߜ Looking at servlets
ߜ Downloading, installing, and configuring Tomcat
ߜ Creating simple servlets
ߜ Working with forms to get data from the user
S
ervlets 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 net-
working 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 com-
puter 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.
46_58961X bk07ch02.qxd 3/29/05 3:39 PM Page 613
Using Tomcat
614
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:
3. 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 gen-
erates 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 com-
puter 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
jakarta.apache.org/tomcat.
Tomcat can also work as a basic Web server. In actual production environ-
ments, Tomcat is usually used in combination with a specialized Web server,
such as Apache’s HTTP Server.
46_58961X bk07ch02.qxd 3/29/05 3:39 PM Page 614
Book VII
Chapter 2
Creating Servlets

Using Tomcat
615
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 choos-
ing 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 jakarta-
tomcat-5.5.4 (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:\tomcat.
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 Files\Java\jdk1.5.0.
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 jre\lib\ext folder in your
JDK root.
For example, if your JDF is installed in
c:\Program Files\Java\
jdk1.5.0, copy this file to c:\Program Files\Java\jdk1.5.0\
jre\lib\ext.You find the servlet-api.jar file in c:\tomcat\
common\lib, assuming you extracted the Tomcat files to c:\tomcat.
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 mes-
sages 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 <context> tag.
The
context.xml file is located in c:\tomcat\conf. The second
line is initially this:
<Context>
46_58961X bk07ch02.qxd 3/29/05 3:39 PM Page 615
Using Tomcat
616
Change it to:
<Context reloadable=”true”>
6. Modify the web.xml file to enable the invoker servlet.
Like
context.xml, the web.xml file is located in c:\tomcat\conf.

It contains two groups of lines that configure a Tomcat feature called the
invoker servlet that you need to modify. These lines are initially com-
mented 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:
<!
<servlet>
<servlet-name>invoker</servlet-name>
<servlet-class>
org.apache.catalina.servlets.InvokerServlet
</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
>
Simply remove the first (<! ) and last ( >) of these lines.
The second group looks like this:
<!
<servlet-mapping>
<servlet-name>invoker</servlet-name>
<url-pattern>/servlet/*</url-pattern>
</servlet-mapping>
>
Once again, you must remove the first and last line so these lines aren’t
treated as comments.
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 direc-
tory
c:\tomcat\webapps\ROOT\WEB-INF\classes. Unfortunately,
the
classes directory is missing. So you must navigate to c:\tomcat\
webapps\ROOT\WEB-INF and create the classes directory. (Of course,
the
c:tomcat part of these paths varies if you installed Tomcat in some
other location.)
46_58961X bk07ch02.qxd 3/29/05 3:39 PM Page 616
Book VII
Chapter 2
Creating Servlets
Using Tomcat
617
Starting and stopping Tomcat
After you install and configure Tomcat, you can start it by opening a command
window, changing to the
c:\tomcat\bin 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.
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
If the Tomcat window appears for a few seconds, and then an exception mes-
sage 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 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:\tomcat\
conf and look for this tag:
<Connector port=”8080” />
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.
Figure 2-1:
Starting up
Tomcat.
46_58961X bk07ch02.qxd 3/29/05 3:39 PM Page 617
Using Tomcat
618
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:\tomcat\bin 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.
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.
Figure 2-2:
Testing
Tomcat.
46_58961X bk07ch02.qxd 3/29/05 3:39 PM Page 618
Book VII
Chapter 2
Creating Servlets
Creating a Simple Servlet
619
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 addi-
tional
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

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()
46_58961X bk07ch02.qxd 3/29/05 3:39 PM Page 619
Creating a Simple Servlet
620
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 call-
ing 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.
46_58961X bk07ch02.qxd 3/29/05 3:39 PM Page 620

×