|
April 2006 [Revision number: V2.1-1] |
|
|
This tutorial gives you a whirlwind tour of the Sun Java Studio Creator integrated
development environment (IDE). The tutorial shows you how to use the IDE to perform
the typical phases of web application development.
The tutorial is designed so that you do not need to go through it in any particular
order. You might want to skim over it quickly and then return to each section
as time allows. |
|
Contents
|
![[spacer]](/im/a.gif) |
 |
Starting a Project
A project is the equivalent of your working environment for a web application.
When you create a project from the IDE, the IDE builds a supporting directory
structure, which conforms to the
standard directory layout for web applications. In addition, the IDE creates
directories for building and deploying the application.
You create a project by choosing File > New Project from the main menu.
Try It
Start the IDE, using the appropriate step:
- Windows. Double-click the Creator desktop icon.
- Mac. Double-click the Creator icon in the installation folder.
- Solaris Operating System (SPARC and x86 Platform Editions) and Linux. Go to the install-directory
/sun/Creator2_1/bin directory, type ./creator, and press Enter. Note that if you have version 2, and not version 2 update 1, the bin directory is under Creator2.
Create a project by choosing File > New Project from the main menu. Note
that the default project type is a web application, then click Next. Click Finish
to accept the default project name and location. The IDE creates the project directory
Creator/Projects/web-application-name under your home directory
by default. To change the default location, see the help
topic "Setting the Location of Project Files."
Explore the Projects window, which is shown in the following figure. The Projects
window groups items by category. Expand each of the nodes to see what type goes in each category. Notice the badges that are next to the Request Bean,
Session Bean, and Application Bean nodes. These badges show that the files need
to be compiled. The IDE compiles the files automatically when you build the project.
Figure 1: Projects Window |
Under the Web Pages node is the Page1.jsp
node. The IDE creates this page by default and makes it the start page. The arrow
badge next to the node identifies the page as the start page. If you want to use
a different page for the start page, right-click that page's node and choose Set
as Start Page from the pop-up menu.
Click the Files header, or choose View > Files from the main
menu, to bring the Files window to the front. This window organizes the
items by their physical storage. Expand the nodes to see the structure. Hover
the mouse over the nodes and subnodes to see the tool tips.
Figure 2: Files Window |
In Figure 2, notice the WebApplication1 > src
> webapplication1 > Page1.java node. This Java class is the backing bean
for the Page1.jsp file. Whenever you add a page to the project, the IDE creates
both a .jsp file and a .java file for the page. You
learn more about .jsp and .java files in the next section.
For More Information
- From the main menu, choose Help > Help Contents > Starting With Projects > About Projects.
Creating Web Pages
With JavaServer pages (JSP) web applications, you use JSP pages and page
beans (also known as backing beans) instead of HTML pages. The JSP page is a
template from which the server generates the HTML response to be
displayed in the browser (the client). The page bean contains
the logic that the server executes when generating the HTML response
and also after a user submits the page.
When you add a web
page using the IDE, the IDE creates both a JSP file and a Java source file for
you. You mostly use the Visual Designer and the Properties window to develop the
web page. The IDE modifies the JSP code and Java code to implement what you design.
Most of your work can be done from the Visual Designer.
Note: The JSP pages that the IDE generates are JSP documents. A JSP document is an XML document and, therefore, must be well-formed.
While most JSP elements comply with XML syntax, there are some elements that are not XML compliant, such as comments, declarations, directives,
expressions, and scriptlets. See the JavaServer Pages Syntax Reference for JSP document syntax.
In the Projects window, right-click the Web Pages node and choose New > Page, as shown in the following figure.
Figure 3: Right-Clicking the Web Pages Node |
Name the page Page2 and click Finish. The IDE opens Page2 in the Visual Editor, which is in the editing area.
Figure 4: Visual Designer |
Click the Java button in the editing toolbar to see the source
code for the page bean, as shown in the following figure.
When the editing area shows the Java source,
the Navigator window appears in the bottom-left corner. This
window lists all the member fields and methods. Notice that
the page's source code has methods to access the Application Bean, Session Bean, and Request Bean. See the Storing
and Passing Data section in this tutorial for an explanation
of these three types of beans.
The source also has methods that get invoked during certain lifecycle events between
the time the page is requested and the time the page rendering is complete.
Figure 5: Java Source for Page Bean |
Tip: Double-clicking a member in the Navigator window positions
the source code in the editing area on that member's declaration.
You can also click in the Navigator window and start typing the first few characters of a member's name to raise a Quick Search
dialog box. Continue typing until the IDE
highlights the desired entry in the list, and press enter to
position the source code to the
matching member's declaration, as shown in the following figure.
Figure 6: Quick Search in the Navigator Window |
Click the JSP button in the editing toolbar to see the JSP code for the page, as shown in the following figure. Notice how the JSP page
uses JSP document syntax. If you are familiar with JSP pages, you might also note how the JSF tags, such as <ui:page>, use
the #{...} expression language (EL) syntax instead of the ${...} syntax, so that the expression is evaluated by the
tag handler.
Figure 7: JSP View |
Click Design in the editing toolbar to switch to the Visual
Designer and to display the representation of the page
in the Outline window, which is shown in the following figure.
Note how the tags in the JSP file are represented
as nodes in the Outline window.
Figure 8: Outline Window |
For More Information
Adding Components to a Web Page
You design a web page by dragging components from the Components tab of the
Palette window and dropping them on the web page in the Visual Designer. The following
figure shows Page2 with the Button, Calendar, Text Field, Message, Drop
Down List, and Radio Button Group components. All of these
components are available from the Basic section of the Palette.
The components have been customized by changing the component
properties. You learn about properties later in this section.
Figure 9: Components in the Visual Designer |
Note: The components that are available from the Palette are JSF 1.1
components, which have been enhanced according to the Design
Time API so that they are available at design time. You can use other JSF 1.1 components in the web applications that you build using the IDE,
but you will not be able to use the interactive design-time features of the IDE on these components, unless they have been customized according
to requirements of the Design Time API.
Most of the components that you use
are in the Basic, Layout, and Composite sections of the Palette window. The following
tables show some of the most commonly used components.
Input Components
| Text Field |
Input field for a single line of text. |
Basic |
| Text Area |
Multiple-line input field. |
Basic |
| Password Field |
Input field that echoes the input characters with a replacement character, so as to mask the input. |
Basic |
| Calendar |
Input field with a pop-up calendar that allows the user to select a date. |
Basic |
| Drop Down List |
A drop-down menu, also referred to as a combo box. |
Basic |
| Listbox |
A list from which the user can select either one item or multiple items, depending on how the component is configured. |
Basic |
| Checkbox |
A single-character box that the user can either select (check) or clear. |
Basic |
| Radio Button |
A single radio button that the user can select (check). |
Basic |
| Add Remove List |
Contains two listboxes (one for available options, one for selected options) together with buttons to move the options between the lists, and optionally to order the selected options.
| Composite |
| File Upload |
A component with a text input field and a Browse button that displays a file chooser for specifying a file to upload. The application uploads the specified file when the user submits the page.
| Basic |
Display Components
| Static Text |
Field for displaying text. |
Basic |
| Label |
Text field that can be associated with an input field and for which you can specify a weak, medium, or strong font style. |
Basic |
| Image |
Inline image. |
Basic |
| Message |
Text field that is linked to a specific component for displaying validation errors and other messages about that component. |
Basic |
| Message Group |
Text field for displaying runtime error messages, program generated error messages, and, optionally, validation errors and other messages about components that are on the page. |
Basic |
| Alert |
Displays an icon and informational text such as a warning, an error, or the successful completion of some event.
|
Composite |
| Page Alert |
Similar to an Alert component, but is intended for displaying the icon and information on a separate page.
|
Layout |
Grouping Components
| Checkbox Group |
Displays two or more check boxes in a grid layout. |
Basic |
| Radio Button Group |
Displays two or more radio buttons in a grid layout and ensures that only one button can be selected at a time. |
Basic |
| Table |
Use to display data from a composite data type such as a database table or an array. |
Basic |
| Tree and Tree Node |
Renders an expandable list in a tree structure. |
Basic |
| Tab Set and Tab |
Use to display different layouts on the same page or use as a navigational tool. |
Layout |
| Grid Panel |
Use to organize the components within a layout of rows and columns. |
Layout |
| Group Panel |
Use to group a set of components in flow layout mode. |
Layout |
| Layout Panel |
Use to group a set of components in flow layout mode or grid layout mode. |
Layout |
| Property Sheet |
Use to quickly lay out a single column of labeled components, and optionally divide the components into sections. |
Layout |
| Breadcrumbs |
Use to lay out a series of link components
separated by right angle brackets (>). |
Composite |
| Page Fragment Box |
Use to group components that you want to consistently display on two or more pages. |
Layout |
Action Components
| Button |
Button that submits the associated form. |
Basic |
| Hyperlink |
Text field that submits a URL or submits a form |
Basic |
| Image Hyperlink |
Image that submits a URL or submits a form. |
Basic |
| Tree Node |
A subcomponent of a Tree or Tree Node. A leaf tree node can optionally submit a URL or submit a form.
|
Basic |
| Tab |
A subcomponent of a Tab Set or a Tab. A tab can optionally submit a URL or submit a form. |
Composite |
You use the component's property sheet
in the Properties window to change the appearance and behavior of the component,
to bind the component to data, and to associate the component with event handlers.
The following figure shows the properties sheet for a Listbox component.
Figure 10: Listbox Property Sheet in the Properties Window |
Try It
Create a new page named Page2 or reuse the one that you created by following the Try It suggestions in the Creating Web Pages section.
Drag various components from the Basic section and the Layout section of the
Palette window and play around with their properties. For example, try the following
steps:
- Drag a Button Component onto the page, type
Click Me! and press
Enter. In the Properties window, notice how the text
property has the value Click Me!. Also notice
how the text property name appears in bold. Bold property
names indicate that the property's value has been changed from its default. In the
Properties window, select the primary property's
checkbox and notice how the button's appearance changes.
- Drop a Calendar component on the page and set the
label property to Expiration Date:.
- Drag a Text Field component onto the page. Next, drag a Label component onto the page, type
Name:, and press Enter. Ctrl-Shift-Click
inside the Label component and drag to the Text Field component. Notice how the for property for the Label component is
now set to the id for the Text Field Component. Set the labelLevel to Strong (1).
- Drag a Message component to the right of the Text Field. Control-Shift-Drag from the Message Component to the Text Field
component. As with the Label component, notice how the
for property for the Message component is
now set to the id for the Text Field Component.
- Drag a Drop Down List component onto the page and set its
label property to Color.
Right-click the Drop Down List component and choose Configure Default Options to raise the Options Customizer.
Triple-click Item 1 in the Display column and type Blue.
Use similar steps to change Item 2 to White and change Item 3
to Green. Click OK and notice how your changes affect the component in
the Visual Designer.
- Use steps similar to those for the Drop Down List to create a Radio
Button Group component with the choices Blue, White, and Red.
In addition, select the Select Items checkbox in the Options Customizer,
and select one of the radio buttons in the Selected column to set
the default selection to that item. Click OK to apply the changes
and to dismiss the Options Customizer. In the Properties window,
set the columns property to 3 to align the radio buttons horizontally
instead of vertically.
- Right-click on a blank spot in the page and choose Preview in Browser to see how your browser
renders the components.
For More Information
Getting Help About the IDE
The IDE provides a Help Viewer, which contains help topics about the IDE and the bundled components.
To access the help topics, choose
Help > Help Contents from the main menu. Also, when you press F1 on a window, dialog
box, or Palette component, the Help viewer appears
and displays information about that item.
The IDE also provides a Dynamic Help window, which shows links to information
that is related to the current window or object. When you double-click
a link in the Dynamic Help window, the IDE displays the information in
the appropriate viewer, such as a browser, the Help viewer, or the Javadoc
viewer.
Try It
- Create a page with a Text Field component and a Drop Down List component. Select the Text Field component. Notice
the topics in the Dynamic Help window.
- Select the Drop Down List component. Notice the new topics in the Dynamic Help window.
- In the Dynamic Help window, double-click the Drop Down List Component node to view the topic in the Help viewer. Close the Help viewer.
- Click in the Properties window for the Drop Down List. Press F1 to view the topic about the Drop Down List component properties.
- Select the node for the Text Field component in the Basic section of the Palette. Press F1 to view the help
topic about the Text Field component.
Building and Testing a Web Application
When you are ready to test run a project, press Ctrl-F5 or click the Run Main
Project button. The IDE takes the following actions:
- Saves any files that need saving.
- Compiles any files that need to be compiled.
If there are any complications, the IDE displays the related error messages in the Output window (shown below) and does not continue with the build-and-run process. Click the link in the error message to go to the source code that caused the compilation error.
- Starts the application server if it is not already started.
- Deploys the application to the application server.
If there are any complications, the IDE displays the related error messages in the Output window and does not continue with the build-and-run process.
- Opens a browser and sends the URL for the deployed application to the browser which, in turn, displays the start page.
Figure 11: Output Window |
If you have made massive changes, deleted several items, or you are seeing
some unexpected behavior, you can choose Build > Clean and Build Main Project
from the main menu. The IDE cleans out the project's build directory and dist
directory, undeploys the web application, and then builds
and deploys the application.
Try It
- Open a page in the Visual Designer, or create a new one
by right-clicking the Web Pages node in the Projects
window and choosing New > Page. If the page's node in the Projects window does not display the start page badge (a green arrow), right-click the page's node and choose Set as Start Page from the pop-up menu. Drag a Hyperlink component onto the page, type
Next Page, and press Enter. In the Properties window for the Hyperlink
component, set the url property to /faces/Page2.jsp.
- Create a page named Page 2 if one does not already exist.
- Press Ctrl-F5 to build and run the web application and watch the messages that appear in the Output window. Look
at the URL that the IDE sends to the browser.
- When the start page appears in the browser, click the Next Page link. If you are reusing the page that you created in the Adding Components to a Web Page section, you can try out the components that you added earlier.
- In the Servers window, expand Deployment Server, expand Deployed Components, and note that there is a
node for your project.
- Right-click the Deployment Server node and choose View Server Log from the pop-up menu. Press Ctrl-F5 to run the application. The server log appears in the Output window. You might have to click the Output
window's header bar to bring the window to the front.
You can use the
log(String) method
to send messages to the server log.
Figure 12: Deployed Components |
For More Information
- From the main menu, choose Help > Help Contents > Starting With Projects > Building a Project > Building a Project.
- From the main menu, choose Help > Help Contents > Deploying Applications > About Deployment.
Linking Web Pages and Handling User Actions
When a user types in a URL, clicks a link, or clicks a button, the browser
sends a request to the server. The server maps the request to a JSP page and uses
that JSP page and its associated page bean to render a response.
You can specify page navigation in one of two ways:
- You add a link component, such as the Hyperlink component,
the Tree Node component, or the Tab component, to the page and set
the component's URL property to
/faces/page-name.jsp.
note: A Tree Node component must be nested within a Tree component or a Tree Node component. A Tab component
must be nested withing a Tab Set component or a Tab component.
- You use the Page Navigation editor to map actions to pages, and the Visual Editor and the Java Source Editor to create action handling methods.
To access the Page Navigation editor, right-click on a blank spot in the page in the Visual Designer and choose Page Navigation. The Page Navigation editor shows all the pages in the project. When
you click a page in the Page Navigation editor, the page expands and shows all its action
components. (An action component is a component that has
an action property, such as a Button, a Hyperlink,
or a Tab.) You drag from an action component to a page to create the mapping
between that action's request and the page to be rendered as a response, as shown in the following figure.
Figure 13: Page Navigation Editor |
Try It
- Create two pages named LinkPage1 and LinkPage2. Make LinkPage1 be the start page.
- Drag a Hyperlink component onto LinkPage1, type
Next Page, and press Enter.
- Drag a Button component onto LinkPage2, type
Go, and press Enter.
- Double-click the Button component to access the button's action method. Notice that the action method
returns null. When an action method returns null, the application redisplays the page.
- Click Design in the editing area to switch to the Visual Designer.
- In the Visual Designer, right-click on a blank spot in LinkPage2 and choose Page Navigation. In the Page Navigation
editor, click the icon for LinkPage1.jsp to expand the page's icon. Drag a link from
hyperlink1 in LinkPage1.jsp to LinkPage2.jsp, type
nextPage and press Enter.
Notice how the link is named nextPage. Look at the Properties window
to see the From View, To View, and Outcome properties for the link.
- Use similar steps to create a link from the button on LinkPage2.jsp back to LinkPage1.jsp and name the link
go.
- Click the Source button in the editing toolbar to view the actual mapping XML that is deployed to the server, then close the Page Navigation editor. Click Save when asked whether to save the changes.
- In LinkPage2, double-click the Button component to access the button's action method. Notice that the action method now returns the string "go". That is, it returns the value of the
Outcome property. The mapping that you created in the Page Navigation editor instructs the server to display LinkPage1.jsp whenever LinkPage2.jsp returns "go."
- Press Ctrl-F5 to run the application and try out the new page linkage.
For More Information
Editing Java Code
The IDE's Java Editor is packed full of features to facilitate the programming
process, many more than can be discussed in this introductory tutorial. The following
list of examples of editing features is just the tip of the iceberg.
- b>Code Completion. Code completion enables you to type a few characters and
then choose from a list of possible classes, methods, variables, and so on to
automatically complete the expression. To display the code
completion box, press Ctrl-Space. The code completion box
also appears when you pause after typing a period that follows
a package name, a variable, or a method call, as shown in the
following figure.
Figure 14: Code Completion
Box |
- Javadoc. The code completion feature also displays related Javadoc, if any exists. In addition, you can right-click on a type, field, or method and choose Show Javadoc to see the Javadoc for that item, or you can press Shift-F1 to display a Javadoc Index Search tool. Some of the more commonly used Javadoc API references are available from the Dynamic Help window.
- Fix Imports. Press Alt-Shift-F to add necessary import statements automatically.
- Error detection. Red error boxes appear in the left margin of all statements that will not compile. Hover the mouse over the box to see the description of the error, as shown in the following figure. When you compile files, all compilation errors appear in the Output window. Click on an error message to display the erroneous code in the Java Editor.
Figure 15: Error Detection |
- Java Editor Keyboard Shortcuts. You can invoke many common editing tasks with a simple key combination as shown in the following examples. To learn more about the shortcuts, choose Help > Help Contents > Introduction and Setup > Keyboard Shortcuts > Editor Keyboard Shortcuts from the main menu.
Reformat code |
Ctrl-Shift-F |
Remove current line |
Ctrl-E |
Move insertion point to matching bracket |
Ctrl-[ |
Select the block delineated by the bracket to the left
of the cursor |
Ctrl-Shift-[ |
Word match: forward and back |
Ctrl-L, Ctrl-K |
- Abbreviations. Abbreviations are short groups of characters that expand
into a full word or phrase when you press the space bar, as shown in the following
examples. To see the full list of abbreviations, choose Tools > Options >
Editing > Editor Settings > Java Editor. Click the ellipsis (
...)
button for the Abbreviations property.
for (int i = 0; i < |.length; i++) {} |
fora |
for (Iterator i = |.iterator; i.hasNext();) { Object
o = (Object)i.next();} |
fori |
try {|} catch (Exception ex) {log("Error Description",
ex); } finally {} |
trcf |
- Code Clips. The Code Clips tab of the Palette window contains many useful code clips that you can drag and drop onto your source file.
- Auto Comment Tool. Choose Tools > Auto Comment to raise a dialog box for adding Javadoc comments.
- Quick Search. As mentioned earlier, if you click in the Navigator window and start typing the name of a method or a field, a Quick Search dialog box appears and the IDE highlights the first matching entry in the list. Press Enter to position the Java source code at that entry's declaration.
Try It
NOTE: The following exercises have you type code in the destroy method. The code that you type is meant to illustrate the editing features. You would not normally put this code like this in this method. After you complete the steps, you should remove the code.
- Create a page or open an existing page. Drop a Hyperlink component onto the page. Click Java in the editing toolbar to display the Java source code.
- Right-click in the left margin and choose Show Line Numbers. Press Ctrl-G in the Java source, type 50 in the Go To Line dialog box and press Enter. Right-click in the source and choose Go To from the pop-up menu. Note the actions available from the submenu.
- In the Navigator window, double-click
destroy() to
position the source code on that method. In the destroy()
method, type getSessionBean1(). and pause. The Code Completion
box appears. Type d to see the box narrow the list down to destroy().
Press Enter to use that selection. Type ; and press Enter. Now type
this.getH, press Ctrl-Space to raise the Code Completion box, move the cursor
down to getHyperlink1() and press Enter. Type the period, pause for the Code Completion
box, and type set. After the Code Completion box narrows
down the list to all methods that start with set, type te to narrow the list to setText(Object text) and press Enter. The IDE inserts setText(text) after
the period and selects the word text. Type "hello"; and note how the IDE replaces text with "hello" and places the semi-colon
at the end of the line.
- Start a new line, type
serr and press the Spacebar to expand the abbreviation to
System.err.println(""). Remove the semi-colon from the end of the
line. Press Shift-F9 to compile the file. The Output window displays several links
to errors. Click the first link that appears in the window. The IDE displays the
statement that caused the error. Replace the semi-colon that you just removed.
- Start a new line, type
getSes and press Ctrl-K. The IDE replaces the string with the first matching word from the source code above the current line.
- To clean up the code, place the cursor on the first line in the
destroy method body and press Ctrl-E to remove that line. Use Ctrl-E to remove the remaining lines in the method body.
- Hover over the icons in the editing toolbar and try each one out.
- Right-click in the Java source and choose Code Folds from the pop-up window. Try the various actions in the submenu.
- Try dragging code clips from the Palette to see what they offer.
For More Information
- Using the Java Editor.
- From the main menu, choose Help > Help Contents > Working With Java Source Code > Viewing and Editing Code in the Java Editor.
- From the main menu, choose Help > Help Contents > Introduction and Setup > Keyboard Shortcuts.
Handling User Input
The IDE provides validator and converter objects to facilitate
input checking and formatting. These objects can be found in their
respective sections in the Palette.
You bind a validator
to an input component, such as a Text Field component,
by dropping the validator onto the
input component.
For example, after you add a Text Field component
to a page in the Visual Designer, you can drag a Length Validator
from the Validators section in the Palette and drop it on the Text
Field.
Alternatively, you can drop the validator
onto the page and set the input component's validator
property to that
validator object. For example, you can drop a Long Range Validator
on a blank spot on the page, which adds longRangeValidator1 to
the Outline window. You can then select an input component in
the visual designer, such as the
Text Field component, and choose longRangeValidator1 from its
validator property's drop-down list. This method
enables you to use the same validator for several components.
The same mechanisms are true for converters.
You can also associate converters with output components, such
as the Static Text component.
You use the validator's Properties window to set the validation rules, such as the minimum and maximum value or the minimum and maximum length.
Similarly, you use the converter's Properties window to set the conversion rules, such as the pattern that the value should match or
the method to call to do the validation. The Number converter has a special wizard that appears when
you first drop the Number Converter onto the page or onto a visual component.
The Basic section of the Palette provides the Message component
and the Message Group component for automatically displaying conversion errors, validation errors, and required-field messages. The Message Group component displays global error messages and, optionally, all the component error messages. A Message component displays only the messages for the component to which it is bound. You bind a Message component to another component by setting the Message component's for property or by pressing Ctrl-Shift on the Message component and dragging the mouse to the component that you want to bind the Message component to.
You can programmatically send custom error messages to the
Message Group component using the error, warn, fatal, and info
methods in any Page Bean. To learn more about these methods,
see the entry in the Application Model Reference for the FacesBean class. To view the API for the FacesBean class, expand
Javadoc API References in the Dynamic Help Window,
double-click Application Model Reference, and click
FacesBean in the All Classes list.
Try It
- Create a page and drag a button onto the page. Set the button's text to
Go.
- Drag a Text Field component onto the page. In the Properties window for the Text Field component, select the
required property's checkbox.
- Drop a Label component above the Text Field component, type
Price: and press Enter.
- In the Properties sheet for the Label component, select
textField1 from the drop-down list for the
for property. Note how the label in the Visual Designer shows an asterisk to indicate that input is required for its associated Text Field component.
- In the Palette, expand the Validators section. Drag a Double Range Validator and drop it on the Text Field component.
In the Outline window, select the newly created doubleRangeValidator1 node. In the Properties window for the validator, set the maximum to
10.0 and set the minimum to 1.0, as shown in the following figure.
Figure 16: Double Range Validator Properties |
- In the Palette, expand the Converters section. Drag a Number Converter and drop it on the Text Field component.
A Number Format dialog box appears. Select currency from the Type drop-down list, select English (United States) from the Locale drop-down list, and click OK.
Figure 17: Number Format |
- Add a Message component to the page. Press Ctrl-Shift on the component and drag to the Text Field component.
- Add a Message Group component to the page.
- Make the page be the start page and run the application. Type
$1.50 in the text field
and click the button. Try clicking the button with no price entered, with a price
greater than $10.00, with 1.5 entered, and with a non-numeric value
entered in the price field.
Notice how the application accepts values that conform to the number format, and
rejects all other values. Notice the different messages that appear
in the Message and Message Group components.
- Experiment with setting the
showGlobalOnly checkbox for the Message Group component.
For More Information
Storing and Passing Data
You use the Application Bean, the Session Bean, and the Request Bean to store information for use by other pages.
- Use the Application Bean for information that applies to all user sessions, such as a static option list for
a Drop Down component.
- Use the Session Bean to store information for use by other pages throughout the user's session, such as the
user's logon name.
- If you only need the information for use by the next page, use the Request Bean. (You cannot
use Request Beans in portlets.)
Any value that you store in the Request Bean disappears as soon as the request ends. A request is a single transmission of an HTTP request from the client to the server plus the corresponding response, which can be another page. In most cases, the request begins with the clicking of a button or a link, and ends with the response of an HTML page to be displayed.
Note: The Request Bean gets instantiated only if the page
that initiates the request stores values in Request Bean properties, such as when
an input component is bound to a Request Bean property as described
below.
Warning: You cannot use the Request Bean if you have
included the <redirect> element inside the
<navigation-case> element
of a navigation rule. (You see these rules when
you click the Source button in the Page Navigation editor.) When the
page is submitted, the <redirect> element redirects
the page and
ends the request before a subsequent page can use any of the values
stored in the Request Bean.
To add a property to the Session Bean, right-click the Session
Bean node in the Projects window and choose
Add > Property. The IDE adds a declaration, a getter method,
and a setter method for the property. Use similar steps to add a property to the
Request Bean or the Application Bean.
Tip: If you see syntax errors when you write code that
correctly uses a new property, compile the class that the property is
in to make the property's existence known to other parts of the IDE.
For example, if the new property is in the Session Bean, right-click
the Session Bean node in the Projects window and choose Compile File from
the pop-up menu.
To associate a component with a bean's property, right-click the
component
and choose Bind to Data. In the Bind to Data dialog box, select the
Bind to Object
tab and choose the bean's property, as shown in the following
figure.
Figure 18: Bind to Data Dialog Box |
Note: For most components, the pop-up menu provides two binding actions - Property Bindings and Bind to Data. The Property Bindings dialog
box enables you bind any of the component's properties to a managed bean property or a data provider field. The Bind to Data dialog box is a shortcut
for binding the component's value-holding property to a managed bean property or a data provider field. Use the Bind to Data Provider tab to bind to
any data provider that you have added to the page or a managed bean. Use the Bind to an Object tab to bind to a page property or a managed bean
property.
Try It
- Right-click the Request Bean node in the Projects window and choose Add > Property. Name the property
parm, make it a String, and click OK.
- Create a page named First with a Button component and a Text Field component.
- Right-click the Text Field component and choose Bind to Data from the pop-up menu. Click the Bind to an Object tab,
select RequestBean1 > parm, and click OK.
- Create a page named Next. Add a Button component and add a Static Text component.
- Bind the Static Text component on the Next page to RequestBean1 > parm using the same steps that you used for the Text Field component on the First page.
- Use the Page Navigation tool to create a link from the Button component on the First page to the Next page. Leave the Button component on the Next page alone, because you want this button to cause the Next page to simply rerender itself.
- Set First.jsp as the start page and run the application. Enter a value and click the button. Note that the Next page displays the value that you entered on the First page. Behind the scenes, an instance of RequestBean1 was instantiated to store the Text Field component's value in the parm property. The value of that parm property was subsequently retrieved for the response (the HTML for the Next page). Once the response was rendered, the RequestBean1 instance was destroyed.
- Click the button that is on the Next page to cause the Next page to rerender itself. Notice how the Static Text
component no longer shows a value. This is because the RequestBean1 instance that held the value only lived as long as the request that began when the First page was submitted and that ended when the HTML for the Next page was sent back to the client.
For More Information
Connecting to Databases
The Servers window includes a Data Sources node, which shows all the data sources that are added to the IDE, as
shown in the following figure. The Java Studio Creator IDE comes with an embedded database management system (DBMS), which is prepopulated with sample schemas.
Figure 19: Data Sources |
Before you can access the bundled data sources, you must first start the database server.
If a red X appears on a data source's 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 data source and choose Refresh.
Note: When you open an existing project, the Visual Designer might show an error screen. Typically,
this is because the Visual Designer needs to get information from the database and the database server is not
running. Try starting the database server and clicking the Continue button in the error screen to resolve the problem.
You add a datasource to the IDE by right-clicking the Data Source node in the
Servers window and choosing Add Data Source from the pop-up menu. An
Add Data Source dialog box appears with which you can
supply information about the data source, such as host name,
database name, user name, and password. After you add
the data source, you can expand
the data source's node and expand Tables to access the schema's tables.
You can connect a page with a database table by dragging the table from the data
sources section and either dropping it on a component or dropping it on the page.
When you do this, the IDE adds a data provider to the page and a rowset to the
SessionBean1 class, as shown in the following figure.
Later in this section, you learn how to add
a data provider to the page and bind it to a component in a single step.
Figure 20: Data Provider and Row Set |
The rowset object makes the connection to the database, executes the queries,
and manages the result set. The data provider object provides a common interface
for accessing many types of composite data, from database tables, to Array objects,
to Enterprise JavaBeans objects. Typically, the only time that you work with the
rowset object is when you need to set query parameters. In most cases, you
use the data provider object to access and manipulate the data.
To bind a component to the database, right-click the component and choose Bind
to Data. In the Bind to Data dialog box, click the Bind to Data Provider tab to bring it to the front. The Choose a Data Provider drop-down list shows all the page's data providers from which you can select the data provider to bind to the component. To bind to a data provider that is not on the list, click Add Data Provider and select the appropriate data table from the Add Data Provider dialog box. After you select the data provider, choose the appropriate data column to be bound to the component. For some components, such as the Drop Down List component, you must choose both a Value field and a Display field.
You use the Query Editor for a rowset object to define the SQL query to use to retrieve the data, as shown in the following figure.
Figure 21: Query Editor |
Try It
- Create a page, make it the start page, and drop a Listbox component onto the page.
- Right-click the Listbox component and choose Bind to Data from the pop-up window. Click the Bind to Data Provider tab and click Add Data Provider. In the Add Data Provider dialog box, select Data Sources > Travel > Tables > TRIPTYPE and click Add.
- In the Bind to Data dialog, set the Value Field to TRIPTYPE.TRIPTYPEID (the default selection) and set the
Display Field to TRIPTYPE.DESCRIPTION. Click OK.
- Run the application to see how the listbox is filled with data from the table.
- Expand the SessionBean1 section in the Outline window and double-click the triptypeRowSet node to open its Query Editor. In the DESCRIPTION row of the grid panel, choose Ascending from the drop-down list in the Sort Type column. Close the Query Editor and run the program again. Note how the items now appear in alphabetical order.
- (Optional) Look in the
_init method in the page's Java source code to see the code for associating the data provider with the rowset. This method is folded by default. To unfold the code, click the code fold box that appears next to the left margin.
Double-click the Session Bean node in the Projects window to open the Java source code for the session bean. Look in the session bean's _init method to see how the rowset code implements the query. Right-click on the data provider and rowset methods, and choose Show Javadoc from the pop-up menu to view the documentation about what the methods do.
- (Optional) Double-click on Data Provider Reference and on RowSet Reference in the Dynamic Help window to view
the full set of Javadoc.
For More Information
Debugging a Web Application
The IDE has a built-in debugger to help you troubleshoot your programs. You can use it to set breaks and watches, to step through code, and to run until it reaches the code statement that the cursor is on.
You set a breakpoint by clicking in the left margin of the Java Editor. You set a watch by right-clicking a variable or expression choosing New Watch. To run the debugger, choose either Run > Debug Main Project or Run > Run to
Cursor from the main menu.
Figure 22: Debugger Window |
TIP: Here are some other features that you can use to diagnose and resolve problems:
- 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.
- Add a Message Group component to the page and use the
error, warn, fatal, and info methods to display diagnostic messages in the component.
- In the Servers window, right-click the Deployment Server node and choose View Server Log from the pop-up menu. You can use the
log method to send diagnostic messages to the server log.
Try It
- Create, or reuse, a start page. Add a Static Text component, set its
text property to Hello, and set its id property to helloText.
- Add a Button component. Double-click the Button component to access its action method (
button1_action) and replace the method's body with the following code:
| Code Sample 1: button1_action Method |
String oldString = (String) this.helloText.getText();
this.helloText.setText("Good Bye");
String newString = (String) this.helloText.getText();
return null;
|
- Right-click
oldString, choose New Watch and click OK. Do the same for newString. Click in
the left margin to set a breakpoint for the first statement in the method's body.
- Choose Run > Debug Main Project from the main menu.
- When the page displays in the Web Browser, click the button. When the debugger breaks in the
button1_action method, click the Watches tab in the Debugger window to see the current value of newString and oldString.
- Choose Run > Step Over from the main menu or press F10 to run to the next statement. Look in the Watches tab.
Press F10 two more times and observe the Value column in the Watches tab.
- Explore the Local Variables and Call Stack tabs.
- Choose Run > Finish Debugger Session to close the debugger session.
For More Information
Summary
- You start a web application by creating a project.
- You add pages by choosing Web Pages > New > Page from the Projects window.
- To design a page, drag components from the Palette onto the page in the Visual Designer.
- Click the Run Main Project button in the main toolbar to save, build, deploy, and run the application.
- Use the Page Navigation editor to specify page navigation. You can also add link components to a page and set their
url property values. (Note that you cannot use the url property for page navigation in portlets.)
- Drop Validator and Converter objects onto a component to specify formatting and validation rules.
- Use Message components and the Message Group component to display error messages.
- Use properties in the RequestBean1, SessionBean1, and ApplicationBean1 classes to store and pass values from page to page.
- Use one of the following methods to create a data provider object and its associated rowset for a database table:
- Right-click a component and choose Bind to Data from the pop-up menu, click the Bind to Data Provider tab, click Add Data Provider, and select the data table.
- Drag a table from the Data Sources section of the Servers window onto the page or onto one of its components to create a data provider object and a rowset object for the table.
- Use the Bind to Data menu action to bind components to data provider fields, and to bind components to bean properties.
- Open a Query Editor on a rowset to modify the SQL query that is used to fill the rowset object.
- Use the debugger, the HTTP Monitor, the Server Log, and the Message Group component to diagnose runtime problems.
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: January 24, 2007
|