Working with JSF Select Components

Written by Chris Schalk, Oracle Corporation
January 2005

Introduction

An extremely common Web application development task is to assemble User Interface (UI) components which display selection choices from either static or dynamic sources such as from a database or a Web Service. Obviously basic HTML form elements can easily handle the static case, but when dynamic content is needed, technologies like JavaServer Faces for the UI presentation and a middle-tier technology like Oracle TopLink offer a comprehensive solution.

This HowTo provides detailed instructions on how to assemble both static JSF and dynamic selection Components which are bound to data provided from an Oracle TopLink middle-tier using Oracle JDeveloper 10.1.3 Preview.

A related, complementary HowTo, "Working with ADF Faces JSF Select Components", is also available on OTN. It demonstrates the same selection examples but instead using Oracle's ADF Faces JSF Components. Readers are definitely encouraged to check it out as well..

Getting Started - Building an Oracle TopLink middle-tier

To get started, first make sure to download JDeveloper 10.1.3 Preview from OTN and install it on your machine. You'll also want to set up a database connection. (This HowTo uses a connection to the HR common schema, but any schema will suffice.)

  1. To start building our example app, we'll use the Application Workspace wizard which will generate both a Model project for our middle-tier persistence code as well as a ViewController project for our View (and Controller) components of our application. File->New->General->Application.



    For the Application Package Prefix we'll use "selectfun"and for the Application Template along with "No Template [All Technologies]".

  2. Click OK to generate the Workspace.
  3. You can name the new project selectexamples.


  4. Build a TopLink middle-tier set of classes for the HR.Employees table. (Note: Any database table will do.).
  5. Once you have a Toplink mid-tier as well as a TopLink Deployment Descriptor, generate a sample java client. Some of the code generated will later be copied to a managed bean for our JSF application.
    • Select the Employees.java class and right-click "New Sample Java Client".



  6. Optional: At this point feel free to run the new sample client to make sure that your TopLink persistence code works. You'll see a list of Employees in the console.

  7. Create a new Java class "ModelBean". This will contain two fields as well as a method which extracts data from the TopLink middle-tier.

  8. Add two fields "selectedcountry" and "selectedempno" of type java.lang.String to ModelBean using the the Class editor. (Click on the "Class" tab at the bottom of the edit and then click on the "Add" button at the top. )


  9. Using the class editor, add an employees field of type: java.util.List.
  10. Important!: This will add an empty field "employees" to our ModelBean, however we must add code to instantiate the employees List of type ArrayList. To do this add the following to the declaration of the employees List:

    • public class ModelBean
      {
      String selectedCountry;
      String selectedEmpno;
      List employees = new ArrayList();

  11. Now we will modify the getter for the employees field, "getEmployees", with code from the main method from our TopLink EmployeesClient class.
    • In the getEmployees method of ModelBean before the single "return employees;" line, copy and paste the content of the generated "main()" method in the EmployeesClient class. (Later we will bind a JSF selection component to this method when we create the View.)

      Here's an example of the code for your new getEmployees method after you've pasted it: (note: you should not copy and paste this code as you will need your own path to your toplink deployment descriptor.)

    •   public List getEmployees()
      { EmployeesClient employeesClient = new EmployeesClient(); // To use sessions.xml uncomment the following three lines of code, fill in the appropriate resource locations and add sessions.xml to the classpath. // oracle.toplink.tools.sessionconfiguration.XMLLoader xmlLoader = new oracle.toplink.tools.sessionconfiguration.XMLLoader("META-INF/sessions.xml"); // oracle.toplink.tools.sessionmanagement.SessionManager sessionManager = oracle.toplink.tools.sessionmanagement.SessionManager.getManager(); // DatabaseSession session = (DatabaseSession)sessionManager.getSession(xmlLoader, "MySessionName", employeesClient.getClass().getClassLoader()); // To use sessions.xml as defined above, comment out the following three lines of code. oracle.toplink.sessions.Project project = XMLProjectReader.read("path_to_your/toplink-deployment-descriptor.xml"); DatabaseSession session = project.createDatabaseSession(); session.login(); Vector objects = session.readAllObjects(selectfun.Employees.class); for (Iterator itr = objects.iterator();itr.hasNext();) { employeesClient.printObjectAttributes(itr.next()); } return employees; }
    • Now we'll modify it to work with a JSF SelectItem Component. Replace the employeesClient.printObjectAttributes(..); statement in the for loop with code to populate the employees list. See below:
        public List getEmployees()
      { EmployeesClient employeesClient = new EmployeesClient(); // To use sessions.xml uncomment the following three lines of code, fill in the appropriate resource locations and add sessions.xml to the classpath. // oracle.toplink.tools.sessionconfiguration.XMLLoader xmlLoader = new oracle.toplink.tools.sessionconfiguration.XMLLoader("META-INF/sessions.xml"); // oracle.toplink.tools.sessionmanagement.SessionManager sessionManager = oracle.toplink.tools.sessionmanagement.SessionManager.getManager(); // DatabaseSession session = (DatabaseSession)sessionManager.getSession(xmlLoader, "MySessionName", employeesClient.getClass().getClassLoader()); // To use sessions.xml as defined above, comment out the following three lines of code. oracle.toplink.sessions.Project project = XMLProjectReader.read("path_to_your/toplink-deployment-descriptor.xml"); DatabaseSession session = project.createDatabaseSession(); session.login(); Vector objects = session.readAllObjects(selectfun.Employees.class); for (Iterator itr = objects.iterator();itr.hasNext();) { try { Field field = itr.next().getClass().getDeclaredField("email"); Field valfield = itr.next().getClass().getDeclaredField("employeeId"); field.setAccessible(true); valfield.setAccessible(true); employees.add(new SelectItem( valfield.get(itr.next()).toString(), field.get(itr.next()).toString())); } catch (Exception ex) { ex.printStackTrace(); } } return employees; }
  12. As you add the code, JDeveloper will prompt you to import required packages into the class. Accept the recommendations. Note: You'll also have to make sure that the "JSF" library is added to the project. (Double-Click the project in the navigator, select the Libraries node and click "Add Library"..)
  13. Save all and compile all. Your project should compile successfully.

Building the View with JSF Components

We will now build a simple View with the original JSF Reference Implementation (RI) UI Components. In a related followup HowTo, you can learn how to construct a similar View using Oracle's ADF Faces JSF Components.

Important Notice: Please note that this application will be built with JSF Auto-Binding turned off. This is an option which autobinds both the page and any JSF Components that you drag and drop onto your JSF page, however this HowTo shows how to manually bind JSF pages. Before continuing, please make sure that the JSF Auto-Binding option is turned off by unchecking the "Autobind JSF.." setting in the JSP and HTML visual editor preferences.
For further info, see my Blog entry on this: http://radio.weblogs.com/0130966/2005/01/05.html#a28

  1. In the same project build a JSF enabled JSP page by selecting File->New->Web-Tier->JSF->JSF JSP.
    Important Notice: Creating JSF-JSP and subsequent drag and drop of JSF Comoponent



  2. As you invoke the JSF JSP Wizard you can name the page "selectfun.jsp". You can also leave the type and error page settings as default and click "Finish" to generate your page. (For further customizations of the page you can optionally click "Next" in the JSP wizard.)

  3. Once the page is generate feel free to add a banner such as "JSF Select Fun" formatted to <H2>. Also add separate lines: "Static Example" and "Dynamic Example Using Oracle TopLink". Format these with <H3>.:You can then drag and drop a Cascading Style Sheet (such as jdeveloper) from the CSS palette page.



  4. Before continuing we'll need to add our ModelBean class that we created in the Model project as a managed bean in the Faces-Config.xml file. To do this locate the faces-config.xml file in the navigator (Web Content->WEB-INF->faces-config.xml) and double-click it to edit its contents.

  5. The default editor for the faces-config.xml file is the Page Flow modeler, but for this simple application we will not introduce any navigation rules so click on the "Overview" tab at the bottom of the page to invoke the faces-config editing console.

  6. Add a new Managed Bean by first clicking on the Managed Beans node on the left in the console and clicking "New".
    Specify the following and click OK:
    • Name: Model
    • Class: selectfun.ModelBean
    • Scope: request



  7. Now we'll build a simple static example Select list which will display a list of countries and display the country code selected. Under the "Static Example" enter a new paragraph <p> with text: "Select a Country:".

  8. From the Component Palette drag and drop the "Menu" item onto the page after the new paragraph. The Menu item on the palette is actually the JSF HTML h:selectOneMenu UI Component. Notice after you drag and drop, a simple wizard appears which allows you to bind it to a List or directly to static values. Let's create a static list of countries using the wizard.

    After clicking OK, the wizard will add insert the parent tag h:selectOneMenu along with children tags (UI Components), <f:selectItem>, with your static values defined in the wizard.

  9. At this point we could run the page and it will display the values, but in order to save the selected value we must bind the h:selectOneMenu parent tag to the selectedcountry field of our ModelBean.
    To bind the List Menu, first select it in the visual editor, click in the "Value" property in the Property Inspector, click the databind icon , then click in the Value property again. This will add an empty JSF expression along with a button to invoke the JSF Value binder dialog . Click on the new button to invoke the dialog. You can then bind the Value attribute to #{Model.selectedcountry}.



    After clicking "OK" the "selectedcountry" field will receive the value from the selected List Menu item when a form submit occurs.

  10. To show the selected value on the page after a form submit occurs, we'll use an outputText JSF UI Component..
    In the page beneath the select menu, enter a new paragraph and add text "You selected: ". Then drag and drop an "Output Text" (h:outputText) JSF UI Component onto the page. Bind the Value attribute to #{Model.selectedcountry} using the Value binding dialog.

  11. Before running the static example we need to insert a CommandButton which will allows us to submit the form. From the Component Palette drag and drop the "Command Button" onto the bottom of the page. Set the Value to "Update Model".

  12. Save All and run the selectfun.jsp page (right-click and select Run.). You should see the selected country codes for the selected countries.



  13. Now we'll create a dynamicly bound List item based on data from TopLink. In the page beneath the static example, add a new paragraph and enter the text: "Select an Employee: ".

  14. Drag and drop a new JSF Menu UI Component and bind it to the List supplied from TopLink. As the wizard appears, click on the Bind option and invoke the JSF value binder dialog and bind the List to #{Model.employees}.

    Clicking OK will bind the child tag f:selectItems to the getEmployees method returning a List generated from TopLink.

  15. Again we must now bind the parent selection tag to the selectedempno field of our ModelBean class. Select the new List Menu ("h:SelectOneMenu") and bind the Value property to #{Model.selectedempno} using the JSF value binder dialog.

  16. To show what we selected, enter a new paragraph with text:"You selected Employee #: " and then drop an "Output Text" (h:outputText) JSF component next to the text and bind it to the same #{Model.selectedempno} field. (You can also wrap it with bold <b> tags as well.)

  17. Re-run the JSP page, select a country and an employee and observe the results!


  18. Cool huh!

Summary

As you can see in this HowTo, using JSF select Component with both static or dynamic sources is a fairly straightforward process. This example explains how to use just one of the many JSF select components, feel free to begin experimenting with the other various JSF select Components.

An Oracle ADF Faces View Option

In addition to using the provided JSF RI Components, it is also possible to use Oracle's ADF Faces JSF Components. A followup HowTo which shows how to use ADF Faces JSF Components to build a similar View with both static and dynamic Select components is available on OTN as wells: Working with ADF Faces JSF Select Components. Readers are encouraged to check this out as well!

 

E-mail this page
Printer View Printer View
Oracle Is The Information Company About Oracle | Oracle RSS Feeds | Careers | Contact Us | Site Maps | Legal Notices | Terms of Use | Privacy