Chapter 1. Getting Started!

Welcome to JavaServer Pages (JSP)! Over the next 21 days, you'll get an in-depth guided tour of the ins and outs of JSP. From the most basic aspects to the most advanced, we're going to become masters of JSP in this book. You've come to the right place.

If you want to do Web programming on the server, there's just nothing like JSP. It's easy to get started with JSP, and because it has the incredible power of Java behind it, there's no limit to how far you can go. Traditionally, server programming was a task only for experts, but with JSP, that's all in the past—now anyone can make Web pages come alive as never before.

Let's dig into JSP immediately. In this, our first day on the job, we're going to take a look at these topics:

  • What JavaServer Pages can help you do

  • Setting up your development environment

  • Running the Tomcat Server

  • How we got here: from HTML to JSP

  • Building and dissecting your first JSPs

  • Understanding JSP syntax

  • JSP resources online

We're going to work with JavaServer Pages 1.2 in this book, but as you'll find, JSP itself is only the beginning. Because JSP lets you use Java to create Web pages on the server, much of what we're going to study is Java itself, as we see what we can do with JSP. And you'll find there's practically no limit.

What Are JavaServer Pages Good For?

Take a look at Figure 1.1, which shows the home page of Delta Airlines. Note the URL at the top of the browser: http://www.delta.com/home/index.jsp. The JSP in the index.jsp portion is the JSP in JavaServer Pages.

The Delta Airlines home page.

Figure 1.1. The Delta Airlines home page.

It's easy to find JSP at work everywhere on the Web these days. In fact, JSP is becoming the new standard for easily developed, easily maintained Web applications. As you might expect, there are many, many reasons for JSP's soaring popularity, and more are being invented all the time. Here are a couple of things that JSP can do for your Web pages—this is just a starter list, of course:

  • Making Web pages come alive—. There are too many static pages on the Internet already. Why add yours to the list? To get noticed, your page must be live—it must do something, or offer some service. What better way to liven pages up yourself than to use JSP? Now your Web pages can interact with the user in real time.

  • Getting data from the user—. All the text fields, radio buttons, check boxes, and so on, you see in Web pages can hold data. JSP makes it easy to read that data back to the server, and to send Web pages that use that data back to the browser, as we'll see in Day 4, “Reading Data from Web Pages: Buttons and Fields,” and Day 5, “Reading Data from Web Pages: Check Boxes, Radio Buttons, and Select Controls.”

  • Easier to program—. There are plenty of server-side programming options out there, but none easier to program than JSP. In fact, JSP is specifically designed to be easy to program, as you'll see today.

  • More power through Java—. JSP lets you run Java code when creating Web pages. That fact alone makes what you can do with JSP practically boundless. Java is an ever-expanding, nearly endless programming package, and JSP puts it at your service. And you don't have to be a Java expert either—you can start small, as we will in this book, building up to whatever level you want.

  • Connecting to databases—. One of the most popular things you can do with JSP on the server is connect to databases via Java. It's not as hard as you might think, and we'll see how to connect to databases, add our own data to them, get data out of them, and more in this book.

  • Performance—. JSP is built to perform better than other server-side programming packages. JSP is built right into the server software itself, which means that many users can access your Web page without using a lot of extra memory or degrading performance. In some other server-side programming packages, a whole new process has to start for every user that accesses your Web page, and if a lot of users are downloading that page, it can bring the server to a virtual halt.

  • Separating code and data—. A very big topic in the programming world these days is the separation of code and data, and JSP fits right into that. The idea is that when your JSP programming code that the server runs is separate from the data that that code works on, it's easier to write and maintain your programs. As we'll see in this book, there are some new ways of working with JSP that let you separate code and data very effectively.

  • Handling cookies—. A popular use of JSP is to work with cookies, storing information on the user's machine. Some people love cookies, some hate them, but there's no doubt that JSP allows you to use them. Want to record a user's special settings for your Web page? A JSP cookie will do that. You'll see how to work with cookies in Day 7, “Tracking Users with Sessions and Cookies.”

In choosing JSP, you've chosen the right package for server-side programming. You can do startlingly powerful things with JSP, because JSP has the full power of Java behind it on the server. For example, take a look at Figure 1.2, which shows an example we'll develop later in the book (in Day 20, “Creating Images on the Server and Handling Internet Programming,” where you'll learn how to create and draw images using Java). In this case, the user can “draw” a line in the browser using the mouse, and the software we'll develop for the server will actually create the corresponding image file (a JPEG file) and send that image back to the browser, as you see in the figure. That's a JPEG image file you're looking at in the figure, created interactively with Java on the server thanks to JSP.

Creating a JPEG image file.

Figure 1.2. Creating a JPEG image file.

Let's get down to business by setting up your own development environment in which to create and use JSP ourselves. This development environment will give you a JSP server and allow you to develop your own JSP-enabled Web pages. All the software you'll need is free, and you can download it from various sites on the Web.

It All Starts with Java

The J in JSP is for the Java programming language, and we're going to need Java to run JSP. If you already have access to a Web server that runs Java and JSP, congratulations—you're all set. On the other hand, if you don't yet have access to such a server, or want to develop your JSP code offline on your own computer, we can set up our own development environment.

The first thing to install is Java itself, which the Web server will need to access to run your JSP code. Java is a product of Sun Microsystems, and you can download it for free from its Web site. We're going to use Java 2 Standard Edition; the current version is 1.4. (That might be different when you read this, however—you should get the latest version of the Java 2 Standard Edition SDK, the Software Development Kit.) Here are the URLs you'll need:

  • http://java.sun.com/j2se/—. The home page for Java 2 Standard Edition. Go here to see your download options for Java.

  • http://java.sun.com/j2se/1.4/download.html—. The current download page for Java 1.4. You can also download the Java documentation here, which is a good idea.

Caution

Allow some time to download Java—the executable installation file is 20–36MB large, depending on what operating system you're using.

The installation instructions are online (you can view them from the download page). Typically, you run a self-extracting executable file, such as j2sdk-1_4_0-win.exe in Windows, or j2re-1_4_0-solx86.sh for the Solaris operating system. After you follow the installation instructions, you'll have Java installed.

The Tomcat Server

Now that you've installed Java, you're halfway there. The next step in creating your JSP development environment is to install a JSP-enabled Web server on your computer. There's nothing complex in this, although the idea of installing a Web server on your computer can sound a little daunting.

There are a number of JSP-enabled Web servers, and we'll use the one that's become the JSP standard: the Apache project's Tomcat server. This server is the standard throughout the JSP world, and it's the one Sun uses when creating its JSP implementation.

You can download the Tomcat server at http://jakarta.apache.org/tomcat/ (“Jakarta” is the name of the project that Tomcat is a part of). We'll use the most recent Tomcat version available as of this writing, version 4.0.3, which supports JSP version 1.2. Currently, you can download this version from http://jakarta.apache.org/builds/jakarta-tomcat-4.0/release/v4.0.3/bin/. Just pick the appropriate version for your system, such as jakarta-tomcat-4.0.3.zip for Windows, and unzip it in a directory of your choosing.

Note

In this book, the Zip file will be copied to the Windows directory C: omcat and unzipped there, which creates the directory C: omcatjakarta-tomcat-4.0.3, and plenty of subdirectories underneath it. You might want to use the same directory structure to make it easier to follow the examples we'll develop (substitute / for in Unix).

That installs Tomcat—now let's take a look at what we've got.

The Tomcat Directory Structure

The Tomcat Directory Structure
jakarta-tomcat-4.0.3 
|__bin                        Binary executable files
|__classes                    Classes available to all Web applications
|__common                     Classes available to internal classes and
                              Web applications
|   |__classes                Common Java classes
|   |__lib                    Common Java classes in Java Archive (JAR) format
|__conf                       Configuration files (such as passwords)
|__jasper                     JAR files used to process and run JSP pages
|__lib                        JAR files available to Web applications
|__logs                       The server's log files
|__server                     Internal Tomcat classes
|__webapps                    Directory for Web applications
|__work                       Scratch directory for holding temporary files

We'll get more familiar with this directory structure when we start using it in depth in the coming days.

Note in particular the webapps directory, which is where the Web applications you create go so they're accessible to the browser. For instance, the examples from Day 1 will go into the ch01 directory we'll add to webapps:

webapps 
|__ch01                       Our folder for Day 1 examples

The directory containing Web applications must also contain a directory named WEB-INF, with two subdirectories, classes and lib. WEB-INF, classes, and lib might all be empty, but Tomcat will expect them to be there before running your application:

webapps 
|__ch01                       Our folder for Day 1 examples
    |__WEB-INF                Information about Day 1's Web applications
         |__classes           Java classes used by Day 1's Web applications
         |__lib               JAR files used by Day 1's Web applications

We'll create the ch01, WEB-INF, classes, and lib directories we need in a moment, but first, let's start Tomcat itself.

Note

There will be plenty of path specifications in this book, such as jakarta-tomcat-4.0.3webappsch01 in Windows, or jakarta-tomcat-4.0.3/webapps/ch01 in Unix. If you're using Windows and you see forward slashes (/) in a path, it's a Unix path—just substitute backslashes () instead, and vice versa if you're a Unix user who sees forward slashes. The Tomcat directory structure is the same on all operating systems, except for operating system-dependent syntax, like using instead of /.

Starting Tomcat

Starting Tomcat

Tip

You can get the details on these environment variables by taking a look at the readme.txt document that comes with Tomcat, which will refer you to the document running.txt. It's also available online at http://jakarta.apache.org/tomcat/tomcat-4.0-doc/RUNNING.txt.

In particular, the environment variables to set are the following:

  • JAVA_HOME points to the installation directory of Java; for example, that might be C:jdk1.4 in Windows.

  • CATALINA_HOME points to the installation directory of Tomcat; for example, C: omcatjakarta-tomcat-4.0.3 (you get this path when you unzip Tomcat 4.0.3 in C: omcat).

  • PATH holds the search path the computer's operating system will search for programs to run. Make sure you add Java's bin directory to your path—for example, you would add C:jdk1.4in to the path if Java was installed to C:jdk1.4.

The way you actually set these variables varies by operating system. For example, to set JAVA_HOME to C:jdk1.4 in Windows 2000 Professional, you can select Start, Settings, Control Panel to open the control panel, and double-click the System icon in the control panel. Next, click the Advanced tab as you see in Figure 1.3. Doing so opens the Environment Variables dialog box; click the New button in the System Variables part, opening the New System Variable dialog you see in Figure 1.4.

The Advanced tab in the System Properties dialog in Windows 2000 Professional.

Figure 1.3. The Advanced tab in the System Properties dialog in Windows 2000 Professional.

Setting an environment variable in Windows 2000 Professional.

Figure 1.4. Setting an environment variable in Windows 2000 Professional.

You can enter the new setting for JAVA_HOME as you see in Figure 1.4: C:jdk1.4. To change the PATH variable, which already exists, you click the Edit button in the System Variables section and edit the PATH variable to add the Java bin directory to it. For example, if your path looks something like this:

C:WINDOWS;C:Program Files 

you'd add a semicolon and the path of the Java bin directory:

C:WINDOWS;C:Program Files;C:jdk1.4in 

How you set environment variables depends on the operating system, however; for example, the process is completely different in Windows 95/98, where you must edit the C:autoexec.bat file instead.

Tip

You can find excellent instructions on setting environment variables for all the operating systems that run Java from the Java download page, in the installation notes. Here's the URL with links for various operating systems: http://java.sun.com/j2se/1.4/install-operatingsystemname.html (for example, for Windows, the URL is http://java.sun.com/j2se/1.4/install-windows.html). These notes are all about setting the PATH environment variable, but you can use them to set any environment variable.

You can also set the environment variables when you start Tomcat itself, and you might find that more convenient. You'll find the directions for starting Tomcat in the running.txt document that comes with Tomcat.

To start Tomcat, you'll need a command prompt. In Windows, that's the DOS prompt, which you get in a DOS window. You can open a DOS window by selecting Start, Programs, Accessories, Command Prompt in Windows 2000 Professional; Start, Programs, MS-DOS Prompt in Windows 98, and so on.

To set the environment variables (if you haven't set them already), you can type the following at the DOS prompt. (Make the version numbers and paths match what you have installed, of course. )

C:>SET JAVA_HOME=C:jdk1.4 
C:>SET CATALINA_HOME=C:	omcatjakarta-tomcat-4.0.3
C:>SET PATH=%PATH%;C:jdk1.4in

Note the last statement, SET PATH=%PATH%;C:jdk1.4in, which is an easy way of adding C:jdk1.4in to the end of the path, without making any changes to the rest of the path.

In the Unix bash shell, this might look something like this in your .bashrc file (start a new shell to make the changes take effect):

JAVA_HOME=/jdk1.4 
export JAVA_HOME
SET CATALINA_HOME=/tomcat/jakarta-tomcat-4.0.3
export CATALINA_HOME
SET PATH=/usr/local/bin:/jdk1.4/bin
export PATH

In the Unix tcsh shell, it might look like this in your .tcshrc file (start a new shell to make the changes take effect):

setenv JAVA_HOME /jdk1.4 
setenv CATALINA_HOME /tomcat/jakarta-tomcat-4.0.3
setenv PATH /usr/local/bin:/jdk1.4/bin

After these environment variables are set, we're ready to start Tomcat. Again, this process is operating system-dependent; see the Tomcat document running.txt for more details. In Windows, go to the Tomcat bin directory (the bin directory is right under the directory that Tomcat unzips itself to, such as C: omcatjakarta-tomcat-4.0.3in if Tomcat was unzipped in C: omcat) and type startup:

C:	omcatjakarta-tomcat-4.0.3in>startup 

In Unix, that command might look like this:

/tomcat/jakarta-tomcat-4.0.3/bin/startup.sh 

That's it—now Tomcat is running. In Windows, you'll see a new DOS window open and a message similar to this appear:

Starting service Tomcat-Apache 
Apache Tomcat/4.0.3

Don't close this new window—that's where Tomcat is running. So how do we put Tomcat to work? You'll need a browser, such as Microsoft Internet Explorer (which you can pick up free at http://www.microsoft.com/windows/ie/default.asp), or Netscape Navigator (free at http://browsers.netscape.com/browsers/main.tmpl). Run the browser now and enter the URL http://localhost:8080/index.html, which should bring up the page you see in Figure 1.5.

Running the Tomcat server.

Figure 1.5. Running the Tomcat server.

Running the Tomcat server.

Tip

If Tomcat doesn't run for you, see the Troubleshooting section in the running.txt document that comes with Tomcat.

To stop Tomcat, you use the shutdown command. It looks something like this in Windows:

C:	omcatjakarta-tomcat-4.0.3in>shutdown 

and this in Unix:

/tomcat/jakarta-tomcat-4.0.3/bin/shutdown.sh 

That's our first step—getting Tomcat itself running. We've already made progress—now let's see whether we can display some of our own pages using this server.

Creating Web Documents

Throughout this book, we'll be creating our own documents—HTML documents, Java documents, JSP documents, and so on. That means that we'll need an editor that can save plain text files as part of our development environment.

You can use any editor or even word processor you like, such as WordPad in Windows, or vi (or even pico) in Unix. The main point here is that you must save the files you create in plain text format (not, for example, rich text format, which is the default for some versions of WordPad).

For example, you can see how to use WordPad to create a Web page named ch01_01.html (that is, Example 1 from Day 1) in Figure 1.6. When you save it, use the File, Save As menu item, and select the Text Document item in the Save As Type box of the Save As dialog box that appears. We'll see how to open this new HTML document in Tomcat later in this Day.

Creating a Web page.

Figure 1.6. Creating a Web page.

Tip

When we develop JSP-enabled pages, we'll give them the extension .jsp, like index.jsp. When you save a file with the extension .jsp in WordPad, it'll try to add the extension .txt because it doesn't know about the .jsp extension, giving you index.jsp.txt. To avoid this, put quotation marks around the name of the file when you save it—if you save the file as "index.jsp", you'll get the file index.jsp, not index.jsp.txt.

You can find the HTML page created in Figure 1.6 in Listing 1.1.

Example 1.1. A Simple Web Page (ch01_01.html)

<HTML>
    <HEAD>
        <TITLE>
            A Web Page
        </TITLE>
    </HEAD>

    <BODY>
        Hello there!
    </BODY>
</HTML>

Where can you save this document so you can view it with Tomcat? In this book, it'll be easiest to store the examples from Day 1 in a directory named ch01, the examples from Day 2 in ch02, and so on. Those directories are subdirectories of the webapps directory in the Tomcat directory structure:

jakarta-tomcat-4.0.3 
|__webapps
   |__ch01
   |__ch02
   |__ch03
        .
        .
        .

Create the ch01 directory now—for example, you can use the Windows Explorer in Windows for this purpose. We'll also need a WEB-INF directory under ch01, as well as classes and lib subdirectories (even though they're empty):

jakarta-tomcat-4.0.3 
|__webapps
   |__ch01
        |__WEB-INF
             |__classes
             |__lib
   |__ch02
        |__WEB-INF
             |__classes
             |__lib

Create this directory structure for ch01 now, and save the first example, ch01_01.html, in ch01 (that is, in jakarta-tomcat-4.0.3webappsch01 in Windows, or jakarta-tomcat-4.0.3/webapps/ch01 in Unix).

What's the URL of our new document? If we had put it into the webapps directory itself, it would be http://localhost:8080/ch01_01.html, but because we've placed it in the webappsch01 directory, its URL is http://localhost:8080/ch01/ch01_01.html. Enter that URL into the browser now, and you should see the result in Figure 1.7.

Viewing a new document in Tomcat.

Figure 1.7. Viewing a new document in Tomcat.

And that's it—now our development environment is complete. We've got Java, we've got a JSP server, we've got a browser, and we've got an editor with which to write our Web documents (alternatively, you could just download the source code for this book and use that). Not bad—we've made a great deal of progress.

Now we're ready to start working up to JSP itself. And to do that, it's a good idea to start by taking a look at the history of JSP.

A Brief History of JSP

To understand JSP, you have to understand where JSP came from. The Web started with HTML, and JSP's history starts there, too, so the first step is to take a look at HTML.

HTML

The pages into which we embed our JSP are Hypertext Markup Language (HTML) pages. (This book assumes you are already familiar with HTML.) HTML is a specification of the World Wide Web Consortium (W3C), and you can find the official home page for HTML at http://www.w3.org/MarkUp. The current version of HTML is 4.01, and you can find HTML's official specification at http://www.w3.org/TR/html4/.

Tip

If you want to brush up on HTML, there are many resources on the Internet. Here's a good one that lists all HTML tags and attributes by browser version and what they do: http://www.willcam.com/cmat/html/tags.html.

We've already seen our first HTML example, ch01_01.html; that example didn't do anything except support a title for the page and display the text Hello there!:

<HTML> 
    <HEAD>
        <TITLE>
            A Web Page
        </TITLE>
    </HEAD>

    <BODY>
        Hello there!
    </BODY>
</HTML>

That's okay as far as it goes, but it doesn't go very far. This page is very static, and Web developers wanted more as the Web became more and more popular. At first, client-side programming became popular, using script languages like JavaScript.

JavaScript

Despite the name, JavaScript is not related to Java. It actually began in 1995, when a Netscape Communications Corporation developer named Brendan Eich was given a new project to work on. The original idea was to give Netscape Navigator something extra; Eich took a look around and decided that what was needed was a scripting language that was fast and easy to use.

He called his creation LiveScript, but it was renamed JavaScript (although developed by Netscape, Sun had the trademarks on Java, so, interestingly, the name JavaScript is actually a trademark of Sun Microsystems). The new language was announced in a joint press conference with Netscape and Sun on December 4, 1995.

Unlike JSP, which is all about programming on the server, scripting languages like JavaScript are all about programming on the client side, in the browser. You enclose your JavaScript code in a <SCRIPT> element in an HTML page—for example, you can see how to use JavaScript to write the message Hello there! to a Web page while that page is being loaded in Listing 1.2.

Example 1.2. Using JavaScript (ch01_02.html)

<HTML>
    <HEAD>
        <TITLE>
            A Web Page
        </TITLE>
    </HEAD>

    <BODY>
        <SCRIPT LANGUAGE="JavaScript">
            <!—
                document.write("Hello there!")
            //—>
        </SCRIPT>
    </BODY>
</HTML>

This creates the same results as we saw for our HTML page in Figure 1.7, but now we're using JavaScript to write to the Web page. Client-side programming like this can be useful—you'll see that we can use JavaScript to pass data to JSP documents on the server—but it's extremely limited. As a result of security restrictions, for example, you can't access files from JavaScript. And because JavaScript has to be built into the browser, it has to be relatively small, and can't contain more than a small fraction of the power of a full programming language like Java. In fact, during all the time HTML and scripting languages like JavaScript were developing, so was Java.

Java

Java wasn't originally created for the Internet. The first version was actually begun in 1991 and written in 18 months at Sun Microsystems. In fact, it wasn't even called Java in those days; it was called Oak, and it was used internally at Sun.

The original idea for Oak was to create an operating system-independent language. Many programmers were confining themselves to programming for the IBM PC at that time, but the corporate environment can include all kinds of programming platforms, from the PC to huge mainframes, and the inspiration behind Oak was to create something that could be used on all those computers. (Actually, the original inspiration for Oak was not what you'd call especially glamorous—Sun wanted to create a language it could use in consumer electronics. )

Oak was renamed Java in 1995 when it was released for public consumption, and as you probably know, it's become very popular. Even though it's not targeted at the Internet, you can still use it to display the message Hello there!; Listing 1.3 details a small Java application named ch01_03.java that does just that.

Example 1.3. A Java Application (ch01_03.java)

public class ch01_03
{
    public static void main(String[] args)
    {
        System.out.println("Hello there!");
    }
}
A Java Application (ch01_03.java)

You compile ch01_03.java with the Java compiler, which is named javac. If you've set up your path to include the Java bin directory as we saw earlier, you can use the javac command at the command prompt; here's how that might look in Windows (make sure you're in the same directory as ch01_03.java):

C:>javac ch01_03.java 

This creates ch01_03.class, which you can run with the Java tool, simply named java. Here's how that would look in Windows:

C:>java ch01_03 

You can see the results in Figure 1.8, where our Java application is displaying the message Hello there!

Running a Java application.

Figure 1.8. Running a Java application.

JSP is based on Java, and a lot of this book is about learning to use Java. Java's a big part of the Internet now because Sun couldn't ignore the Internet, and Java's first attempt at working with the Internet was to introduce applets.

Java Applets

Java Applets

Here's an example called ch01_04.java. The Java applet you see in Listing 1.4 displays our Hello there! message.

Example 1.4. A Java Applet (ch01_04.java)

import java.applet.Applet;
import java.awt.*;

public class ch01_04 extends Applet
{
    public void paint(Graphics g)
    {
        g.drawString("Hello there!", 60, 100);
    }
}

To use this applet, you must first compile it with javac:

C:>javac ch01_04.java 

This creates ch01_04.class, which you can use in the HTML <APPLET> element. Here's a sample Web page that does this by setting aside an area 200×200 pixels in which to display the applet in Listing 1.5.

Example 1.5. Displaying an Applet (ch01_05.html)

<HTML>
    <HEAD>
        <TITLE>A Web Page</TITLE>
    </HEAD>

    <BODY>
        <APPLET CODE="ch01_04.class" WIDTH="200" HEIGHT="200"></APPLET>
    </BODY>
</HTML>

If you store the applet, ch01_04.class, and this Web page, ch01_05.html, in the webappsch01 directory, you can see the applet at work by navigating to http://localhost:8080/ch01/ch01_05.html, as you see in Figure 1.9.

Viewing an applet.

Figure 1.9. Viewing an applet.

Applets can display text like this, along with buttons, and so on, but like JavaScript, they're very limited. In fact, their time is mostly past as new client-side applications like Flash take over; the standard version of the newest Netscape Navigator no longer even supports applets by default.

But the Internet was still there to conquer. With the demise of applets, Java turned to the server side of things, and its first step in the server was to implement servlets.

Java Servlets

Java Servlets

Listing 1.6 shows a sample servlet, ch01_06.java, written in pure Java that will display our message.

Example 1.6. A Java Servlet (ch01_06.java)

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

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

        out.println("<HTML>");
        out.println("<HEAD>");
        out.println("<TITLE>");
        out.println("A Web Page");
        out.println("</TITLE>");
        out.println("</HEAD>");
        out.println("Hello there!");
        out.println("</BODY>");
        out.println("</HTML>");
    }
}

Compiling ch01_06.java into ch01_06.class takes an additional step we haven't seen before. Much of the support for servlets is not built into the core of Java, but is stored in a Java Archive (JAR) file named servlet.jar, which stores many specialized .class files internally.

Tomcat comes with servlet.jar (located in the jakarta-tomcat-4.0.3commonlib directory), and to access it, we have to set the CLASSPATH environment variable, which is specific to Java. As you might expect from the name, CLASSPATH indicates where Java can look for the .class files it needs when getting an application ready to run; we're using CLASSPATH because we need a number of servlet .class files stored in servlet.jar. Here's how you can set the CLASSPATH variable to include servlet.jar in Windows (change the path to servlet.jar as needed):

C:>SET CLASSPATH=C:	omcatjakarta-tomcat-4.0.3commonlibservlet.jar 

Now Java can find what it needs to compile servlets. You might have already set CLASSPATH to other locations, so if you just want to add servlet.jar to the CLASSPATH without affecting the rest of what's already in CLASSPATH, you can do the following in Windows (like other environment variables, you separate the locations and JAR filenames in the CLASSPATH variable with semicolons):

C:>set classpath=%CLASSPATH%;d:	omcatjakarta-tomcat-4.0.3commonlibservlet.jar 

You'll see more on using and setting CLASSPATH in Day 11, “Creating More Powerful JavaBeans.” Now that we have access to servlet.jar, navigate to the directory where our sample servlet ch01_06.java is located, and use javac to create ch01_06.class (this assumes javac is in your computer's path) :

C:>javac ch01_06.java 

Now transfer ch01_06.class to jakarta-tomcat-4.0.3webappsch01classes—note that we have to use the classes directory for Java classes like ch01_06.class.

And that's it—all we have to do now is navigate to http://localhost:8080/ch01/servlet/ch01_06. You can see the results in Figure 1.10-note that it looks just like our original HTML document, but this time, we've created this Web page on the server.

Using a servlet.

Figure 1.10. Using a servlet.

Tip

The servlet in http://localhost:8080/ch01/servlet/ch01_06 tells Tomcat that you're navigating to a servlet that it should run. We'll see how we can make some configuration changes that will allow us to omit that term in Day 13, “Creating More Powerful Servlets,” making this URL simply http://localhost:8080/ch01/ch01_06.

Servlets are very powerful, but they're not easy to program. As a result, they haven't become very popular. But Java and the Internet was a match meant to be—and the next step is JSP.

JSP

JSP is built on top of servlets, but JSP is much easier to program, and that's the whole point—that's why JSP has taken off.

JSP, a specification of Sun Microsystems, first appeared in 1998. The official versions, 1.0 and 1.1, both appeared in 1999, and both were very popular. The current version, 1.2, appeared in 2001, and is the most popular implementation yet; this is the version we'll be using in this book.

Internally, each JSP page is actually converted into a servlet by the server (we'll see exactly how that works in Day 13). In other words, this is really a book about servlets—but they're acting entirely behind the scenes.

Note

We'll also see how to create servlets in this book for some added power—see Days 13 and 14.

From our point of view, JSP pages are simply HTML pages with embedded Java in them. And by using JSP, we avoid all the hassle of creating full-blown Java applications—the server will do all that for us, taking our Java snippets of code and compiling them for us automatically.

It's clear that Sun had gotten the message about making things easy for the programmer when it came up with JSP, and we're the winners. Let's use JSP now to create the Web page we've already developed—you can see what it looks like in Listing 1.7, ch01_07.jsp (giving this document the extension .jsp means Tomcat will know that it is a JSP document and treat it accordingly):

Example 1.7. A JSP Page (ch01_07.jsp)

<HTML>
  <HEAD>
    <TITLE>A Web Page</TITLE>
  </HEAD>

  <BODY>
    <% out.println("Hello there!"); %>
  </BODY>
</HTML>
A JSP Page (ch01_07.jsp)
Our first JSP.

Figure 1.11. Our first JSP.

Tip

As you probably know, a Web server will send the document named index.html to the browser if that document is present in the directory you navigate to on the server, and you don't specify any other document. Similarly, index.jsp is the default for JSP documents—Tomcat will send that to the browser if you don't specify any specific document otherwise. If both index.jsp and index.html are present, the server chooses index.html as the default.

And that's it—now we've created and run our first JSP! Let's see what makes it tick.

Dissecting Our First JSP

The crucial line in our first JSP is this one, where it uses some Java code:

<HTML> 
  <HEAD>
    <TITLE>A Web Page</TITLE>
  </HEAD>

  <BODY>
    <% out.println("Hello there!"); %>
  </BODY>
</HTML>

The special JSP tags <% and %> create a scriptlet, and we can enclose Java code in the scriplet. In this way, we're able to embed Java directly into our page's HTML.

Dissecting Our First JSP
Dissecting Our First JSP

The out object is one of the objects already built into JSP for our use. Note that in our servlet example, we had to create this object ourselves, using techniques we'll look at later in this book:

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

        out.println("<HTML>");
        .
        .
        .

In JSP, the out object is already created for us in order to make things easier, and in this example, we're using the println method to write text to the Web page being sent back to the browser. That's all there is to it.

Overview of JSP Syntax

Now that we're actually working with JSP, the next step is to get an overview of JSP itself, which means getting an overview of the JSP syntax. After we've gotten the components of JSP syntax down, everything else will fit into that framework. There are four different types of elements you can use in JSP:

  • Scripting elements—. This is where your Java goes, as in the scriptlets we've already seen.

  • Comments—. Comments are text you add to annotate a JSP document—they're like notes to yourself or other programmers. They're ignored by the Web server, and are only for programmers to read.

  • Directives—. Directives are instructions specific to a particular page that let you set how the page is to be processed. For example, you can use a directive to indicate that you want the output of a page to be XML, not HTML.

  • Actions—. Actions let you perform some operation, such as including other pages in the current page, or including Java applets, or working with JavaBean components (which you'll see in Day 6). Unlike directives, actions are re-evaluated each time the page is accessed.

Let's take a look at these various types of JSP elements, starting with scripting elements.

Scripting Elements

There are three types of scripting elements in JSP:

  • Scriptlets—. Scriptlets can contain Java code. This is the most general of all the scripting elements.

  • Declarations—. Declares a variable or a method for use in your code.

  • Expressions—. Contains a Java expression that the server evaluates. The result of the expression is inserted into the Web page.

Scriptlets

The most general place for your Java code is in a scriptlet. Scriplets hold Java code fragments, and are enclosed with the tags <% and %>. We've already seen an example of a scriptlet in our first JSP, where we used the Java statement out.println("Hello there!"); to display text in a Web page:

<HTML> 
  <HEAD>
    <TITLE>A Web Page</TITLE>
  </HEAD>

  <BODY>
    <% out.println("Hello there!"); %>
  </BODY>
</HTML>

A scriptlet can hold any number of Java statements, declarations, or expressions, making scriptlets the most general of all the JSP scripting elements. Note that they must hold valid Java statements, so you can't include direct HTML in a scriptlet.

Scriptlets are what many JSP programmers think of when they think of JSP. Scriptlets are used to embed Java code in HTML documents, turning them into JSP documents. But besides scriptlets, you can also use declarations and expressions.

Declarations

Declarations
String msg = "Hello there!"; 

This declares a new variable named msg that holds the text Hello there!. In Java, you must declare variables before you use them, giving them a name. After you've named a variable, you can refer to it in your code using that name.

There's a special set of tags, <%! and %>, that you can use to declare variables in JSP (you can also declare variables in scriptlets, which is a more common thing to do). Here's an example: In this case, the code declares the variable msg:

<HTML> 
  <HEAD>
    <TITLE>A Web Page</TITLE>
  </HEAD>

  <BODY>
    <%! String msg = "Hello there!"; %>
  </BODY>
</HTML>

Now you can use this new variable in a scriptlet; for example, here's how you can display the text in msg in the Web page using the out.println method:

<HTML> 
  <HEAD>
    <TITLE>A Web Page</TITLE>
  </HEAD>

  <BODY>
    <%! String msg = "Hello there!"; %>
    <% out.println(msg); %>
  </BODY>
</HTML>

That's what the process looks like in overview; you'll get all the details on declaring and using variables in Day 2.

Expressions

Expressions are any Java code fragment that can be evaluated to yield a value. For example, the expression 2 + 2 yields a value of 4, the expression 44 - 10 yields 34, and so on. In JSP, you can surround a Java expression in the tags <%= and %>. The expression's value is inserted into the Web page as text by the server.

You can even use a variable as an expression—when such an expression is evaluated, it yields the value of the variable. For example, if we had stored our string Hello there! in a variable named msg, we can insert that string into the Web page simply by using the variable as an expression this way:

<HTML> 
  <HEAD>
    <TITLE>A Web Page</TITLE>
  </HEAD>

  <BODY>
    <%! String msg = "Hello there!"; %>
    <%= msg %>
  </BODY>
</HTML>

Expressions like this are similar to scriptlets, because you can place Java code in them, but they have to be able to result in a single value when they're evaluated.

Expressions like this are useful for shorter JSP pages, but note that you don't have to use them to insert text into a Web page—you can use methods like out.println in scriptlets instead.

Comments

You can use JSP comments to document what's going on in a JSP page; they act like notes to you or other programmers. Comments are purely for the benefit of the programmers that work on the page, because the server will strip them out before sending the page back to the browser. You enclose the text in a comment between the tags <%-- and --%>.

Here's an example; in this case, the code includes the comment Display the message now. to this JSP example:

<HTML> 
  <HEAD>
    <TITLE>A Web Page</TITLE>
  </HEAD>

  <BODY>
    <%-- Display the message now. --%>
    <% out.println("Hello there!"); %>
  </BODY>
</HTML>

This comment lets you and other programmers know what's going on in your JSP. You can add as many comments to a JSP as you like—they're entirely for the benefit of programmers, and will all be stripped out before the page is sent back to the browser.

Directives

JSP directives let you give directions to the server on how a page should be processed. There are three directives in JSP; we'll see them throughout the book, but here's an overview:

  • page—. This directive lets you configure an entire JSP page, such as whether its output is HTML or XML. You'll see more on this directive in Day 6.

  • include—. This directive lets you include another page or resource in a JSP page.

  • taglib—. This directive lets you use a set of custom JSP tags as defined in a tag library. More on taglibs is coming up in Day 9, “Using Custom JSP Tags,” and Day 10, Creating Custom Tags.”

The page directive is going to be a useful one for us as we work with Java. You can use this directive to configure the page you're working on. Like other directives, you use the special tags <%@ and %> with this directive; to create a page directive, you also include the keyword page like this: <%@ page ... %>.

taglib—
taglib—
<%@ page errorPage="error.jsp" language="java" 
    contentType="application/xml" import="java.sql.*" %>
<HTML>
    <HEAD>
        .
        .
        .

As you can already see, the page directive is going to give us a lot of programming power.

The include directive, which looks like <%@ page ... %>, lets you include another page in the current page. When you include a page at a particular point, that page's entire contents are simply inserted at that point.

The taglib directive (which looks like this: <%@ taglib ... %>) specifies a library of custom JSP tags (see Days 9 and 10) that you want to use in the current page. Tag libraries let you define your own JSP tags. We're going to see how to use this directive later, so we won't go into the details now.

Note

There are rumors that scriptlets are going to be phased out in JSP 2.0 and tag libraries will be used instead, so it's a good idea to make sure you know what's going on with tag libraries in Days 9 and 10.

Actions

Actions

There are two types of actions: custom and standard. Custom actions are actions you create yourself, and standard actions come built into JSP. Here are the standard actions in overview:

  • <jsp:forward>—. Forwards the browser request for a new Web page to an HTML file, JSP page, or servlet. In this way, you can delegate how your Web applications respond to the browser.

  • <jsp:include>—. Includes a file or Web component. Note that <jsp:include> is different than the include directive because it re-evaluates the included file every time the page is accessed, whereas the include directive does not.

  • <jsp:plugin>—. Lets you execute applets or JavaBeans with a plug-in. If the browser doesn't have the required plug-in module, it will display a dialog box asking you to download it. We'll see this one in Day 13.

  • <jsp:getProperty>, <jsp:setProperty>, and <jsp:useBean>—,. You use these actions with JavaBean components, as you'll see in Day 6.

We'll get all the details on these standard actions when we put them to work in the coming days. And that's it—that completes our overview of JSP syntax. Now we've got the foundation we'll need to move on to Day 2.

Online JSP Resources

Our first day of JSP work will end by taking a look at some of the resources available to you online. These resources are available for free, and they're there to augment your JSP arsenal. Let's start with JSP itself:

Here's a starter list of online JSP tutorials:

And here are some JSP tools available online (note that they're not necessarily free, however) :

Even though you can also find Java 1.4 documentation online or download it, here are a few good URLs to know:

There's also some Tomcat documentation available:

As you can see, there are a great number of online resources available on JSP—take a look!

Note

No JSP groups have appeared on Usenet (yet). Even so, the comp.lang.java groups (like comp.lang.java.help, comp.lang.java.databases, and so on) can offer a lot of Java help.

Summary

In our first day working with JSP, we've come far. We've gotten an idea of what JSP is good for, and how it's used. We've seen that JSP gives us the power of Java on the Web server, which is an incomparable asset.

We've also taken a look at where JSP came from, and how it developed. We've seen that as the Web has evolved, Java has been a part of the picture—first with applets, then servlets, and now JSP. Applets were nice, but limited; servlets are very powerful but complex. JSP gives us the best of both worlds: They're both very powerful (they're converted to servlets before they're run) and easy to write.

You've also installed the Tomcat server and gotten it running, and built the development environment (Java, Tomcat, browser, and an editor) you'll be using in the coming days.

We've also developed and run our first JSP. Instead of having to write everything in Java, we were able to simply insert the Java we wanted into an HTML page. That's the whole genius of JSP—you use an HTML backbone and just add the Java you need. As we've also seen, JSP offers a whole set of built-in objects, which means we can get away with even less Java because we don't have to create those objects ourselves.

We also took a look at the JSP syntax in overview here—some of which might not have made a great deal of sense yet. (But don't worry, that's why this is Day 1—it's all coming up in depth in the next days.)

And that's it—we've started our in-depth guided tour of JSP, and built the foundation we'll need in the coming days. Tomorrow, you'll see more details, such as how to work with data and operators in JSP, and you'll start writing some real code.

Q&A

Q1:

Do I have to use the Tomcat server? Aren't there any other JSP-enabled Web servers out there?

A1:

There sure are—take a look at http://klomp.org/gnujsp/ and http://www.caucho.com/ for some other JSP Web servers.

Q2:

How can I find out whether my Internet service provider supports JSP?

A2:

The best way is simply to ask your ISP's tech support. If they don't support JSP, suggest to them that they consider it—tell them that JSP is growing all the time and that other users will soon be asking. Many of the larger commercial Web servers offer some kind of JSP support these days.

Workshop

This workshop tests whether you understand all the concepts you learned today. It is very helpful to know and understand the answers before starting tomorrow's lesson. You can find the answers to the quiz questions in Appendix A.

Quiz

1:

Can you trace the development of JSP from HTML pages as you saw today? Knowing this history will help explain a great deal when it comes to working with servlets later in the book.

2:

What are the four different types of JSP elements discussed today?

3:

How many different types of scripting elements are there in JSP? What are they?

4:

What are the tags you use for the three different types of JSP scripting elements?

5:

What are the three JSP directive types?

Exercises

1:

Take a look at the JSP resources given in the topic “Online JSP Resources” and either bookmark or download your favorites. Compiling a list of ready resources like that can be a big help in your JSP development. You might even want to try a few of the JSP tutorials.

2:

Use the JSP expression <%= new java.util.Date() %> in a welcome message in a new JSP page. This expression will insert the current date and time, permitting you to customize your welcome page.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.98.148