You are on page 1of 13

Developing a Web Application

April 2006 [Revision number: V2.1-1]


Copyright 2006 Sun Microsystems, Inc.

In this tutorial, you use the Sun Java Studio Creator integrated development environment (IDE) to create and run
a simple web application, Hello Web. The example application asks you to input a name and then displays a
message that uses that name. At first, you implement this page with an input field. Then you replace the input
field with a drop-down list from which the user can choose a name. The drop-down list is populated with names
from a database table.

Contents

- Create a Project
- Design the Page
- Add Some Behavior
- Run the Application
- Replace the Text Field With a Drop Down List
- Bind the Drop Down List to the Database Table
- Add Some Behavior
- Run the Application
- (Optional) Monitor the Application
- Doing More

Before you use this tutorial, you must have the Java Studio Creator IDE installed on your system. Familiarize
yourself with the basic parts of the IDE. Getting Started With Java Studio Creator is a useful introduction to the
Sun Java Studio Creator IDE.

Create a Project

1. From the main menu, choose File > New Project.

2. In the New Project Wizard, select Web from the Categories list and select Web Application from the
Projects list.

3. Click Next.

4. Name the project HelloWeb and click Finish.

Your project appears with the initial page (Page1) open in the Visual Designer.

Design the Page

To begin, you design a page like the one shown in the following figure.

1
Figure 1: Page1 Design

1. Type Hello Web in the Title property's text box in the Properties window as shown in the following
figure.

The Title property's value appears in the browser's title bar when the browser accesses this page.

Figure 2: Page Properties in the


Properties Window

TIP: You access a component's properties in the Properties window by selecting the component in either
the Visual Designer or the Outline window. You access a page's property sheet by clicking on a blank spot
on the page.

2. If the Basic node in the Palette window is not expanded, expand it now.

All the components that you use in this example are in the Basic section of the Palette.

If the Palette is not visible, choose View > Palette to display it.

3. Drag a Label component from the Basic section of the Palette to the left side of the page in the Visual
Designer, type Name:, and press Enter.

Note that the component snaps to the grid on the page. Also note that the value of the text property in the
Properties window is Name:.

TIP: You can switch the component to edit mode by right-clicking the component and choosing Edit Text
from the pop-up menu.

4. Drag a Text Field component from the Basic section of the Palette onto the Visual Designer, type Enter
Your Name, and press Enter.

5. In the Properties window, change the id property of the Text Field from textField1 to nameField.

6. Ctrl-Shift-Drag from the Label component to the Text Field component.

2
7. Select the Label component and note that the for property is now set to nameField.

8. Drag a Button component to the right of the Text Field component, type Say Hello, and press Enter.

9. In the Properties window, change the Button component's id property from button1 to helloButton.

10. Drag a Static Text component to a spot below the Label component.

11. Change the Static Text component's id property from staticText1 to helloText.

12. In the Editing toolbar, click JSP to switch to the JavaServer Pages (JSP) Source Editor.

Scan through the code and note how the changes that you made in the Properties window are saved. When
a page is first displayed in the browser, the page appears exactly as indicated by the tags in the JSP page. If
your page bean has code that changes the property values, such changes appear only on requests where the
page is submitted and subsequently redisplayed.

Add Some Behavior

In this section, you add code to make the page redisplay with the message Hello entered-name. You do this
by adding an event handler that the application calls whenever the button is clicked. This event handler sets the
Static Text component's text property to a "hello" message and then causes the page to be redisplayed so that the
text appears.

1. In the Editing toolbar, click Design to switch to the Visual Designer.

2. Double-click the Button component.

The Editing Area switches to the Java Editor and shows the page bean for Page1. The button's event
handler, helloButton_action, has been added to the page bean.

3. (Optional) In the main menu, choose View > To Do.

The To Do window appears, as shown in the following figure. Notice how this window lists all the lines in
the current program that have //TODO comments. This window is a helpful way to remind yourself of the
changes that you need to make.

Figure 3: To Do Window

4. Replace the body of the helloButton_action method with the following lines of code. Then press
Ctrl-Shift-F to reformat the code.

3
Code Sample 1: helloButton_action() Code
String name = (String)nameField.getText();
helloText.setText("Hello, " + name + "!");
return null;

The first line in bold gets the value of the text property for the nameField Text Field component using
the getText method. That value is an object of type Object, which needs to be a string, so it is cast to a
String object. Then the object is assigned to the name variable.
The second line in bold sets the value of the text property for the helloText Static Text component.
This value contains the name that the user entered into the nameField Text Field component. For
example, if the user enters Fred, this line of code sets the Static Text component's text property to
Hello, Fred!

Run the Application

1. Ensure that your Java code does not contain any errors in the Java Editor. Errors are indicated by red
underlines or red boxes along the left side of the code.

Your project will not build if there are errors in the code.

TIP: Hold the cursor over the red box on the left side of the code to see a description of the error.

2. Click the Run Main Project button .

The IDE saves your files and builds your project. The Build Output window appears at the bottom of the
screen and displays relevant status messages. Once your application is built and deployed, the IDE launches
your web browser (if it is not already running), and your web application appears.

TIP: If your project does not build, choose Help > Help Contents from the main menu and expand the
Troubleshooting node for helpful tips.

3. Type your name and click Say Hello.

The browser submits the form to the web server, which calls your web application. The application
executes the button action method, updates the page elements, rerenders the same page with the changed
data, and sends the page back to the web browser. The following figure is the result if the name submitted
is Gus Townsend.

Figure 4: Hello Web, With Result.

4
Replace the Text Field With a Drop Down List

The remainder of this tutorial shows how to use a Drop Down List component instead of a Text Field to get user
input, as shown in the following figure. This Drop Down List component gets its list of choices from the bundled
PERSON database table.

Figure 5: Hello Web, Final Version

1. In the Editing toolbar, click Design to switch to the Visual Designer.

2. In the Visual Designer, select the nameField Text Field component and click the Delete button (the
button with the trash can icon) in the main toolbar.

3. Drag a Drop Down List component from the Basic section of the Palette onto your page in the Visual
Designer. Move the component into the area where the Text Field component was.

Notice, as shown in the following figure, that the Outline window shows a dropDown1 component and a
dropDown1DefaultOptions object. The Drop Down List component's items property identifies the object
that contains the choices in the list. When you add a Drop Down List component to the page, the IDE
creates a Default Options object (dropDown1DefaultOptions) and sets this object as the value of the
Drop Down List component's items property. Only the Drop Down List component is visible in the
Visual Designer. The Default Options object merely supplies the choices that appear in the list. Later in this
tutorial, you modify the Drop Down List component to obtain its choices from a different source.

Figure 6: Components in the Outline Window

5
4. In the Properties window, change the component's id to nameDropDown.

5. Ctrl-Shift-Drag from the Label component to the Drop Down List component.

6. Select the Label component and note that the for property is now nameDropDown.

Bind the Drop Down List to the Database Table

The Servers window, which appears on the left side of the IDE workspace, includes a Data Sources node. The
Data Sources node shows all the databases, web services, and EJB data sources that are added to the IDE.

The Java Studio Creator development environment comes with an embedded DBMS, which is prepopulated with a
sample Travel schema. The Travel schema appears under the Data Sources node. You use the PERSON table from
the Travel schema to supply the choices for the Drop Down List component.

1. In the Servers window, expand the Travel data source and expand Tables.

Under Tables, you see nodes for each database table in the data source, such as CARRENTAL,
NORELATION, PERSON, TRIP, and TRIPTYPE. The following figure shows the Servers window with
the Tables node expanded.

Note: If a red X appears on the Travel icon and an error appears when you try to expand it, the database
server is not running. To start the database server, right-click the Bundled Database Server node in the
Server Navigator and choose Start Bundled Database from the contextual menu. Then right-click the Travel
data source and choose Refresh.

6 Figure 7: Servers Window


2. Drag PERSON from the Servers window and drop it on the Drop Down List component.

The display on the list changes from item1 to abc, indicating that the list is displaying bound data and
that the data being displayed is of the type String.

The IDE adds a nonvisual personDataProvider component for the database table. The personDataProvider
component appears in the Outline window. The IDE also adds a personRowSet property to
SessionBean1.

3. Right-click the Drop Down List and choose Bind to Data from the contextual menu. The Bind to Data
dialog box appears, as shown in the following figure.

Figure 8: Binding Data to the Drop Down List

When you bind data to a Drop Down List component, you must specify what to display in the list (the
Display Field) and you must specify what values to use in the underlying program (the Value Field).
Typically, you want to display some meaningful value from the database table, such as a person's name, but
you want to use a unique identifier in the underlying program, such as the person's ID. With this
application, however, you want to bind both the Value field and the Display field to the same database
column, the PERSON.NAME column, as described in the next two steps.

4. Set the Value field in the dialog box to PERSON.NAMEÌ..

5. Leave the Display field set to PERSON.NAME.

6. Click OK.

7. Drag and drop a Message Group component onto an out-of-the-way spot on the page, such as under the
Static Text component.

Adding a Message Group component, which displays runtime errors among other types of messages, is

7
useful for diagnosing programming errors.

Add Some Behavior

1. In the Visual Designer, double-click the Button component.

The Editing Area switches to the Java Editor and moves to the helloButton_action method.

2. Replace the body of the helloButton_action method with the following code.

Code Sample 2: helloButton_action Replacement Code


String name = (String)nameDropDown.getSelected();
String splitnames[] = name.split(",");
helloText.setText("Hello, " + splitnames[1] + "!");
return null;

The first line uses the getSelected method to get the current value of the Drop Down List, which is the
currently selected name in the list.

Because data is stored in the database as lastname, firstname, the string must be modified before it is
displayed. Otherwise, the application will print "Hello, lastname, firstname!" The second line uses the
split method to split the string into an array, using the comma as a delimiter. The first item in the array
(at position 0) contains the last name and position 1 contains the first name.

In the third line, the text property for the Static Text component is set to a value that includes the first
name.

Note: This method assumes that all values in this table are in the format lastname, firstname. It does not
robustly handle strings that do not follow this format. How would you change the method to handle
deviations?

3. Add the following code to the prerender method. This code sets the first item in the list as the default
selection.

Code Sample 3: prerender Method Code


// If no selection, set default selection
if (nameDropDown.getSelected() == null) {
personDataProvider.cursorFirst();
nameDropDown.setSelected
((String)personDataProvider.getValue("person.name"));
}

Run the Application

1. Click the Run Main Project button.

The IDE builds and deploys the application and displays the page in the web browser.

8
2. Select a name from the list and click Say Hello.

The browser sends the Drop Down List component's selected value to the server and the server executes the
button's helloButton_action method.

(Optional) Monitor the Application

You use the HTTP Monitor to monitor the client-server communication and to replay HTTP requests. The ability
to replay requests can be helpful when your page has several input fields and you want to re-create the HTTP
request without having to fill in all the fields.

The first four steps assume that you have not already enabled the HTTP Monitor. If you have already enabled the
HTTP Monitor, you may skip to Step 5.

1. In the Servers window, right-click the Deployment Server and choose Start/Stop Server from the contextual
menu.

2. In the Server Status dialog box, click Stop Server.

3. In the Properties window for the Deployment Server, select true from the drop-down menu for the
Enable HTTP Monitor property.

4. Restart the server by right-clicking the Deployment Server, choosing Start/Stop Server from the contextual
menu, and clicking Start Server.

5. Click the Run Main Project button.

The HTTP Monitor window appears. Notice the list of request records under Current Records, as shown in
the following figure.

9
Figure 9: HTTP Monitor

6. In the web browser, click Say Hello.

Notice the new GET and POST records that appear in the Current Records list.

7. Right-click the POST record and choose Edit and Replay from the contextual menu.

8. In the Edit and Replay dialog box, change the text for the form1:nameDropDown entry to Chen,
Larry, as shown in the following figure, and press Enter.

You must press Enter to save your changes.

Figure 10: Edit and Replay Dialog Box

10
9. Click Send HTTP Request.

The web browser redisplays the page and the message now says "Hello Larry!"

You can save any record for replaying at a later time.

Doing More

Try It. A Listbox component is similar to a Drop Down List component. Try replacing the Drop Down List
component with a Listbox component. In this application, the Listbox component's multiple property must not
be checked, because only one item can be selected at a time. Remember to bind the listbox to the database table
and to change the helloButton_action method to get the listbox's selected value.

Try It. Using steps that are similar to the ones that you have learned in this tutorial, try building a web application
that has a Drop Down List component that shows all the DESCRIPTION values in the TRIPTYPE table. When a
user clicks a Show Type Id button, have the page display the trip type's TRIPTYPEID. To do this, you must bind
the Drop Down List component's Display field to TRIPTYPE.DESCRIPTION and the component's Value field to
TRIPTYPE.TRIPTYPEID.

Summary

The typical workflow for designing a web page from the IDE consists of the following steps:

1. Create the page.


2. Place components, such as the Text Field component and the Button component, onto the page.
3. Edit the components' properties to change their appearance and behavior.
4. Bind the components to their data sources and data holders, when appropriate.
5. Edit the Java source to control server-side behavior, such as event handling.
6. Build and test your application.

See Also:

● Using Listbox Components for more information about list components.


● Using Databound Components to Access Databases for more information about using databases in your
web application.

More Developer Resources:

For more tutorials, articles, tips, forums, updates, and expert advice for developers, visit the Java Studio Creator
developer resources on the Sun Developer Network (SDN) at http://developers.sun.com/jscreator/.

This page was last modified: April 27, 2006

11
Sun and Third-party Trademarked Terminology

The following Sun trademarked terms might be used in the Sun Java(tm) Studio Creator tutorials:

● Sun Java Studio Creator integrated development environment (IDE)


● Sun Java System Application Server version number (Application Server)
● Java Platform, Standard Edition technology (Java SE(tm) platform)
● JavaServer(tm) Faces technology
● JavaServer Pages(tm) technology (JSP(tm) technology)
● Sun Java System Web Server version number (Web Server)
● Java Database Connectivity software (JDBC software)
● Enterprise JavaBeans(tm) specification (EJB(tm) specification)
● Solaris(tm) Operating System software (Solaris OS software)

The following third-party trademarked terms might be used in the Sun Java Studio Creator tutorials:

● UNIX(R) software
● SPARC(R) processor

Copyright © 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, U.S.A. All rights
reserved.

Sun Microsystems, Inc. has intellectual property rights relating to technology embodied in the product that is
described in this document. In particular, and without limitation, these intellectual property rights may include one or
more of the U.S. patents listed at http://www.sun.com/patents and one or more additional patents or pending patent
applications in the U.S. and in other countries.

U.S. Government Rights - Commercial software.

Government users are subject to the Sun Microsystems, Inc. standard license agreement and applicable provisions of
the FAR and its supplements. Use is subject to license terms. Sun, Sun Microsystems, the Sun logo, Java and the Java
Coffee Cup logo are trademarks or registered trademarks of Sun Microsystems, Inc. in the U.S. and other countries.
This product is covered and controlled by U.S. Export Control laws and may be subject to the export or import laws in
other countries. Nuclear, missile, chemical biological weapons or nuclear maritime end uses or end users, whether
direct or indirect, are strictly prohibited. Export or reexport to countries subject to U.S. embargo or to entities
identified on U.S. export exclusion lists, including, but not limited to, the denied persons and specially designated
nationals lists is strictly prohibited.

Note: Sun is not responsible for the availability of third-party web sites mentioned in this document and does not
endorse and is not responsible or liable for any content, advertising, products, or other materials on or available from
such sites or resources. Sun will not be responsible or liable for any damage or loss caused or alleged to be caused by
or in connection with use of or reliance on any such content, goods, or services available on or through any such sites
or resources.

Copyright © 2006 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, California 95054, États-Unis. Tous
droits réservés.

Sun Microsystems, Inc. détient les droits de propriété intellectuels relatifs à la technologie incorporée dans le produit
qui est décrit dans ce document. En particulier, et ce sans limitation, ces droits de propriété intellectuelle peuvent
inclure un ou plus des brevets américains listés à l'adresse http://www.sun.com/patents et un ou les brevets
supplémentaires ou les applications de brevet en attente aux États-Unis et dans les autres pays. L'utilisation est
soumise aux termes de la Licence. Sun, Sun Microsystems, le logo Sun, Java et le logo Java Coffee Cup sont des
marques de fabrique ou des marques déposées de Sun Microsystems, Inc. aux États-Unis et dans d'autres pays.Ce
produit est soumis à la législation américaine en matière de contrôle des exportations et peut être soumis à la

12
règlementation en vigueur dans d'autres pays dans le domaine des exportations et importations. Les utilisations, ou
utilisateurs finaux, pour des armes nucléaires,des missiles, des armes biologiques et chimiques ou du nucléaire
maritime, directement ou indirectement, sont strictement interdites. Les exportations ou réexportations vers les pays
sous embargo américain, ou vers des entités figurant sur les listes d'exclusion d'exportation américaines, y compris,
mais de manière non exhaustive, la liste de personnes qui font objet d'un ordre de ne pas participer, d'une façon directe
ou indirecte, aux exportations des produits ou des services qui sont régis par la législation américaine en matière de
contrôle des exportations et la liste de ressortissants spécifiquement désignés, sont rigoureusement interdites.

Sun Microsystems n'est pas responsable de la disponibilité de tiers emplacements d'enchaînement mentionnés dans ce
document et n'approuve pas et n'est pas responsable ou iresponsable d'aucun contenu, de la publicité, de produits, ou
d'autres matériaux dessus ou fournis par de tels emplacements ou ressources. Sun ne sera pas responsable ou
iresponsable d'aucuns dommages ou perte causés ou allégués pour être causé par ou en liaison avec l'utilisation de ce
produit ou la confiance dans des tels contenu, marchandises, ou services disponibles sur ou par des tels emplacements
ou ressources.

13

You might also like