Products Docs & Support Community

>> More Visual Web Pack Documentation

Using the Ajax Text Completion Component

May [Revision number: V5.5-1]    

This tutorial shows you how to use NetBeans Visual Web Pack 5.5 to build a web page that contains a text field component created using Java BluePrints Ajax technology. As you type in the text field, auto-completion is attempted based on a list of possible expansions provided by a 180,000-word English dictionary. The dictionary is provided through a web service; you must download and install the dictionary service.

Note: This tutorial currently does not support any non-English version of the DictionaryService.war file. The text field component supports only ASCII characters.

Contents

Adding the Auto Complete Text Field
Adding the Dictionary Service Client
Adding Code to Display a Set of Words
Adding Code to Display Word Definitions
Summary
 

External code used in this tutorial

» Dictionary Service

This tutorial works with the following technologies and resources

JavaServer Faces Components/
Java EE Platform
works with1.2 with Java EE 5*
works with1.1 with J2EE 1.4
Travel Database not requiredNot required
BluePrints AJAX Component Library requiredRequired

* When this tutorial was published, only the Sun Java System Application Server supported Java EE 5.

This tutorial has been tailored for use with the Sun Java Application Server PE 9.0 Update Release 1.

Adding the Auto Complete Text Field

The completed application that you develop in this tutorial is shown in the following figure.

Figure 1: Final Design of Page

To create this page, begin by adding the Auto Complete Text Field component. The source code included with this component displays the text "Hello" and also the uppercase version of the text typed in the text field.
  1. Download and import the BluePrints AJAX components if you have not already done so.
  2. From the main menu, choose File > New Project.
  3. Create a new visual web application project and name it AutoCompleteApp.
  4. Choose Sun Java System Application Server 9, and choose either Java EE 5 or J2EE 1.4 for the Java EE version.

    Note: This tutorial works only with the Sun Java System Application Server.
  5. In the Projects window, right-click the AutoCompleteApp > Component Libraries node and choose Add Component Library from the pop-up menu. Select BluePrints AJAX Components and click Add Component Library.

    The IDE copies the component library into the project and adds the components to the Palette.
  6. Drag a Label component from the Basic section of the Palette and drop it on the page. Set its text property to Type a word:.
  7. From the BluePrints AJAX Components section of the Palette, drag the Auto Complete Text Field component and drop it on the page next to the Label component.
  8. Double-click the Auto Complete Text Field component to add an event handler and open its source in the Java Editor.

    The Java Editor opens with the insertion point in the autoComplete1_complete method.
  9. Remove the comment characters (//) from the two lines beginning with result so that the autoComplete1_complete method is as follows:

    Code Sample 1: Event Handler Code
    public void autoComplete1_complete(FacesContext context,
    String prefix, CompletionResult result) {
    result.addItem("Hello");
    result.addItem(prefix.toUpperCase());
    }
    
  10. Deploy and run the application.

    Note that as you type in the text field, the uppercase version of what you type is displayed, as shown in the figure below. The server performs the computation to convert the typed text into upper case without any kind of page submit. The text field dynamically displays the results, as shown in the figure below.

    Figure 2: Text Completion Initial Page

Adding the Dictionary Service Client

You can enhance the function of the text completion component to use the dictionary service to display a small set of words that start with the text typed in the Auto Complete Text Field. The dictionary web service has an interface with two methods. One method looks up the definition of a word, and the other method returns the ten closest matches to a user input. To access the dictionary service client, you must download and extract the Dictionary Service zip file, deploy the DictionaryService.war to your application server, and then add the web service to your application.

As noted above, DictionaryService.war currently does not support non-English locales.
  1. Download and extract the contents of the Dictionary Service zip file.
  2. Deploy the DictionaryService.war to your server.
  3. In the IDE, open the DictionaryService.wsdl file by choosing File > Open File and navigating to the location where you saved the file.
  4. Verify that the default deployment URL and port number, match your application server settings. If necessary, edit the file to match your application server settings, and then save the file.
  5. In the Projects window, right-click the AutoCompletionApp project node and choose New > Web Service Client.

    The New Web Service Client, as shown in Figure 2, opens.
  6. In the New Web Service Client wizard, click Local File and add the path to the DictionaryService.wsdl file.
  7. Choose autocompleteapp for the Package. If the Client Type field is active, choose IDE-generated static stub for the setting, and then click Finish.

    The IDE compiles the libraries and addss a Web Service References node to your Project menu.


    Figure 3: New Web Service Client Wizard

Adding Code to Display a Set of Words

Now you modify the code so that it uses the dictionary service to display a small set of words that start with the text typed in the Auto Complete Text Field. Again, the words display dynamically without any page submits.
  1. In the Java Editor, remove the lines that begin with result.
  2. With the cursor in the autoComplete1_complete method, right-click and choose Web Service Client Resources > Call Web Service Operation.

    Note: If the Call Web Service Operation dialog is empty, close and reopen the window.
  3. In the Select Operation to Invoke dialog box, click matchPrefix, and then click OK.


    Figure 4: Select Operation to Invoke Dialog

    A try-catch block that invokes the DictionaryServiceSEIPort:matchPrefix operation is added to the autoComplete1_complete method.
  4. If your project is a J2EE 1.4 project, skip to step 5. For a Java EE 5 project, remove the line java.util.List<java.lang.String> result = port.matchPrefix(string1); and copy and paste the code shown in bold in Code Sample 2.

    The code defines the type for the variable that the results are placed into, passes the prefix into the matching method, and adds the output results object.

    Code Sample 2: Call the Dictionary Web Service With Arguments (for Java EE 5 Projects)
    public void autoComplete1_complete(FacesContext context, String prefix, CompletionResult result) {
    // TODO: Return your own list of items here based on the prefix, like this:
    try { // Call Web Service Operation
    autocompleteapp.DictionaryService service = new autocompleteapp.DictionaryService();
    autocompleteapp.DictionaryServiceSEI port = service.getDictionaryServiceSEIPort();
    // TODO initialize WS operation arguments here
    java.lang.String string1 = "";
    // TODO process result here
    java.util.List items = port.matchPrefix(prefix);
    result.addItems(items);

    System.out.println("Result = "+result);
    } catch (Exception ex) {
    // TODO handle custom exceptions here
    }
    }
    }
  5. If your project is a Java EE 5 project, skip this step. For a J2EE 1.4 project, delete the line dictionaryServiceSEIPort.matchPrefix(/* TODO enter operation arguments*/); and copy and paste the code shown in bold in Code Sample 3.

    The new code enters an operation to the try statement and adds a custom exception to the catch statement.

    Code Sample 3: Call the Dictionary Web Service With Arguments (for J2EE 1.4 Projects)
    public void autoComplete1_complete(FacesContext context, String prefix, CompletionResult result) {
            try { // This code block invokes the DictionaryServiceSEIPort:matchPrefix operation
                on web service
                autocompleteapp.DictionaryService dictionaryService =
                new autocompleteapp.DictionaryService_Impl();
                autocompleteapp.DictionaryServiceSEI dictionaryServiceSEIPort =
                dictionaryService.getDictionaryServiceSEIPort();
                String[] items = dictionaryServiceSEIPort.matchPrefix(prefix);
                result.addItems(items);
            } catch(javax.xml.rpc.ServiceException ex) {
                // TODO handle ServiceException
            } catch(java.rmi.RemoteException ex) {
                // TODO handle remote exception
            } catch(Exception ex) {
                log("Exception getting the matching words", ex);
                String[] items = new String[] {"Exception getting the matching words"};
                result.addItems(items);
            }
        }
    }
  6. Deploy and run the application.

    When you type in the Auto Complete Text Field, a list of ten words is returned from the dictionary service and displayed in the text field, as shown in the following figure:

    Figure 5: First Ten Words Returned by the Dictionary Service
  7. Type java in the text field.

    The list displays the word Java and the next nine words provided by the dictionary service, as shown in the figure below.

    Figure 6: List of Ten Words Returned After Typing Java

    In the next steps, you enable the user to look up the definition of a word chosen from the list.

Adding Code to Display Word Definitions

Here you add a Static Text component and a Button component to the page. You add the DictionaryServiceSEIPort:define operation to the button handler to use the definitions from the dictionary service. When the user clicks the Button, the definition of the chosen word displays in the Static Text component.
  1. Return to the Visual Designer.
  2. Drag another Label component onto the Visual Designer and place it under the first Label component. Set its text property to Definition:.
  3. Drag a Static Text component onto the page and drop it below the Auto Complete Text Field component.
  4. Resize the width of the Static Text component so that it is slightly wider than the Auto Complete Text Field.

    You do this so that the text as it displays in the deployed application does not show up as a long column only a couple of words wide, as allowed by the default width of the component.
  5. In the Data section of the Properties window, set the Static Text component's escape property to False.

    A value of False turns off the escaping of HTML so that the characters <, >, and & are not converted into the HTML entities <, >, and &. This is necessary because the dictionary service returns the word's definition with HTML markups. The HTML tags need to be interpreted by the browser instead of displayed just as plain text.
  6. Drag a Message Group component onto the page and place it under the Static Text.
  7. Drag a Button component onto the page and place it to the right of the Auto Complete Text Field. Set the Button's id property to lookUpButton and set its text property to Look Up.
  8. Double-click the Look Up button to show its event handler code.
  9. Right-click in the Java Editor and choose Web Service Client Resources > Call Web Service Operation.
  10. In the Select Operation to Invoke dialog box, click define, and then click OK.

    A try-catch block that invokes the DictionaryServiceSEIPort:define operation is added to the lookUpButton_action method.
  11. If your project is a J2EE 1.4 project, skip to Step 12. For a Java EE 5 project, modify the lookUpButton_action method by removing the line java.lang.String string1 = ""; and replace it by copying and pasting the following code, shown in bold in Code Sample 4.

    Code Sample 4: Button Handler (for Java EE 5 Projects)
    public String lookUpButton_action() {
            // TODO: Process the button click action. Return value is a navigation
            // case name where null will return to the same page.
            try { // This code block invokes the DictionaryServiceSEIPort:define operation
                on web service
    autocompleteapp.DictionaryService dictionaryService = new autocompleteapp.DictionaryService();
    autocompleteapp.DictionaryServiceSEI dictionaryServiceSEIPort = dictionaryService.getDictionaryServiceSEIPort();
    String definition = dictionaryServiceSEIPort.define(autoComplete1.getText());
    staticText1.setText(definition);
    } catch(Exception ex) {
    log("Dictionary Service Error:", ex);
    error("Error accessing Dictionary Service");

    }
    return null; } }
  12. If your project is a Java EE 5 project, skip this step. For a J2EE 1.4 project, modify the lookUpButton_action method by removing the line dictionaryServiceSEIPort.define(/* TODO enter operation arguments*/); and replacing it with the code shown in bold in Code Sample 5.

    Code Sample 5: Button Handler (for J2EE 1.4 Projects)
    public String lookUpButton_action() {
            // TODO: Process the button click action. Return value is a navigation
            // case name where null will return to the same page.
            try { // This code block invokes the DictionaryServiceSEIPort:define operation
                on web service
                autocompleteapp.DictionaryService dictionaryService =
                new autocompleteapp.DictionaryService_Impl();
                autocompleteapp.DictionaryServiceSEI dictionaryServiceSEIPort =
                dictionaryService.getDictionaryServiceSEIPort();
                String definition = dictionaryServiceSEIPort.define(autoComplete1.getText());
                staticText1.setText(definition);
            } catch(javax.xml.rpc.ServiceException ex) {
                // TODO handle ServiceException
            } catch(java.rmi.RemoteException ex) {
                // TODO handle remote exception
            } catch(Exception ex) {
                log("Dictionary Service Error:", ex);
                error("Error accessing Dictionary Service");
            }
            return null;
        }
    }
  13. Deploy and run the application.
  14. Type the word Java in the text field and click the Look Up button.

    The corresponding definition is retrieved from the dictionary service and displays on the page, as shown in the following figure.

    Figure 7: Chosen Word and Its Definition
     

See Also:


This page was last modified:  May 24,