Skip to main content

By clicking Submit, you agree to the developerWorks terms of use.

The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

All information submitted is secure.

  • Close [x]

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerworks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

By clicking Submit, you agree to the developerWorks terms of use.

All information submitted is secure.

  • Close [x]

developerWorks Community:

  • Close [x]

IBM WebSphere Developer Technical Journal: Developing JSF applications using WebSphere Studio V5.1.1 -- Part 4

Integrating JSF applications with Enterprise Java Beans using action handlers and JavaBean data components

Roland Barcia (barcia@us.ibm.com), Consulting IT Specialist, IBM Software Services for WebSphere
Roland Barcia is a Consulting IT Specialist for IBM Software Services for WebSphere in the New York/New Jersey Metro area.

Summary:  In prior installments of this 5-part series, we built Java Server Faces forms using Rapid Application Development (RAD) JSF components and saw how JSF works with data using Web Data Object (WDO) or Service Data Object (SDO) technology. In Part 4, we demonstrate how JSF can work with existing J2EE technology.

Date:  14 Apr 2004
Level:  Intermediate

Activity:  6530 views
Comments:  

Introduction

This is Part 4 of a series of articles exposing the features of the Java™ Server Faces Technology Preview within WebSphere® Studio V5.1.1. The articles in this series include:

In the Part 3 of this series, we illustrated how JSF applications can access data using the Service Data Object (SDO) technology. In this chapter, we will see how JSF can work with existing J2EE technology. We will create a JSF page that calls an existing EJB application and use JavaBean Data control to display the results of an EJB invocation without compromising the RAD nature of JSF. In addition, we will use the Quick Edits view to write an Action Handler to invoke the existing Stateless Session Bean.

You will need to download the materials included with this article to complete this exercise. In case you have not completed Part 3, the solution is included in the download file; import the EAR file as described in Part 3. To run the example, you need to create the database as we illustrated in Part 3; once you import the solution, run the application as illustrated in the last section of Part 3 to automatically create the JDBC Data Source on the Server Configuration that we will use for this exercise.


Import and setup StockSystemEJB

We will now create our next JSF result page for the Stock Data Page created in Part 2. We will begin by importing an existing EJB JAR file, then create a JSF page that will display the results.

  1. To import an EJB JAR file and make it part of the existing EAR file:
    1. From WebSphere Studio Application Developer (hereafter called Application Developer), select File => Import.
      Figure 1. Application Developer File menu
      Figure 1. Application Developer File menu
    2. Select EJB JAR file, then Next.
      Figure 2. File Import dialog
      Figure 2. File Import dialog
    3. Browse to C:\JSFArticleSeries\Part4\StockSystemEJB.jar. The Project name should be StockSystemEJB. Select the existing EAR File StockSystemEAR. (You must explicitly select the existing EAR; it will default to StockSystemEJBEAR which can be misleading.). Press Finish.
      Figure 3. EJB Import
      Figure 3. EJB Import
    4. Press OK when the Repair Server Configuration dialog displays.
      Figure 4. Repair Server Configuration
      Figure 4. Repair Server Configuration
  2. With the EJB JAR file imported into the existing EAR, we now need to make it visible to the WAR file. We can do this by adding the EJB JAR file to the manifest of the WAR file, which is one of the standard J2EE ways to handle classpath. Application Developer provides a simple way to do this: with one step, it will add the EJB JAR to both the build time and compile time classpath.
    1. Right-click the PersonalTradeJSF Web project from the Project Navigator view and select Properties.
      Figure 5. Project Navigator
      Figure 5. Project Navigator
    2. Select Java JAR Dependencies. In the dialog, check the StockSystemEJB.jar. Make sure that Use EJB JAR is also selected. (As of Version 5.1.1, Application Developer supports the generation of the EJB Client JAR).
      Figure 6. Java JAR Dependencies
      Figure 6. Java JAR Dependencies
    3. Select OK.
  3. In our application, PersonalTradeJSF will access a StockFacadeEJB. The StockFacadeEJB interacts with entity beans to access the current stock data. It is considered a best practice to use EJB references when accessing EJBs. Although the EJB JAR file provides a delegate to hide the details of the EJB client API, it makes use of the resource reference. Since the delegate is called under the context of the Web application, the reference needs to be defined.
    1. From the Project Navigator, open the Web Deployment Descriptor editor using the link right under the PersonalTradeJSF.
      Figure 7. Open Web Deployment Descriptor
      Figure 7. Open Web Deployment Descriptor
    2. Select the References tab on the bottom of the editor.
      Figure 8. References tab
      Figure 8. References tab
    3. Select the EJB Local tab on the References page.
      Figure 9. EJB Local References
      Figure 9. EJB Local References
    4. Select Add under the EJB Local References tab.
      Figure 10. Add EJB Local references
      Figure 10. Add EJB Local references
    5. Make the name of the reference ejb/StockFacade.
      Figure 11. Add ejb/StockFacade
      Figure 11. Add ejb/StockFacade
    6. In the Details section, press the Browse button.
      Figure 12. Details and WebSphere Bindings
      Figure 12. Details and WebSphere Bindings
    7. Select the StockFacade EJB and press OK.
      Figure 13. Select StockFacade EJB
      Figure 13. Select StockFacade EJB
    8. Both the session bean and binding information should be complete.
      Figure 14. Details and WebSphere Bindings
      Figure 14. Details and WebSphere Bindings
    9. The Web application will use the EJB local interface to access the data. The EJB local interface takes the symbol as input and returns an AccessStockQuoteVO. This is a simple JavaBean with getters and setters.
      public interface StockFacadeLocal extends javax.ejb.EJBLocalObject {
         public AccessStockQuoteVO getCurrentStockData(String symbol)
            throws SymbolNotFoundException, 
                   StockException, 
                   InvalidSymbolException;
         ...
      }


    10. The EJB JAR provides a simple Delegate object that hides the complexity of the object. The delegate is a singleton Java object and provides a similar interface.
      public class AccessQuoteDelegate
      {
         private StockFacadeLocal stockFacade;
         public static AccessQuoteDelegate accessQuoteDelegate = null;
         public static AccessQuoteDelegate getAccessQuoteDelegate() throws StockException
         {
            if(accessQuoteDelegate == null)
            { 
               accessQuoteDelegate =  new AccessQuoteDelegate();
            }
            return accessQuoteDelegate;
         }
         private AccessQuoteDelegate() throws StockException 
         {
            InitialContext context;
            try
            {
               context = new InitialContext();
               StockFacadeLocalHome home = (StockFacadeLocalHome)context.lookup("java:comp/env/ejb/StockFacade");
               stockFacade = home.create();
            }
            catch (NamingException e)
            {
               throw new StockException(e.getLocalizedMessage());
            }
            catch (CreateException e)
            {
               throw new StockException(e.getLocalizedMessage());
            }
         }
         public AccessStockQuoteVO getCurrentStockData(String symbol) 
            throws SymbolNotFoundException, StockException, InvalidSymbolException
         {
            return stockFacade.getCurrentStockData(symbol);
         }
      }
      


Create viewStockData.jsp

Now that the EJB project is set up, we can build the Stock Data page that will display the results of calling the StockFacade stockData method.

  1. First, we will to create a new JSF page that will display the results of submitting a Stock Data Request.
    1. In Application Developer, right-click the WebContent folder on the PersonalTradeJSF page and select New => Faces JSP File.
      Figure 15. Create new JSF page
      Figure 15. Create new JSF page
    2. For the File Name, enter viewStockData.jsp and select Create from page template.
      Figure 16. New Faces JSP File
      Figure 16. New Faces JSP File
    3. Ensure that StockPageTemplate.jtpl is selected. Press Finish.
      Figure 17. Page Template File Selection
      Figure 17. Page Template File Selection
  2. We will now use the Visual Palette to add a label.
    1. Select the Output component from the Faces Visual Palette.
      Figure 18. Visual Palette
      Figure 18. Visual Palette
    2. Add the output component to the page. Make the text size 18 and the text value: View Stock Data.
      Figure 19. Add Output to JSP
      Figure 19. Add Output to JSP
  3. The EJB returns a regular Java Bean. We will add this Java Bean as page data.
    1. Go to the Page Data view. Right-click on JSP Scripting and select New => JavaBean.
      Figure 20. Create new JavaBean
      Figure 20. Create new JavaBean
    2. On the Add Managed Beans dialog, select New.
      Figure 21. Add Managed Beans dialog
      Figure 21. Add Managed Beans dialog
    3. Press the Browse... button.
      Figure 22. Create a Managed Bean dialog
      Figure 22. Create a Managed Bean dialog
    4. Look for AccessStockQuoteVO; this is the data returned from invoking the StockFacade Session Bean.
      Figure 23. Class Selection dialog
      Figure 23. Class Selection dialog
    5. For Name, enter stockData, and for Scope select request.
      Figure 24. Create a Managed Bean values
      Figure 24. Create a Managed Bean values
    6. Press OK.
      Figure 25. Add Managed Bean values
      Figure 25. Add Managed Bean values
    7. The stockData is now available for the page.
      Figure 26. Page Data
      Figure 26. Page Data
  4. Now we can drag the stockData bean from the Page Data view onto the JSP page.
    1. Select the stockData object from the Page Data view and drag it onto the JSP under the View Stock Data component, as shown in Figure 27.
      Figure 27. Drag Data Object to JSP
      Figure 27. Drag Data Object to JSP
    2. Select Create output components.
      Figure 28. Select drop action dialog
      Figure 28. Select drop action dialog
    3. The JSP should now contain the JSP elements matching the JavaBean.
      Figure 29. JSP elements
      Figure 29. JSP elements
  5. We need to update the attributes of the output component so that the displays is a bit more user-friendly.
    1. Select anywhere on the JavaBean component. Go to the Attributes dialog and select TABLE, as shown in Figure 30. On the Table tab, enter 0 for the Border.
      Figure 30. Attributes dialog
      Figure 30. Attributes dialog
    2. Select the symbol field title. Change the first letter to be uppercase.
      Figure 31. Select field title
      Figure 31. Select field title
    3. Also, on the attribute section, select Header for each field name cell.
      Figure 32. Cell attributes
      Figure 32. Cell attributes
    4. The header should be bold.
      Figure 33. Header field
      Figure 33. Header field
    5. Change all the other title elements as shown in Figure 34.
      Figure 34. Remaining title elements
      Figure 34. Remaining title elements


Action handling and navigation

With the results page built, we now need to build the Action Handler for the submission page to interact with the EJB. After that, we need to grab the results to configure the appropriate navigation rule. We can use the Quick Edit section of the control to add Server Side Actions to the application.

  1. Add an action to the accessStock.jsp page.
    1. Open the accessStock.jsp page.
      Figure 35. Open accessStock.jsp
      Figure 35. Open accessStock.jsp
    2. Select the Submit Stock Request button.
      Figure 36. Submit Stock Request button in JSP
      Figure 36. Submit Stock Request button in JSP
    3. From the Quick Edit button menu, select Command.
      Figure 37. Quick Edit menu
      Figure 37. Quick Edit menu
    4. The code is provided from the download file. Paste the code from the C:\JSFArticleSeries\Part4\CodeSnippet1.txt into the edit section of the Quick Edit window. The main code segment is in the try block, but some exception capture and error handling is also included:
      • The try block gets an instance of the Delegate and calls the business method (which, in turn, calls the StockFacadeEJB). The AccessStockQuoteVO is returned. We store it under the request scope under the stockData name. This is the name by which viewStockData.jsp is expecting it. (The symbol input is obtained from the request scope.)
        try
        {
           com.deploybook.stock.delegate.AccessQuoteDelegate 
              accessQuote = com.deploybook.stock.delegate.AccessQuoteDelegate.getAccessQuoteDelegate();
           com.deploybook.stock.vo.AccessStockQuoteVO 
              accessQuoteForm = accessQuote.getCurrentStockData((String)requestScope.get("symbol"));
           requestScope.put("stockData",accessQuoteForm);
        }
        


      • If we catch an exception, we add an error method to the button component. The codebehind objects instantiate each component on the page based on the name configured on the attribute. We then return failure. If no navigation is configured to the failure return value, it will return to the same page. We can add an error component linked to the button control.
        catch (com.deploybook.stock.exceptions.StockException e)
        {
           e.printStackTrace(System.err);
           context.addMessage(buttonEx1,
              new javax.faces.application.MessageImpl(
              javax.faces.application.Message.SEVERITY_ERROR,
              "Stock Not found", 
              "Symbol Not Found or invalid"
              ));
           return "failure";
        } catch (com.deploybook.stock.exceptions.SymbolNotFoundException e) {
           e.printStackTrace(System.err);
           context.addMessage(buttonEx1,
              new javax.faces.application.MessageImpl(
              javax.faces.application.Message.SEVERITY_ERROR,
              "Stock Not found", 
           "Symbol Not Found or invalid"
        ));
           return "failure";
        } catch (com.deploybook.trade.exception.InvalidSymbolException e) {
           e.printStackTrace(System.err);
           context.addMessage(buttonEx1,
              new javax.faces.application.MessageImpl(
              javax.faces.application.Message.SEVERITY_ERROR,
              "Stock Not found", 
              "Symbol Not Found or invalid"
              ));
        return "failure";
        }
        


      • If all is successful, we return success. We can then configure navigation.
        return "success";


    5. The Quick Edit dialog should contain the code, as in Figure 38.
      Figure 38. Quick Edit dialog containing code
      Figure 38. Quick Edit dialog containing code
    6. The Java code will be added automatically. You can confirm this by opening accessStock.java.
      Figure 39. Open accessStock.java
      Figure 39. Open accessStock.java

      Figure 40. accessStock.java code
      Figure 40. accessStock.java code
  2. We now need to specify the navigation rule. Rather then having the submission hardcode the result as we did in Part 3, we will specify the action handler that will return the navigation result.
    1. With the button still selected, go to the Attribute view. Select the Navigation tab, then press the Add button.
      Figure 41. Navigation attributes
      Figure 41. Navigation attributes
    2. For the value of Page, select viewStockData.jsp. For Alias, enter success (which is returned by the action handler). For ActionRef, select cb_accessStock.buttonEx1Action.
      Figure 42. Add Navigation Rule dialog
      Figure 42. Add Navigation Rule dialog
    3. We do not need to specify the action result for the control because now the action will control it.
      Figure 43. Navigation attributes added
      Figure 43. Navigation attributes added
  3. Because we store the error as a message for the button component, we need to set up an error component on the submission page.
    1. Under the Faces Component palette, select the Display Error component.
      Figure 44. Visual Palette
      Figure 44. Visual Palette
    2. Drag it onto the JSP between the Access Stock title and the input form.
      Figure 45. Add error component to JSP
      Figure 45. Add error component to JSP
    3. Select the output component then go to the Attribute view. In the For validation errors on section, select the buttonEx1 for the Id field.
      Figure 46. Output component attributes
      Figure 46. Output component attributes


Test the JSF component

Before we can test the application, we need to make a couple of updates to the server configuration. We will then test both the successful and error scenarios.

  1. We need to create an authentication alias and enable CMP support for the generated WDO data source. This will enable the CMP entities in the EJB JAR to use the same data source as the WDO objects.
    1. Go to the Servers view by selecting the Servers tab at the bottom of the Web perspective. Double-click the server to open the Server Configuration editor.
      Figure 47. Open Server Configuration editor
      Figure 47. Open Server Configuration editor
    2. Select the Security tab of the Server Configuration editor.
      Figure 48. Server Configuration editor tabs
      Figure 48. Server Configuration editor tabs
    3. Select Add next to the JAAS Authentication Entries.
      Figure 49. JAAS Authentication Entries
      Figure 49. JAAS Authentication Entries
    4. For alias, enter DBUser. Enter db2admin for the User ID and Password (or enter whatever password you used for creating the database).
      Figure 50. Add new user ID and password
      Figure 50. Add new user ID and password

      Figure 51. JAAS authentication entry added
      Figure 51. JAAS authentication entry added
    5. Go to the Data source perspective.
      Figure 52. Select Data source tab
      Figure 52. Select Data source tab
    6. Under the Server Settings, select the WDO DB2 JDBC Provider, then select the Edit button in the Data source list.
      Figure 53. Server Settings
      Figure 53. Server Settings
    7. Select DBUser for the Container-managed authentication alias and the check box for Use this data source in container managed persistence (CMP).
      Figure 54. Edit data source
      Figure 54. Edit data source
    8. Save and close the server editor.
  2. Now we are ready to run the application:
    1. In the Project Navigator, right-click accessStock.jsp and select Run on Server.
      Figure 55. Run application
      Figure 55. Run application
    2. Select Deploy EJB beans, then Finish.
      Figure 56. Select Tasks dialog
      Figure 56. Select Tasks dialog
    3. Enter IBM for Stock and select Submit Stock Request.
      Figure 57. Test with valid data
      Figure 57. Test with valid data
    4. The result should return as shown in Figure 58.
      Figure 58. Test result successful
      Figure 58. Test result successful
    5. Return to the submission page and enter IBB for the Enter Stock value.
      Figure 59. Test with invalid data
      Figure 59. Test with invalid data
    6. The error should display as shown in Figure 60. (The console should also have a business exception stack trace displayed.)
      Figure 60. Test result failure
      Figure 60. Test result failure
    7. Stop the server.


Conclusion

In this part of the series, we showed how JSF can work with any business layer code of a RAD nature. Specifically, we designed a JSF front end for an existing set of Enterprise JavaBeans. In addition, we used the Quick Edits view to add Action Handling to our JSF application and added error handling as well. In the conclusion of this series, we will write a JSF-based Web service client that shows how JSF can be used in integration scenarios.


Acknowledgement

The author wishes to thank Beverly DeWitt for her contributions to this article.



Download

NameSizeDownload method
JSFArticleSeriesP4.zip12.2 MBFTP|HTTP

Information about download methods


Resources

About the author

Roland Barcia is a Consulting IT Specialist for IBM Software Services for WebSphere in the New York/New Jersey Metro area.

Report abuse help

Report abuse

Thank you. This entry has been flagged for moderator attention.


Report abuse help

Report abuse

Report abuse submission failed. Please try again later.


developerWorks: Sign in


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Select information in your profile (name, country/region, and company) is displayed to the public and will accompany any content you post. You may update your IBM account at any time.

Choose your display name

The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


Rate this article

Comments

static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=14599
ArticleTitle=IBM WebSphere Developer Technical Journal: Developing JSF applications using WebSphere Studio V5.1.1 -- Part 4
publish-date=04142004
author1-email=barcia@us.ibm.com
author1-email-cc=