Delving Into Components

December 2006 [Revision number: V1-1]  
Components are the building blocks of interactive web pages. This technical article provides the basic knowledge that you need to get the most out of the components that are bundled with the Visual Web Pack. After you become familiar with the generalities, drill down to the individual component tutorials to learn more specifics. You can also press F1 on any component in the Palette to access in-depth information about that component.

This technical article expands on concepts that are introduced in Getting Started With NetBeans Visual Web Pack 5.5 and Developing a Web Application.
 

Contents

What Is a Component
General Information
Output Components
Input Components
Action and Link Components
Layout Components
Non-Visual Components
Summary
  Content on this page applies to NetBeans 5.5 Visual Web Pack
 

What Is a Component

It doesn't take a lot of time or a great depth of knowledge to bang out a static HTML page. However, once you start building dynamic and interactive pages, you enter a realm of complexity. You must know how to use JavaScript for client-side interaction, and you must write Java code and JavaServer Pages (JSP) tags for interaction and validation on the server side. Add to that the many inconsistencies with how different browsers display the tags, and your productivity can slow to a halt.

The JavaServer Faces based components that the Visual Web Pack provides reduce the complexity of building interactive web pages as well as speed up the development cycle. In addition, the Visual Web Pack enables you to use these components without having to learn the intricacies of the JavaServer Faces technology.

Components are tags on steroids. That is, you don't just get the rendered tag, such as a Drop Down List, you get a good-looking tag that is easy to decorate and that generates events, which you can handle using simple Java code. For example, the Text Field component works with the JavaServer Faces framework to convert and validate the input as well as to broadcast change and validation events.

Also, with just a couple of clicks, you can bind a component's property to a bean property or to a data provider wrapper for a data source, regardless of whether the data source is a database, web service, array, or list. By using the binding features, you don't have to write code to fill in the component values, and you don't have to write code to save the component values to the bound objects.

The bundled components offer cool widgets that you can't get using ordinary HTML tags. For example, the Table component shown in the following figure comes with sortable columns and automated paging.

Figure 1: Table Component
Figure 1: Table Component
 

The Visual Web Pack offers two sets of bundled components. One set is built on JavaServer Faces 1.1 technology and the other is built on JavaServer Faces 1.2 technology. The Palette offers the components that are compatible with the Java EE version that you set for the web application project. When you set the Java EE version to Java EE 5, the Palette provides JavaServer Faces 1.2 compatible components. When you set the Java EE version to J2EE 1.3 or 1.4, the Palette provides JavaServer Faces 1.1 compatible components.

This technical article focuses mainly on the components that you find in the Basic, Layout, and Composite sections of the Palette, as shown in the following figure.

Figure 2: Basic, Layout, and Composite Sections
Figure 2: Basic, Layout, and Composite Sections
 

Note: The Standard section in the Palette contains the JavaServer Faces reference implementation components. Because the standard components provide less functionality and require more programming, you should use the visual components from the other Palette sections.

Note: The Palette offers a Form component. This technical article does not discuss the Form component. In most cases, the virtual form mechanism is a much better way to handle multiple forms on a page.

General Information

This section provides information that applies to most or all components. The remainder of the technical article is broken into five sections (output, input, action and link, layout, and non-visual) as reflected in the following figure.

Figure 3: Five Types of Components
Figure 3: Five Types of Components
 

Component Properties

You use the Properties window to specify a component's appearance and behavior. For example, you use the Listbox component's rows property to specify the length of the rendered listbox, and you use the multiple property to specify whether the page visitor can select more than one item in the list.

The Visual Web Pack also provides menu actions for each component's common tasks. For example, the Image component has a Set Image menu item, the Static Text component has an Edit Text menu item, and the Drop Down List component has an Edit Label menu item.

The following table describes the common properties for controlling a component's behavior and appearance. Subsequent sections discuss the specifics for the different types of components.

Property Description
id Every component must have an id that is unique for its page. The IDE creates an id when you add the component to the page. You might want to change a component's id in the following cases:

  • The component is an input component. Give the component an id that corresponds to the property or column to which it is bound, such as personIdDropDown.
  • The component, such as a button, generates action events. Set the id to a verb name that matches the label of the component, such as submitButton.
  • You have several components of the same type on the page and you need to write Java source code to set or access the property values for some of the components. For example, the code is easier to understand if you reference nameTF and addressTF instead of textField1 and textField2.
toolTip Use this property to specify the text that appears when the page visitor hovers the cursor over the component.
style Use the style property to change the following settings:

  • Font
  • Background
  • Text Block
  • Border
  • Margin
  • Position

The ellipses (...) button for the style property opens a Style Editor, which makes it easy to change settings and preview the results. For a description of how to use this editor, click the Help button at the bottom of the editor.

Generally, the IDE sets the height, width, or both, when you resize a component. If the page is in Grid Layout mode, the IDE sets the position values when you drop the component on the page, and when you reposition it on the page.

Sometimes, you see actual properties that are similar to the style settings, such as bgcolor or border. These are standard HTML 4 style attributes. The style property is an enhancement to these standard attributes and provides a better mechanism for configuring a component's look.

The component set implements the Web UI Default Theme, which is a coordinated set of cascading stylesheet (CSS) files. You can override most, but not all, of the theme's style features by making style settings. For example, you cannot use the style property to set the background color for a table or to set the font color for a label property. This is especially true when the setting conflicts with the component's theme. Also, in some cases, the specific area is obscured by other child components that might have different style settings.
styleClass Every project has a theme, which is a set of Cascading Style Sheets (CSS), JavaScript files, and icon images. The Visual Web Pack provides the Web UI Default Theme. To add your own styles to the theme, use the style sheet editor or put style sheets in the project's resources folder. The drop-down list for the styleClass property shows all the style classes for all the style sheets that the application uses. Normally, you do not use this property unless you want to select a style class from your own style sheet. The styleClass settings are applied in addition to the theme's style classes for the component.
visible The visible property specifies whether a rendered component is visible on the page. When the visible property is set to false, it does not appear on the rendered page, but it still appears in the emitted HTML (the page source), its value is submitted, and all the component's conversions, validations, and event generations still happen.
rendered Setting a component's rendered property to false removes the component from the emitted HTML and the component is not available to the client. You cannot reference the component from JavaScript, and no conversions, validations, or event generations occur when the page is submitted.
 

Setting Component Values

All input and output components are value-holding components. For example, a Text Field component holds text, and a Listbox component holds the selected values. There are several ways to set the values of input and output components:

  • Set the component's value-holding property. In the Properties window, click the value-holding property's ellipsis button (...) to open a text editor. Also, for most input and output components, you can select the component in the Visual Designer and start typing to enter the component's value. The pop-up menu for a value-holding property contains Edit menu items for the component's editable text.
  • Call the Component's setter method from the page bean's source code. For example, you call the setText method to set a Text Field component's value, and you call the setSelected method to set a Listbox component's values. Some common places to call the setter method are in the preprocess, prerender, value change, and action methods.
  • Bind the component to a data provider or to a bean property. See the next subsection for more information about binding a component to data.

Note: As with the JavaServer Pages implementation, when the server constructs a page from JSP source, the tag attribute settings in the JSP source take precedence over runtime settings. For example, if you set the text property for a Static Text component to "moon," the IDE adds text="moon" to the Static Text component's tag in the JSP file. Even if the page's prerender method has a staticText1.setText("sun") statement, the Static Text component shows "moon" when the application renders the page. If the page is rerendered, the staticText1.setText("sun") statement takes affect and the Static Text component shows "sun." If you visit another page and come back, the server once again constructs the page from the JSP source, the values set in the JSP tag attributes take precedence, and the page displays "moon."

Tip: To ensure that property setting code always takes effect, do not set that property to a static value in the Properties window.

Binding to Data

You can bind most input and output components to data objects. Binding a component to data enables the web application to automatically synchronize the component's value with the value of the binding target. For example, if you bind a component to a bean property, the web application sets the component's value to the bean property's value when the application renders the page, and when the page is submitted, the web application changes the bean property's value to match changes made to the component's value.

The Visual Web Pack includes data provider wrappers for database tables, web services, Enterprise JavaBeans objects, maps, arrays, and lists. You associate a data provider with a data object and bind components to the data provider. One advantage of using data providers is that they offer a common interface for accessing all types of data.

To create a data provider for a database table, drag the database table from the Databases section of the Runtime window and drop it on the page or drop it on a component in the page. The IDE creates a CachedRowSet Table Data Provider for the database table.

For more information about binding and data providers, see the Using Databound Components to Access Databases tutorial.

Converting Values

The Visual Web Pack provides several converters that you can apply to most input and output components. A converter converts an object's value to a String so that the value can be written to the HTML response. Conversely, a converter converts String values in the HTML request back to the specified data type, such as Boolean or Float.

Note: The web application automatically performs the appropriate conversion for any component that is bound to data. For example, if a Text Field component is bound to an Integer object, the web application automatically converts the input value (a String) to an Integer.

Output Components

The Visual Web Pack offers several output components, as shown in the following figure. These components fall into three groups: text, message, and image. You typically use the output text components for laying out text on a page, and you use the output message components to respond to user input or for other types of dynamic actions. You use the Image component to display a repository of pixel values, such as a jpg or a gif file.

Figure 4: Output Components
Figure 4: Output Components
 

Output Text Components

The Visual Web Pack provides three output text components.

Output Text Component Usage
Static Text



You use the Static Text component when you want to simply display some text on the page.
Label



You use the Label component to associate text with an input component. You associate a Label component with an input component by setting the Label component's for property. When you associate a Label component with an input component, the Label component becomes "smarter." Specifically, if the input component's required property is true, the Label component displays an asterisk. If the server rejects the page submission because the input is invalid, the page highlights the Label component's text.

While the input components do have label properties, you are better off using the Label component because, when you set an input component's label property, you cannot resize or correctly align that component. Also, you have more style options with Label components.
Inline Help



You use the Inline Help component to display short, help-type information on a page.
 

Output Message Components

The Visual Web Pack provides the following output components for displaying various types of messages. With the exception of the Page Alert component, these components only appear on the rendered page when their values are not null.

Output Message Component Usage
Alert



You use the Alert component to display dynamic information such as warnings, errors, success status, or informational status on the completion of some event. You can display an error icon, information icon, warning icon, or success icon along with summary text. You can also optionally display detail text and a hyperlink.

You use the summary and detail properties to set the component's text, and you use the type property to specify which icon to display. The component appears on the page only when the summary property has a value.

You can add an optional hyperlink by specifying linkText and linkURL values. The linkText value does not appear in the component unless the detail property has a value.

To specify dynamic page navigation for the link, do the following steps:

  1. Set the linkText property.
  2. Use the Page Navigation editor to create a connector between the page's connector port and the destination page. Assign the connector a name, such as alertOutcome.
  3. Switch to the Visual Designer and double-click the Alert component. The IDE creates an action event handler method and positions the Java editor on the method.
  4. Change the method's return statement to return the name that you assigned to the connecting line, such as alertOutcome.
Note how this procedure is slightly different from the steps for other action components as described in Action and Link Components. This is because the Page Navigator only allows connectors from pages and from the components that extend UICommand. The Alert component does not extend UICommand.
Page Alert



The Page Alert component is similar to the Alert component and is intended for displaying dynamic messages on a separate page. The Page Alert offers the choice of error, warning, information, and question icons. You use the title, summary, and detail properties to set the component's text, and the type property to specify which icon to display.

Message



You use the Message component to display an input component's error messages. To associate a Message component with an input component, set the Message component's for property. The application sends messages about conversion and validation errors to the Message component. To send your own validation message to a component, throw one of the following exceptions:

  • ValidatorException(new FacesMessage(summary)).
  • ValidatorException(new FacesMessage(summary, detail)).
  • ValidatorException(new FacesMessage(severity, summary, detail)). For the severity argument, you can pass FacesMessage.SEVERITY_INFO, FacesMessage.SEVERITY_WARN, FacesMessage.SEVERITY_ERROR, or FacesMessage.SEVERITY_FATAL.
With the JavaServer Faces 1.2 set of components, you can override the standard error messages by calling the component's requiredMessage, converterMessage, and validatorMessage methods to specify custom messages.
Message Group



You use the Message Group component to display runtime errors. You can also show individual component errors, such as validation and conversion errors, by clearing the showGlobalOnly property's checkbox. Message Group components are also useful for diagnosing programming errors.

To write your own text to this component, call info(String summary), warn(String summary), error(String summary), or fatal(String summary). The web application applies different styles to the text, depending on the method's severity level.

To write both a summary message and a detail message, use FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(summary, detail)) or ValidatorException(new FacesMessage(severity, summary, detail)).

You must select the component's showDetail checkbox for detail messages to appear.
 

Just as with the output text components, you can programmatically set the output values for the Page Alert and Alert components by calling the setter for the appropriate property. For example, to set a Page Alert component's summary text, call setSummary(String). You can also bind these properties to managed bean properties and data provider fields.


The Image Component

You use the Image component either to display a graphic image that is specified by the url property or to display one of the provided icons, such as ALARM_CRITICAL_MEDIUM, or ALERT_OK_SMALL, which you can choose from the icon property's drop-down list.

Figure 5: Image Component Examples
Figure 5: Image Component Examples
 

The url property can contain the URL to an image on the Internet or it can point to an image file in the project's resources folder, such as /resources/images/duke.gif. You can also bind the url property to a managed bean property or to a data provider field that returns the path to the URL in String format. When you click the ellipsis (...) button for the url property, you can either select the Use Binding radio button to bind the property to a data object, or you can select the Use Value radio button to specify an image file. If the image is not yet in the resources folder, click Add File to locate the file and to copy it to the folder. Alternatively, you can type a valid URL in the property's text box.

Tip: When you specify a URL for an image that is packaged with the web application, use a context-relative URL. That is, begin the URL with a forward slash (/), such as /resources/images/dot.gif. When you use a context-relative URL, you cause the server to convert the URL into a full URL before the page is rendered and sent to the client. If you do not prepend the forward slash, the interpretation is done on the client side and the client prepends the URL of the location of the current page to the image's URL. If the page is in a subfolder, the URL might not resolve correctly when requests are forwarded (the default dispatch mechanism).

Input Components

As shown in the following figure, the Visual Web Pack provides several different ways to get user input. This section describes the input components, discusses their common features, and explains how to obtain and process the input values.

Figure 6: Input Components
Figure 6: Input Components
 

The Visual Web Pack provides the following input components.

Input Component Usage
Text Input Components



You use the Text Field component for entering a single line of text, and the Text Area component for multi-line input. Use the Password Field component for an input field that echoes back the input characters with a replacement character to mask the input.
Selection Components



The Radio Button Group, Checkbox Group, Drop Down List, Listbox, and Add Remove List components are very similar. They all provide a list of items (display values) from which the page visitor can select one or more choices.

Each item in a selection component has an underlying return value, which is returned by the selected property's value if the page visitor selects that option.

There are several ways to initialize the list of items:

  • Use a Default Options Component. When you add a selection component to the page, the IDE creates a Default Options component and binds it to the selection component. The Default Options components appear in the Outline window. You can see the binding in the component's items property. To add options to the list, right-click the component and choose Configure Default Options from the pop-up menu. Alternatively, you can add code like the following to the init() method:

    Code Sample 1: Initializing List Options
    dropDown1DefaultOptions.setOptions(new Option[] {
      new Option("item1", "Item 1"),
      new Option("item2", "Item 2"),
      new Option("item3", "Item 3")}
    );
  • Bind the items property to a Data Provider. Drop a database table from Servers window onto the page to create a data provider for the table. Then, right-click the component, choose Bind to Data from the pop-up menu, click the Bind to Data Provider tab, and choose from the list of existing data providers. Choose a column for the return value and choose a column for the display value.
  • Bind the items property to an array of com.sun.webui.jsf.model.Option. (Use com.sun.rave.web.ui.model.Option for the bundled JavaServer Faces 1.1 components.). Typically, you create this array as a Session Bean property. You can also bind the property to an object that implements java.util.Map, if the values of the map are instances of Option. However, the keys are ignored and you have no control over the order in which the values are displayed. That is, the web application displays the values randomly.

One way to preselect items is to call setSelected(Object[]) or setSelected(Object) from the prerender() method. You pass in the return values of the items that you want preselected. Be sure to verify that getSelected() returns null before setting the default options, or you will overwrite the user's selections on a post-back.

If the selection component is bound to a Default Options component, you can preselect items by choosing Configure Default Options from the selection component's pop-up menu. Select the Select Items checkbox, and select the default options that you want preselected.

Warning: The Javadoc and code completion for the Add Remove List component show a getSelectedItems() method, which returns an Iterator. Do not use this method, as it is intended for internal rendering purposes only, and does not reflect the actual selected items.
Checkbox and Radio Button



Single Checkbox and Radio Button components are available for adding to Table component columns. You can also add Checkbox and Radio Button components as standalone components on a page. However, the Radio Button Group and Checkbox Group components are preferable for presenting a list of checkable choices.
Calendar



The Calendar component enables the page visitor to enter a date, either by typing in the date or by choosing it from a pop-up calendar. The selectedDate property value contains the entered date as a java.util.Date object.

To set a date range for the pop-up calendar, bind the minDate and maxDate properties to bean properties of type java.util.Date, which have values for the beginning and ending dates. The following sample shows code for setting the minimum date to the current date. Note that for the minimum date, you must set the time to 0.

Code Sample 2: Minimum Date Property
    private Date minCalDate;
    
    public Date getMinCalDate() {
        java.util.Calendar date = 
		  java.util.Calendar.getInstance(
		  FacesContext.getCurrentInstance().
		    getViewRoot().getLocale());
        // Have to zero out the time because 
        // the date comparison is time sensitive
        date.set(java.util.Calendar.HOUR_OF_DAY, 0);
        date.set(java.util.Calendar.MINUTE, 0);
        date.set(java.util.Calendar.SECOND, 0);
        date.set(java.util.Calendar.MILLISECOND, 0);
        return date.getTime();
    }
 

In this version of the Visual Web Pack, if the minimumDate property is not set, the minimum date defaults 100 years ago and the maximumDate defaults to 100 years from today.

The date format defaults to the default format for the locale. You can use the dateFormatPattern property editor to select from a list of date format patterns.

To change the date format pattern that appears below the component's input field, edit the dateFormatPatternHelp property.

Tip: You can override the minimum and maximum date error messages by passing your custom error message as a String to the component's validatorMessage method.
File Upload



The File Upload component enables a page visitor to locate a file on their system and upload that file to the server.

The component's uploadedFile property returns a value of type com.sun.webui.model.UploadedFile for JavaServer Faces 1.2 components and com.sun.rave.web.ui.model.UploadedFile for JavaServer Faces 1.1 components. The UploadedFile interface has methods for getting the name and size of the file, determining the file's MIME type (such as text/plain or image/jpeg), getting the file's contents as bytes or as a String, and writing the contents to disk. To learn more, right-click on UploadedFile in a declaration statement in the Java source and choose Show Javadoc from the pop-up menu.

By default, the application limits the size of an uploaded file to 1 megabyte. To change the size limit, modify the maxSize parameter for the UploadFilter filter in the application's web.xml file.
 

Customizing an Input Component's Behavior and Appearance

The Visual Web Pack provides the following features for customizing an input component's behavior and appearance.

  • Labeling Fields. There are two ways to label input components:

    • Use a Label Property. You can quickly add a label by setting the input component's label and labelLevel property. When you set the Label property, the component uses the Label value instead of the component's id in the standard converter, required, and validator error messages.
    • Use a Label Component. Label components provide more style control than label properties. In addition, you can align the labels separately from the alignment of the input components, and you have more control over the size of the label and its associated input component. One disadvantage of using a Label component instead of the Label property is that the error messages display the component's internal id in the error message if the Label property is not set. You can override the standard error messages by calling the component's converterMessage, requiredMessage, and validatorMessage methods with your custom messages, or by adding a resource bundle that overrides the standard messages on an application wide basis.
  • Displaying Error Messages. As mentioned earlier, you can add Message and Message Group components to report conversion and validation errors. To associate a Message component with an input component, you set the Message component's for property to the id of the input component. The Message Group component shows all the input conversion and input validation error messages unless you set the Message Group component's showGlobalOnly property to true.

    Tip: Adding a Message Group component to every page is good practice for diagnosing programming errors.
  • Disabling Input and Making Input Components Read Only. All input components have disabled and readOnly properties. Set disabled to true to prevent the user from tabbing to the component and to prevent the application from converting, validating, and submitting the value. Set readOnly to true when you want to prevent the user from entering or changing the value, but you still want the application to convert, validate, and submit the value.
  • Setting the Tab Order. You use the tabIndex property to specify the order in which the user tabs through the input components on a page.
  • Trimming Blank Characters. When the trim property is true, the application removes all leading and trailing blanks from the input. This removal is done before conversion and validation. Some input components, such as the Calendar and File Upload components, do not have a trim property. The application trims their input automatically.
  • Limiting the Number of Characters That Can be Entered. You can use the maxLength property to set the maximum number of characters that the page visitor can type into the input field. The application ignores subsequent character input. For example, if the maxLength value is 5, and the page visitor types bicycle, all that appears in the field is bicyc.
  • Using Input Components to Submit Pages. For most input components, you can select Auto-Submit on Change from the component's pop-up menu to cause the browser to submit the page whenever the input value changes. A typical use of this feature is to cause the page to be submitted whenever the page visitor chooses a new item from a drop-down list of master data so that the detail data can be synchronized to match the new master data selection. For example, when the page visitor selects a new product from the drop-down list, the page redisplays with detail data for that product.

    If you do not want the browser to submit all the input values when the component's value is changed, use a virtual form to indicate what values to submit.

Getting and Setting Input Values

The following table shows the value-holding property for each input component. You use the value-holding property's getter and setter methods to access the input value. For example, you use getSelected and setSelected to get and set the input value for any component that has selected as its value-holding property. You can also bind these value-holding properties to data as explained in the General Information section.

Component Value-Holding Property Type Notes
Text Field, Text Area, Password Field text String or, if bound, the type of the object to which the field is bound.  
Drop Down List selected For the items property, you specify a display label and a return value for each item in the drop-down list. The selected property returns an object of the same type as the return values. If you use a Default Options component to specify the items and return values, selected returns a String. When the page visitor selects an item from the drop-down list, the application sets the component's selected property to the return value of the selected list item.
Listbox selected For the items property, you specify a display label and a return value for each item in the list. The selected property returns an object, or, if the multiple property is selected, an array of objects, of the same type as the return values.

If you use a Default Options component to specify the items and return values, selected returns a String, or if multiple is true, an array of String objects.
If the multiple property is false, the value of the component's selected property matches the return value of the selected list item. If the multiple property is set to true (to enable the user to select more than one item), you must bind selected to an array of Object, an array of primitives, or java.util.List. If you use java.util.List, you must specify a converter for the type of the List members unless they are String objects. The array contains values that match the return values of the selected items.
Radio Button (not in a group) selected By default, boolean. However, you can bind to a wrapper type such as Boolean, Byte, Character, Double, Float, Integer, Long, Short, String, the primitive form of one of these wrapper types, or an application-defined object value. The component is considered to be selected when the value of the selected property matches the value of the selectedValue property. By default, selectedValue is set to true.

If there are several Radio Button components with the same value for the name property, only one radio button in the set can be selected at a time. You typically use the name property when you have a Radio Button component in a Table Component column.
Radio Button Group selected For the items property, you specify a display label and a return value for each radio button. The selected property returns an object of the same type as the return values. If you use a Default Options component to specify the items and return values, selected returns a String. When the page visitor selects a radio button, the application sets the radio button group's selected property to the return value of the selected radio button.
Checkbox (not in a group) selected By default, boolean. However, you can bind to a wrapper type such as Boolean, Byte, Character, Double, Float, Integer, Long, Short, String, the primitive form of one of these wrapper types, or an application defined object value. The component is considered to be selected when the value of the selected property matches the value of the selectedValue property. By default, selectedValue is set to true.

For the JavaServer Faces 1.2 version, if the Checkbox is in a Table component, set the name property and bind the selectedValue to a property for which the getter returns a value that identifies the checkbox. For example, have the getter return tableRowGroup1.getRowKey().toString(). To determine which checkboxes have been checked, call the Checkbox component's getSelected method, which returns an ArrayList.
Checkbox Group selected For the items property, you specify a display label and a return value. The selected value returns an array of objects of the same type as the return values. If you use a Default Options component to specify the items and return values, selected returns an array of String objects. The values in the selected array match the return values of the selected checkboxes.
Calendar selectedDate java.util.Date  
File Upload uploadedFile com.sun.rave.web.ui.model.UploadedFile For security reasons, the uploadedFile property is read-only.

The UploadedFile interface has methods for getting the name and size of the file, getting the file's contents as a String, and writing the contents to disk. To learn more, right-click UploadedFile in a declaration statement in the Java source and choose Show Javadoc from the pop-up menu.

The UploadedFile.getOriginalName() method returns the original file name in the client's file system, as provided by the browser. In most cases, this is base file name, without path information. However, some browsers include path information.

Note: The various browsers render the File Upload component differently. The component usually appears smaller in a browser than in the Visual Designer.
Add Remove List selected An array of Object For the items property, you specify a display label and a return value. The values in the selected array match the return values of the selected items.
 

Verifying User Input

You can use the following features to verify user input. When one or more input fields fail verification, the web application rerenders the page, highlights in red the associated labels, if any, for the invalid input, and sends error messages to the Message Group component and associated Message components, if they exist on the page.

  • Required Input. Every input component provides a required property. When the property is set to true, the web application automatically verifies that the input has a value.
  • Value Conversion. As discussed in the General Information section, the Visual Web Pack provides several converters, which you can apply to an input component. Conversions are performed before the validation process starts. If the page visitor provides a value that the application cannot convert to the specified data type, the web application rejects the input and sends an error message. This error message appears in the Message Group component and the associated Message component if they exist on the page. The Number Converter is a useful converter because you can use it to specify patterns that the input must match.
  • Input Validation. The Visual Web Pack provides three validation components, which you can apply to any input component:

    • Double Range Validator. Checks whether the component's converted value is within a certain range. The value must be floating-point or convertible to floating-point.
    • Length Validator. Checks whether the length of a component's local value is within a certain range. The value must be a String.
    • Long Range Validator. Checks whether the local value of a component is within a certain range. The value must be any numeric type or String that can be converted to a long.

    Alternatively, you can add your own validation method by right-clicking the component and choosing Edit Event Handler > Validate. This menu item creates a validation method and registers the method as a validation event listener. The validation method accepts a FacesContext, a UIComponent, and an Object (the value), and the method throws a ValidatorException.

    As with conversion errors, the application sends validation error messages to the Message Group component and the associated Message components if they exist on the page.

    Note: You can either apply a validator to a component or you can register a validation event handler for the component, but not both.

    The web application performs all the validations before it calls any value change listeners and action listeners. If one or more validation errors occur, the value change listeners and action listeners are not called, and the web application rerenders the page so that the page visitor can correct the problems.
  • Immediate Processing on Change. If you want the browser to submit the page as soon as the page visitor changes the component's value, right-click the component and choose Auto-Submit on Change from the pop-up menu.
  • Turning Conversion and Validation Off. Sometimes you might want to turn off processing, including conversion and validation, on some of the input components on a page. You can use the IDE's virtual form settings to specify which fields to process for a given action. For example, when someone clicks a Cancel button, you might want to bypass processing of all input fields. Or perhaps you have two buttons on a page, and you only want to submit a subset of the fields depending on which button is clicked.

    Note that you can also use the immediate property to limit the processing of input values. However, the virtual form feature is much easier to use. For example, the web application calls the conversion, validation, and value change listeners (and action listeners if an action component) for components that have their immediate property set to true in an earlier JavaServer Faces lifecycle phase than the other components. That is, these processing steps for the immediate components are called during the Apply Request Values phase before the normal conversion processes occur and before the validations occur in the subsequent Process Validations phase. In contrast, virtual forms are much more straightforward, because they do not alter the JavaServer Faces lifecycle.
When a page visitor submits a page, the web application performs the input verifications in the following order:
  1. Conversions
  2. Required input
  3. Validations

Note: Value change events occur only when the value actually changes and all validations are successful.


Handling Value Change Events

A web application that is built with the Visual Web Pack sends a value change event for an input component when the input component's validation has succeeded and the submitted value is different from the one that was displayed. You can register a method as a value change event handler for responding to such an event. For example, you can write a method to change detail data whenever the user changes the master value, and then register that method as a value change listener. When the page visitor changes the master value and submits the page, the web application invokes that method, and thus updates the detail data to match.

An application fires events in the following order:
  1. Events for immediate components are fired first, based on a depth first walk of the component tree.
  2. Value change events for non-immediate input components are fired next, based on a depth first walk of the component tree.
  3. Action events for non-immediate command components are fired last, based on a depth first walk of the component tree.

A quick way to create and register a value change event handler is to double-click the input component in the Visual Designer. When you do so, the IDE creates a method and registers the method as a listener for the component's value change events. The component's valueChange property shows the name of the registered event handler, if any.

Action and Link Components

You use action and link components to enable the page visitor to move from one page to the next and to submit input. The following figure shows the action and link components that the Palette provides.

Figure 7: Action and Link Components
Figure 7: Action and Link Components
 

Simple Page Navigation

If you want the user to click a component to move to a specific page, and you do not want the browser to submit any user input, you can use the Hyperlink, Image Hyperlink, Tab, or Tree Node component and type the path to the destination page in the component's url property, such as /faces/Page1.jsp.


Dynamic Page Navigation

The Page Navigation editor enables you to specify navigation rules that map user actions and decision logic outcome to destination pages. You specify the mapping by dragging a named connector from the link or action component to the destination page. You must also create an action handler for the component that returns the outcome, which is a String value equal to the connector's name. You can use the component's action property to create the action handler.

When a page visitor clicks the component, the browser submits the input, if any, and the action handler returns an outcome. The server looks up the outcome in the navigation rule mapping to determine what page to respond with. If there is no navigation rule for that outcome, the server redisplays the current page. You can write the action handler to return different outcomes based on business logic.

Note: When you set both the url and the action property, the url handler takes precedence. The action handler will not be called.

For more information about page navigation, see the Setting Up Page Navigation tutorial.

Layout Components

The Palette includes several layout components to help arrange the components on a page and to present the components in useful ways, as shown in the following figure.

Figure 8: Layout Components
Figure 8: Layout Components
 

The following table explains the purpose of each layout component and describes how to use the component.

Component Usage
Breadcrumbs



The Breadcrumbs Component enables you to lay out a series of link components separated by right angle brackets (>). You typically use a Breadcrumbs component to show the page visitor the hierarchy of the section or branch that the page is in. When you add a Breadcrumbs component, the IDE automatically adds a nested Hyperlink component for every page in the application. You can use the Outline window to delete, add, and rearrange the nested Hyperlink components.

Alternatively, you can bind the pages property to an array of Hyperlink objects, where each hyperlink represents a page. To display correctly, each Hyperlink component must have, at a minimum, a value for the text property and a value for either the url property or the action property.
Page Fragment Box



The Page Fragment Box component enables you to reuse the same content across several pages. When you change the contents of the page fragment, the changes appear in all the pages that use that page fragment.
Page Separator



Use the Page Separator component to create a horizontal line that separates items on the page. You can also use the Page Separator component to separate items in a Grid Panel cell or in a Group Panel component.
Tree and Tree Node



You use the Tree component and nested Tree Node components to render an expandable list in a tree structure. Trees are often used for navigation in a web application and for navigating through nested data, such as a file system structure. To add another node, right-click a Tree component or a Tree Node component in the Outline window and choose Add Tree Node. The default image for a node is either a folder icon or a page icon depending on whether the node has children (nested nodes).

Use the action property to specify an action handler for when the page visitor selects a tree node. Use the actionListener property to specify a handler for when the page visitor opens or closes a node.

Tip: By default, the browser makes a request to the server each time the page visitor expands or collapses a node. To cause the expanding and collapsing to occur on the client instead, set clientSide to true.
Tab Set and Tab



You can use the Tab Set component as a navigation tool or you can use it to display different layouts on the same page. To add tabs, right-click the Tab Set node in the Outline window and choose Add Tab.

To use the Tab Set as a navigation tool, add a tab for each navigation path and use the Page Navigation editor to specify the destination page for each tab.

To use the Tab Set to display different layouts on the same page, add the desired number of tabs. Then, select each tab in the Visual Designer and add that tab's components.

The Tab Set component's selected property shows the id of the current tab selection.

The Tab component contains a nested Layout Panel component. To add components to a tab, drop them in the Layout Panel component.
Layout Panel



This panel is similar to a page in that you can specify either a grid layout or a flow layout by setting the Layout Panel component's layoutPanel value. In flow mode, components line up, left to right. In grid mode, the components position where you drop them.
Property Sheet and Property



The Property Sheet component enables you to quickly lay out a set of labeled components. The Property Sheet provides and lays out the labels and sections, and you add the components. To add sections, right-click the Property Sheet node and choose Add Property Sheet Section. To add properties, right-click a Section node and choose Add Property. To add a component to a property, drag the component from the Palette and drop it on the Property node in the Outline window.

To display links to each section at the top of the property sheet, set the Property Sheet's jumpLinks to true. You can use the Property component's labelAlign property to align the labels on the left or on the right. Set noWrap to true if you do not want the label text to wrap.
Grid Panel



You use the Grid Panel component to arrange components in rows and columns. After you add the Grid Panel to the page, set the columns property to the number of columns per row. As you add components to the Grid Panel, the IDE adds the components across the row until you fill up the row. The IDE adds rows as necessary.
Group Panel



You use the Group Panel component to group nested components in flow layout mode. The browser positions the components next to each other, wrapping components to the next line as necessary. The components move up to the previous line or down to the next line as the page visitor resizes the page. The Group Panel component is useful for nesting components, such as nesting buttons inside a Page Alert component or nesting components inside a cell in a Grid Panel component.

By default, the block property is set to false, meaning that the component is rendered using the <span> tag, and height and width style settings are ignored. If you need to set a specific height or width for the component, set the block property to true.

If the page is in flow layout mode, setting the block property to true forces the browser to render the component on its own line. The components before and after it appear on different lines.
Table



The Table component makes it easy to display tabular data such as data from a database table or information from an array or list. The quickest way to populate a Table component is to create a data provider for the tabular data and bind the Table component to the data provider, as shown in the Using Databound Components to Access Databases tutorial.

Right-click the component and choose Table Layout to display a dialog box that enables you to do the following:

  • Set the table's title
  • Add and remove columns
  • Set the header, footer, and component type (such as Static Text, Text Field, or Button) for each column
  • Enable sorting and add various sort buttons
  • Enable pagination
  • Specify the text that should appear if a cell is empty

You use a table's nested TableRowGroup component to work with the table's data values. For example, if a column has a button, you use the TableRowGroup component's getRowKey() to determine the underlying row of data as shown in the following code example.

Code Sample 3: Processing a Button in a Table
public String submitTableButton_action() {
  RowKey rowkey = tableRowGroup1.getRowKey();
  getSessionBean1().setSelectedPersonId(
    travelDataProvider.getValue("PERSON.PERSONID", rowkey).toString());
  return "showDetail";
}
 
Tip: When working with nested components in the Visual Designer, press Escape to select the enclosing (parent) component. You can also use the Outline window to select the enclosing parent as well as to rearrange the order of the nested components.
 

Non-Visual Components

The Visual Web Pack provides two non-visual components.

Component Usage
Hidden Field A Hidden Field component is a non-visible form field. A typical use of the Hidden Field component is to store values for use by JavaScript. Because the values of Hidden Field components get submitted, server-side code, such as the page bean, can examine changes made by JavaScript code. You can also use the Hidden Field component to pass values to the rerendered page.
Anchor You use Anchor components to position link targets within a page. The HTML equivalent of the Anchor component is <a name=targetname>. The component's id is the target name. For example, if the component's id is anchor1, you can set a hyperlink's url property to #anchor1 to jump to the position of the Anchor component.
 

Summary

  • The Palette provides components for displaying information, accepting user input, enabling form submission and page navigation, and configuring page layouts.
  • You use the Properties window to configure a component's appearance and behavior. You can also use a property's get and set methods to programmatically define the property's value.
  • You can bind most properties to data.
  • The IDE takes care of value conversions for bound data. You can also use converters to convert component values.
  • Tools for validating input include the required property, validators, and validation event handling.
  • Virtual forms enable concise control over which components are processed when a form is submitted.
  • You use action methods and URLs to define page navigation.
  • You use value change event handling to process input.
 

This page was last modified:  December 6, 2006


Copyright and Trademark Notice