JSPs were introduced to make Java web programming more appealing for the novice, letting you mix HTML and Java code. JSPs are actually based on Java servlets (they're translated into servlets before being run), which are pure Java code, and which we're going to focus on for the most part in this chapter. You can see an example servlet in Example 9-2.
In this case, we're tailoring our response to the browser by using the
method to get a
object, and we're using that object's
method to send HTML back to the browser. In this case, we're just sending back an HTML page with the text "Using servlets" in it.
To follow along, create a new project,
, and enter the code in
into a new class,
, in that project, using the package
the imports we need for this code, include
, which comes with Tomcat, in the build
. You can find
; right-click the
project in the Package Explorer, select Properties, and then add
to the build path.
At this point, you should be able to build the servlet by selecting the
project in the Package Explorer and selecting Project
Build Project, creating
. Class files like this go into the Tomcat
directory. Our servlet is in the
package, and the directory structure must mirror the package structure, so put
_ _ch09 Directory for the servlet code
To let Tomcat know that this new class is a servlet, you use a file named
that holds configuration data for web applications. In this file, we use two XML elements,
, to connect the URL
to the actual Java code for the servlet,
. You can see what
looks like in Example 9-3.
Example 9-3. Updating web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
Create this new document,
, in Eclipse now, by right-clicking the project and selecting New
in Eclipse, right-click it and select the Open With
Text Editor item (if you just double-click it, your default XML editorfor example, Internet Explorer in Windowswill open the file instead, unless you have an XML plug-in like XMLBuddy installed). Enter the XML in Example 9-3, store the file, and then copy it to the
_ _WEB-INF Information about Chapter 9's web applications
Finally, shut Tomcat down and restart it. We're ready to go; in the browser, navigate to the URL
, and you should see the results in Figure 9-4.
Figure 9-4. Viewing a new servlet
Not badwe've used Eclipse to develop a new servlet. At this point, we've still been developing our code and then copying it to the Tomcat directories, but Eclipse can also handle the file handling for us.