Table of Contents | Previous | Next | Index


Chapter 11
Quick Start with the Sample Applications

This chapter describes the sample server-side JavaScript applications that ship with Netscape web servers. It introduces using server-side JavaScript by working with two of the simpler sample applications.

This chapter contains the following sections:

When you install a Netscape web server, several sample JavaScript applications are also installed. For an introduction to the full capabilities of JavaScript applications, run them and browse their source code. You can also modify these applications as you learn about JavaScript's capabilities. Both the source files and the application executables for these applications are installed in the $NSHOME\js\samples directory, where $NSHOME is the directory in which you installed the server. The following table lists the sample applications.

Table 11.1 Sample JavaScript applications  
Basic concepts

world

"Hello World" application.

hangman

The word-guessing game.

cipher

Word game that has the player guess a cipher.

LiveWire Database Service1

dbadmin

Simple interactive SQL access using LiveWire.

If you have restricted access to the Application Manager, this sample is also protected with the server administrator's user name and password.

videoapp

Complete video store application using a relational database of videos.

oldvideo

An alternative version of the video store application.

LiveConnect2

bugbase

Simple bug entry sample using LiveConnect.

flexi

Accessing remote services running on an IIOP-enabled ORB through LiveConnect.

This sample is not automatically added to the list of applications in the Application Manager; you must add it before you can use it.

bank

Another IIOP sample.

This sample is not automatically added to the list of applications in the Application Manager; you must add it before you can use it.

Other sample applications

sendmail

Demonstrates the ability to send email messages from your JavaScript application.

viewer

Allows you to view files on the server, using JavaScript's File class.

For security reasons this application is not automatically installed with the Netscape server. If you install it, be sure to restrict access. Otherwise, unauthorized persons may be able to read and write files on your server. For information on restricting access to an application, see the administrator's guide for your web server.

jsaccall

Sample using external native libraries and providing access to CGI variables.

1 These sample applications work only if you have a supported database server installed on your network and have configured the client software correctly. For more information, see Chapter 17, "Configuring Your Database." These applications are discussed in Chapter 20, "Videoapp and Oldvideo Sample Applications." Before using videoapp or oldvideo, follow the instructions to set them up found in that chapter.
2 These applications are discussed in Chapter 22, "Accessing CORBA Services."

NOTE: In addition to sample applications, the $NSHOME\js\samples directory also contains an application named metadata. This application is used by Visual JavaScript. While you are welcome to browse its source code, do not modify the executable.
For more advanced sample applications, you can visit the Netscape AppFoundry Online home page at http://home.netscape.com/one_stop/intranet_apps/index.html.

The rest of this chapter walks you through two of the simpler samples, giving you a feel for working with JavaScript applications. For now, don't worry about any of the details. This discussion is intended only to give you a rough idea of the capabilities of JavaScript applications. Details are discussed in later chapters.

Chapter 20, "Videoapp and Oldvideo Sample Applications," discusses the videoapp application in detail. You should read that chapter when you're ready to start working with the LiveWire Database Service.


Hello World

In this section, you run Hello World, the simplest sample application, and get an introduction to

To get started with the sample applications, you need to access the JavaScript Application Manager. You can do so by loading the following URL in Navigator:

http://server.domain/appmgr
In this and other URLs throughout this manual, server represents the name of the server on which you run your application, such as research1 or www, and domain represents your Internet domain name, such as netscape.com or uiuc.edu. If your server has Secure Sockets Layer (SSL) enabled, use https instead of http in the URL.

In the Application Manager, select world in the left frame and click the Run button. Alternatively, you can enter the application URL in the Navigator Location field:

http://server.domain/world
In response, the Application Manager displays the page shown in Figure 11.1.

Figure 11.1   Hello World

For more information on the Application Manager, see Chapter 3, "How to Develop Server Applications."

What Hello World Does

This application illustrates two important capabilities: maintaining a distinct client state for multiple clients and maintaining a persistent application state. Specifically, it performs these functions:

The first time a user accesses this page, the values for both names are not defined. The number of times the user has previously accessed the page is 0; the total number of times it has been accessed is 0.

Type your name and click Enter. The page now shows the name you entered following the text "This time you are." Both numbers of accesses have been incremented. This action illustrates simple form processing. Enter another name and click Enter. The page now shows the new name following the text "This time you are" and the previous name following the text "Last time you were." Again, both numbers of accesses have been incremented.

If you access the application from another instance of the Navigator (or from another computer), the page displays the total number of accesses and the number of accesses by each instance of Navigator, not just by that particular instance.

Looking at the Source Script

Now take a look at the JavaScript source script for this application. Using your favorite text editor, open the file $NSHOME\js\samples\world\hello.html, where $NSHOME is the directory in which you installed the Netscape server. The file begins with some typical HTML:

<html>
<head>
<title> Hello World </title>
</head>
<body>
<h1> Hello World </h1>
<p>Your IP address is <server>write(request.ip);</server>
The SERVER tags in the bottom line enclose JavaScript code that is executed on the server. In this case, the statement write(request.ip) displays the ip property of the request object (the IP address of the client accessing the page). The write function is very important in server-side JavaScript applications, because you use it to add the values of JavaScript expressions to the HTML page sent to the client.

The request object is part of the JavaScript Session Management Service. For a full description of it, see Chapter 13, "Session Management Service." The write function is one of the functions JavaScript defines that is not associated with a specific object. For information on the write function, see "Constructing the HTML Page" on page 216.

Then come some statements you shouldn't worry about quite yet. These are the next statements of interest:

<server> client.oldname = request.newname;</server>
This statement assigns the value of the newname property of the request object to the oldname property of the client object. The client object is also part of the JavaScript Session Management Service. For a full description of it, see Chapter 13, "Session Management Service." For now, just realize that client can hold information about an application specific to a particular browser running that application.

The value of request.newname is set when a user enters a value in the form. Later in the file you'll find these form statements:

<form method="post" action="hello.html">
<input type="text" name="newname" size="20">
The value of the form's ACTION attribute is hello.html (the current filename). This means that when the user submits the form by clicking Enter or pressing the Enter key, Navigator reloads the current page. In general, ACTION can be any page in a JavaScript application.

The value of the NAME attribute of the text field is newname. When the page is submitted, this statement assigns whatever the user has entered in the text field to the newname property of the request object, referred to in JavaScript as request.newname. The values of form elements always correspond to properties of the request object. Properties of the request object last only for a single client request.

A few lines down, there is another SERVER tag, indicating that the following lines are server-side JavaScript statements. Here is the first group of statements:

if (client.number == null)
   client.number = 0
else
   client.number = 1 + parseInt (client.number, 10)
This conditional statement checks whether the number property of the client object has been initialized. If not, then the code initializes it to 0; otherwise, it increments number by 1 using the JavaScript parseInt function, which converts the string value to a number. Because the predefined client object converts all property values to strings, you must use parseInt or parseFloat to convert these values to numbers.

Because number is a property of the client object, it is distinct for each different client that accesses the application. This value indicates the number of times "you have been here."

To track the total number of accesses, you use the project object, because it is shared by all clients accessing the application. Properties of the project object persist until the application is stopped. The next group of statements tracks accesses:

project.lock() 
if (project.number == null)
   project.number = 0
else
   project.number = 1 + project.number
project.unlock()
The first statement uses the lock method of the project object. This gives the client temporary exclusive access to the project object. Another if statement checks whether project.number has been defined. If not, then the code initializes it to 0; otherwise, the code increments it by 1. Finally, the unlock method releases the project object so that other clients can access it.

The final statements in the file display the values of client.number and project.number.

<p>You have been here <server>write(client.number);</server> times.
<br>This page has been accessed <server>write(project.number);
</server> times.

Modifying Hello World

In this section, you modify, recompile, and restart this sample application. To edit the source file, you must first determine where it is. In case you don't remember, the Application Manager shows the directory path of the application executable (the file that has the suffix .web). The source file, hello.html, should be in the same directory. Edit the file with your favorite text editor. The HTML file starts with these statements:

<html>
<head> <title> Hello World </title> </head>
<body>
<h1> Hello World </h1>
<p>Your IP address is <server>write(request.ip);</server>
<server>
write ("<P>Last time you were " + client.oldname + ".");
</server>
<p>This time you are <server>write(request.newname);</server>
<server>client.oldname = request.newname; </server>
Add a line that displays the type of browser the user has:

<p>You are using <server>write(request.agent)</server>
If you want, you can also personalize the heading of the page; for example, you could make the title "Fred's Hello World."

When you've finished modifying the file, run the JavaScript application compiler. At the command prompt, change to the directory containing the source code. Type this line at the command prompt to compile the application:

jsac -v -o hello.web hello.html
Alternatively, from that directory you can run the build script (for Unix) or build.bat script (for NT). In either case, the compiler starts and displays messages. The final message should be "Compiled and linked successfully."

Publish the application's files on your development server. To restart, access the Application Manager, select Hello World, then choose Restart. This loads the newly compiled version of the application into the server. You can then run the application by choosing Run. A window opens with Hello World. You see the changes you made to the application.


Hangman

In this section, you run and modify the Hangman sample application and get an introduction to:

Hangman is a classic word game in which the players try to guess a secret word. The unknown letters in the word are displayed on the screen as asterisks; the asterisks are replaced as a player guesses the correct letters. When the guess is incorrect, one more part of the hanged man is drawn. The game also shows the incorrect letters you have guessed.

When the hanged man is completely drawn, the player loses the game. The player wins by guessing all the letters in the word before the man is hanged. In this simple version of the game, there are only three possible secret words. After a game, the player can choose to play again (and use the next secret word) or quit.

Run the Hangman application by selecting Hangman in the Application Manager and clicking Run. Alternatively, you can load the application URL in Navigator:

http://server.domain/hangman
In response, the Application Manager displays the page shown in the following figure.

Figure 11.2   Hangman

Play the game to get a feel for it.

Looking at the Source Files

The following table shows the sources files for Hangman.

Table 11.2 Hangman source files  
hangman.html

The main page for the application. This page is installed as the default page for Hangman in the Application Manager. It is displayed if the user enters just the hangman URL, with no specific page.

hangman.js

A file containing only server-side JavaScript functions used in hangman.html.

youwon.html
youlost.html
thanks.html

The pages displayed when a player wins, loses, and finishes playing the game, respectively.

images directory

Contains the Hangman images, hang0.gif, hang1.gif, and so on.

rules.html

Contains text explaining the game. This file is not compiled with the application; it is included as an example of an uncompiled application page that is part of the same site.

Most of the application logic is in hangman.html. The basic logic is simple:

  1. For a new game, initialize the secret word and other variables.
  2. If the player correctly guessed a letter, substitute it into the answer.
  3. If the guess was wrong, increment the number of wrong (missed) guesses.
  4. Check whether the user has won or lost.
  5. Draw the current version of the hanged man, using a GIF image based on the number of wrong guesses.
The body of the HTML file hangman.html starts with some JavaScript code inside a SERVER tag. First comes code to initialize a new game:

if (client.gameno == null) {
   client.gameno = 1;
   client.newgame = "true";
}
if (client.newgame == "true") {
   if (client.gameno % 3 == 1)
         client.word = "LIVEWIRE";
   if (client.gameno % 3 == 2)
      client.word = "NETSCAPE";
   if (client.gameno % 3 == 0)
         client.word = "JAVASCRIPT";
   client.answer = InitAnswer(client.word);
   client.used = "";
   client.num_misses = 0;
}
client.newgame = "false";
This code makes extensive use of the client object to store information about this client playing the game. Because there is no state that needs to be saved between uses of this same application by different clients, the code doesn't use the project or server objects.

The first statement determines whether the player has played before, by checking if client.gameno exists; if not, the code initializes it to 1 and sets client.newgame to true. Then, some simple logic assigns the "secret word" to client.word; there are just three secret words that players cycle through as they play the game. The client.gameno property keeps track of how many times a particular player has played. The final part of initialization uses InitAnswer, a function defined in hangman.js, to initialize client.answer to a string of asterisks.

Then comes a block of statements to process the player's guess:

if (request.guess != null) {
   request.guess = request.guess.toUpperCase().substring(0,1);
   client.used = client.used + request.guess + " ";
   request.old_answer = client.answer;
   client.answer = Substitute (request.guess, client.word,
      client.answer);
   if (request.old_answer == client.answer)
      client.num_misses = parseInt(client.num_misses) + 1;
}
The if statement determines whether the player has made a guess (entered a letter in the form field). If so, the code calls Substitute (another function defined in hangman.js) to substitute the guessed letter into client.answer. This makes client.answer the answer so far (for example, "N*T**AP*").

The second if statement checks whether client.answer has changed since the last guess; if not, then the code increments client.num_misses to keep track of the number of incorrect guesses. You must always use parseInt to work with integer property values of the predefined client object.

As shown in the following code, the final if statement in the JavaScript code checks whether the player has won or lost, and redirects the client accordingly. The redirect function opens the specified HTML file and passes control to it.

if (client.answer == client.word)
   redirect(addClient("youwon.html"));
else if (client.num_misses > 6)
   redirect(addClient("youlost.html"));
This is the end of the initial SERVER tag. HTML, augmented with more JavaScript expressions, begins. The hanged man is drawn by using a backquoted JavaScript expression inside an HTML IMG tag:

<IMG SRC=`"images\hang" + client.num_misses + ".gif"`>
The entire expression between the two backquotes (`) is a JavaScript string. It consists of the string literal "images\hang" concatenated with the value of client.num_misses (which represents an integer but is stored as a string), concatenated with the string literal ".gif". There are six GIF files containing the hanged man in different stages of completion: image0.gif, image1.gif, and so on. The backquoted JavaScript generates HTML of the form:

<IMG SRC="images\hang0.gif">
These lines follow:

<PRE><SERVER>write(client.answer)</SERVER></PRE>
You have used the following letters so far:
<SERVER>write(client.used)</SERVER>
They display the value of client.answer (the word containing all the correctly guessed letters) and all the guessed letters.

The remainder of the file consists of standard HTML. One important thing to notice is that the ACTION attribute of the FORM tag specifies hangman.html as the URL to which to submit the form. That means when you submit the form, the page is reloaded with the specified form values.

Examine hangman.js, an example of a server-side JavaScript-only source file. It defines two functions, InitAnswer and Substitute, used in the application. Notice that you do not use SERVER tags in a JavaScript-only file.

Debugging Hangman

You can experiment more with JavaScript to get a feel for developing applications. One important task to master is debugging. In the Application Manager, select Hangman and choose Debug. The Application Manager opens a window with the application in one frame and debugging information in a narrow frame along the left side of the window, as shown in Figure 11.3.

Figure 11.3   Debugging Hangman

Notice that the URL is

http://server.domain/appmgr/debug.html?name=hangman
You can add a bookmark for this URL as a convenience while you work on Hangman. Then you don't have to go through the Application Manager.

Try adding a function to Hangman verifying that a player's guess is a letter (not a number or punctuation mark). You can use the function InitAnswer defined in hangman.js as a starting point. After compiling and restarting the application, use your bookmark to run the application in debug mode.


Table of Contents | Previous | Next | Index

Last Updated: 11/12/98 15:29:24

Copyright (c) 1998 Netscape Communications Corporation