IBM WebSphere Developer Technical Journal: Developing JavaServer Faces portlets using WebSphere Studio and the IBM Portal Toolkit -- Part 1

Creating a JSF portlet EJB client

This three-part article series shows how the latest JavaServer™ Faces and portlet specifications can be used together to rapidly build and assemble Web sites to help achieve your business objectives. Part 1 explains how to build an EJB™ client portlet, and how to package an EJB client JAR file inside your portlet WAR files.

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. He is co-author of the upcoming book: IBM WebSphere: Deployment and Advanced Configuration.


developerWorks Master author level
        2

Sapna Mahwal (smahwal@us.ibm.com), IT Specialist, IBM Software Services for WebSphere

Sapna Mahwal is an IT Specialist for IBM Software Services for WebSphere in the San Francisco Bay area.



23 June 2004

Introduction

Get the products and tools used in this article

If you are a developerWorks subscriber, you have a single user license to use WebSphere® Portal, WebSphere Studio Application Developer, and other DB2®, Lotus®, Rational®, Tivoli®, and WebSphere products -- including the Eclipse-based WebSphere Studio IDE -- to develop, test, evaluate, and demonstrate your applications. If you are not a subscriber, you can subscribe today.

Earlier this year, we demonstrated the capabilities of JavaServer Faces using the WebSphere Studio V5.1.1 preview. With the release of WebSphere Studio V5.1.2, developers can now build JavaServer Faces (JSF) applications based on the final release of the JSF 1.0 specification. In addition, with the latest WebSphere Portal Toolkit, Version 5.0.2.2, developers can now develop JSR 168 Portlets.

The JavaServer Faces implementation in the new version of WebSphere Studio Application Developer gives us the ability to rapidly develop portlets At the portlet level, JSF components can be dragged-and-dropped on to your portlet pages. In addition, WebSphere Portal allows you to quickly and dynamically lay out Web sites made up of several portlets. These two complimentary technologies give developers and Web site designers a powerful combination.

This three-part article series will show how the latest JSF and portlet specifications can be used together to rapidly build and assemble Web sites to help achieve your business objectives. The articles in this three-part series include:

  • Part 1: Creating a JSF portlet EJB client
  • Part 2: Creating a JSF Web service client
  • Part 3: Deploying JSF portlets on WebSphere Portal.

Parts 1 and 2 will show several ways portlets can be built using JSF. Part will show how to deploy the 2 portlets together inside a running WebSphere Portal server.

In Part 1, we will build an EJB client portlet. You will drag-and-drop several JSF components on the page and invoke an existing EJB using JSF event handlers. In addition, you will see how portlets can use the EJB ClientJar wizard to package an EJB client JAR file inside your portlet WAR files.

You can download the materials needed to run this exercise at the end of the article.


Setup database for existing application

Before starting this exercise you will need to create the database that the existing EJB application will use.:

  1. Download the materials and database scripts included with this article, if you have not already done so. Extract the files to c:\ keeping the same folder names.
  2. Create the database:
    1. Open a DB2 Command Window by selecting IBM DB2 => Command Line Tools => Command Window from the Windows® Explorer (Figure 1).
      Figure 1. Open a DB2 Command Window
      Figure 1. Open a DB2 Command Window
    2. Switch to the directory where you extracted the ZIP file to and go to C:\JSFPortletSeries\Part1\DBScript.
    3. Type CreateWSTrade to create the necessary tables. (In these files, we used db2admin/db2admin for the userid/password. If you wish to change this, edit the CreateWSTrade.bat file.)
  3. Verify the database is installed correctly:
    1. From the DB2 Command Window, connect to the database by typing db2 connect to WSTRADE user db2admin using db2admin.
    2. Type db2 select * from STOCKHISTORY. You should get some results back (Figure 2).
      Figure 2. DB2 database results
      Figure 2. DB2 database results
    3. Close the DB2 command window.

Import backend applications and create JSF portlet project

In Part 1, we will set up the projects that we will need. First, we will import an existing EJB project that will be used as the backend application, then create a JSF Portlet (JSR 168) project, and finally, we will generate an EJB client JAR file and add it as a library to the portlet application:

  1. Open WebSphere Studio and import the existing EJB project.
    1. Start WebSphere Studio Application Developer V5.1.2. (If the text box feature is disabled, enable it by setting the -setworkspace parameter on the command line.) Set the directory to C:\JSFPortletLab\workspace, then go to the J2EE perspective.
    2. From the main menu, select File => Import. (Figure 3)
      Figure 3. File Import menu
      Figure 3. File Import menu
    3. From the Import Menu, select EJB JAR and then Next. (Figure 4)
      Figure 4. Import select
      Figure 4. Import select
    4. On the EJB Import dialog, browse to C:\JSFPortletLab and select StockSystemEJB.jar for the EJB JAR file field. Leave StockSystemEJB for the EJB Project and make sure the EAR Project is StockSystemEAR. Press Finish. (Figure 5)
      Figure 5. EJB Import
      Figure 5. EJB Import
  2. We are now ready to create our portlet project:
    1. From the main menu, select File => New => Project.
    2. On the New dialog, select Portlet Development from the left pane and Portlet Project (JSR 168) on the right, then Next.
      Figure 6. Create a new portlet project
      Figure 6. Create a new portlet project
    3. For the Project name, enter JSFStockPortlet, and select Faces portlet (JSR 168) for the type of Portlet. Select Finish.
      Figure 7. Portlet project name and location
      Figure 7. Portlet project name and location
    4. When prompted, switch to the Portlet perspective by pressing Yes (Figure 8).
      Figure 8. Confirm Perspective Switch
      Figure 8. Confirm Perspective Switch
    5. Once the wizard is finished, both the JSFStockPortletView.jsp and the Portlet Deployment Descriptor editor will open in the main editor panel. (Figure 9)
      Figure 9. Portlet Deployment Descriptor editor
      Figure 9. Portlet Deployment Descriptor editor
  3. We will now configure our EJB project so that the portlet application can use it:
    1. From the Project Navigator view, right click the StockSystemEJB project and select EJB Client JAR =' Create EJB Client JAR Project. (Figure 10)
      Figure 10. Project Navigator
      Figure 10. Project Navigator
    2. Leave the default values and press Finish. (Figure 11)
      Figure 11. EJB client Jar creation
      Figure 11. EJB client Jar creation
    3. We have created the EJB Client JAR, so now we need to add it to the library directory of the portlet WAR file. (Remember, you deploy portal applications as WAR files.) Right-click on the portlet in the Project Navigator, then select Properties. (Figure 12)
      Figure 12. Project Navigator
      Figure 12. Project Navigator
    4. Select Web Library Projects and press the Add button on the right of the right of the Properties dialog (Figure 13)
      Figure 13. Web Library Projects
      Figure 13. Web Library Projects
    5. On the Add a Library Project dialog, select Browse, then StockSystemEJBClient, and OK. (Figure 14)
      Figure 14. Add a Library Project
      Figure 14. Add a Library Project
    6. Press OK to close the Add a Library Project dialog.
    7. Press OK to close the Properties dialog.
  4. Finally, we will generate the EJB deployment code. This code can be generated automatically at deployment time, but we will do so manually for this exercise simply by right-clicking StockSystemEAR and selecting Generate Deployment Code. (Figure 15)
    Figure 15. Select Generate Deployment Code
    Figure 15. Select Generate Deployment Code

Create JSF page for portlet

Now that we have both applications set up, we will build our portlet using JSF Visual components. We will also set up all the dynamic data we will need for the page, and write Action Handling Code to call an existing EJB component using the Quick Edit feature of WebSphere Studio.

  1. We will first build the input form using different controls.
    1. Switch to the JSFStockPortletView.jsp. Make sure that you are working within the Design tab. Remove the text Place content here. (Figure 16)
      Figure 16. JSFStockPortletView.jsp
      Figure 16. JSFStockPortletView.jsp
    2. From the Faces Visual Palette, find and select the Output component, as shown in Figure 17.
      Figure 17. Faces Components
      Figure 17. Faces Components
    3. Drag the Output component to the JSF page, as shown in Figure 18.
      Figure 18. Drag Output component to JSF page
      Figure 18. Drag Output component to JSF page
    4. Highlight the output component on the page, then go to the Attributes view, which is on the bottom left corner of the workbench. Click the icon button next to the Properties text box as shown in Figure 19.
      Figure 19. Component attributes
      Figure 19. Component attributes
    5. Change the Font size to 24 and press OK. (Figure 20)
      Figure 20. Add Style
      Figure 20. Add Style
    6. For the Value field, enter Access Stock Data. (Figure 21)
      Figure 21. Component attributes
      Figure 21. Component attributes
    7. The resulting page should look like Figure 22.
      Figure 22. JSF result page
      Figure 22. JSF result page
    8. Next, select Panel-Group Box from the Visual Palette (Figure 23) and drag it on to the page under the output control.
      Figure 23. Faces Components
      Figure 23. Faces Components
    9. The Select Type dialog will display. With this Panel control, you can organize various controls in different ways. Select the List control (Figure 24) and see the result in Figure 25.
      Figure 24. Select type of component
      Figure 24. Select type of component
      Figure 25. JSF result page
      Figure 25. JSF result page
    10. Next, drag another output control inside the Panel. (Figure 26)
      Figure 26. Drag in another Output control
      Figure 26. Drag in another Output control
    11. Select the Output control, and type Enter Symbol: in the text box for the Value attribute (Figure 27).
      Figure 27. Component attributes
      Figure 27. Component attributes
    12. Find the Input control in the Visual Palette (Figure 28) and drag it inside the Panel next to the Enter Symbol: output label. Make sure that the input control is inside the panel; you can tell by where the cursor is positioned, as in Figure 29.
      Figure 28. Faces Components
      Figure 28. Faces Components
      Figure 29. Drag in Input control
      Figure 29. Drag in Input control
    13. The control should look similar to Figure 30. (This is a simple panel. Complex pages can be built by combining various panels).
      Figure 30. Sample panel
      Figure 30. Sample panel
    14. Find the Command-Button control on the Visual Palette (Figure 31) and drag and drop it below (outside) the Panel.
      Figure 31. Faces Components
      Figure 31. Faces Components
    15. Highlight the button control on the page, go to the Attribute view, and select the Format tab. Enter Get Stock Data in the Label text box.
      Figure 32. Component attributes
      Figure 32. Component attributes
    16. The input section of the form is complete. (Figure 33)
      Figure 33. Input section of form
      Figure 33. Input section of form
  2. Now, we need to bind the input to some input data. To add data to the page, we will use the Page Data view. Page Data enables us to bind data on the server side. We can also bind controls to client side JavaScript using the Client Data Tab.
    1. Locate the Page Data view on the left-center side of the workbench. Select the Page Data tab, then right-click the requestScope item under the JSP™ scripting. and select Add Request Scope Variable.
      Figure 34. Page Data view
      Figure 34. Page Data view
    2. For the variable name, enter symbol. For the Type, enter java.lang.String.
      Figure 35. Add Request Scope Variable
      Figure 35. Add Request Scope Variable
    3. The Page Data View should now have the symbol variable under requestScope.
      Figure 36. Page Data view
      Figure 36. Page Data view
    4. All we need to do now is drag the request scope variable from the Page Data view right to the Input control. (Figure 37)
      Figure 37. Drag request scope variable to Input control
      Figure 37. Drag request scope variable to Input control
  3. Now we are ready to create the output section of the JSF Page. We will use the JavaBean data control to build a data grid.
    1. Right click on JSP Scripting in the Page Data section, and select New => JavaBean.
      Figure 38. Page Data view
      Figure 38. Page Data view
    2. On the Select JavaBean dialog, select Add new JavaBean.
    3. For the Name, enter stockData. Select the icon button next to the Class text box, select AccessStockQuoteVO from the Matching types list, and press OK. (Figure 39)
      Figure 39. Class Selection
      Figure 39. Class Selection
    4. Check Make this JavaBean reusable, and select session for Scope. Press Finish.
      Figure 40. Select JavaBean
      Figure 40. Select JavaBean
    5. The stockData bean should now be visible in the Page Data view, as shown in Figure 41.
      Figure 41. Page Data view
      Figure 41. Page Data view
  4. We will now add our JavaBean to the page as an output control simply by dragging it from the Page Data view onto the JSP. We will then use the Attribute view to configure the output component.
    1. From the Page Data view, select the stockData JavaBean and drag it onto the page under the Input Form, as shown in Figure 42.
      Figure 42. Add new controls
      Figure 42. Add new controls
    2. The Insert JavaBean wizard will display. Be sure Displaying fields is selected, and then order the elements as shown in Figure 43.
      Figure 43. Configure Data Controls
      Figure 43. Configure Data Controls
    3. When completed, the Data Control will be displayed as shown in Figure 44.
      Figure 44. Data Control in JSF
      Figure 44. Data Control in JSF
    4. Next, select the Symbol label and go to the Attributes view.
      Figure 45. Select label
      Figure 45. Select label
    5. Ensure the Cell tab is selected, then select Header for Cell type. (Figure 46)
      Figure 46. Cell attributes
      Figure 46. Cell attributes
    6. Repeat the above steps for each label. (Figure 47)
      Figure 47. Data labels
      Figure 47. Data labels
  5. Now that we have bound the output data, we will add some action handling code. This code will call an existing EJB component that will return the AccessStockVO object, which we will store in the session scope where our data grid component expects.
    1. Select the Get Stock Data command button from the JSF page. (Figure 48)
      Figure 48. JSF page
      Figure 48. JSF page
    2. Refer to the QuickEdit view on the bottom of the page (Figure 49)
      Figure 49. Quick Edit
      Figure 49. Quick Edit
    3. The code that will invoke the EJB component and store the data in the session scope is shown below. You can either type it (and use Code Assist) or paste it from C:\JSFPortletSeries\Part1\CodeSnippet.txt into the Quick Edit panel.

      // Type Java code to handle command event here
      // Note, this code must return an object of type String (or null)
      		
      InitialContext ctx;
      try {
      	ctx = new InitialContext();
      
      	StockFacadeHome facadeHome = 
      (StockFacadeHome)PortableRemoteObject.narrow(ctx.lookup("java:comp/env/
      ejb/StockFacade"),StockFacadeHome.class);
      	StockFacade stockFacade = facadeHome.create();
      	AccessStockQuoteVO quoteVO = null;
      	quoteVO = 
      stockFacade.getCurrentStockData((String)requestScope.get("symbol"));
      	setStockData(quoteVO);
      	sessionScope.put("stockData",quoteVO);
      	return "success";
      } catch (Exception e) {
      	AccessStockQuoteVO quoteVO = new AccessStockQuoteVO();
      	e.printStackTrace();
      	sessionScope.put("stockQuote",quoteVO);
      	facesContext.addMessage("messages1",
      			 new FacesMessage(
      			 FacesMessage.SEVERITY_ERROR,
      			 "Stock Not found", 
      			 "Symbol Not Found or invalid"
      			));
      	return "failure";
      }
    4. In Quick Edit, the code should appear as shown in Figure 50.
      Figure 50. Code displayed in Quick Edit
      Figure 50. Code displayed in Quick Edit
    5. If you paste the code from the included code snippet, you will be missing imports. You will have to open the underlying Java™ file to add the imports yourself. From the Project Navigator view, expand JSFStockPortlet => Java Resources => servercode => JSFStockPortletView.java. This is the underlying Java object that controls the objects behind the JSP. Right-click anywhere in the Java Editor and select Source => Organize Imports. (Figure 51)
      Figure 51. Organize Imports
      Figure 51. Organize Imports
    6. You may get a pop-up window where you have to select a type to import. If so, select javax.rim.PortableRemoteObject as shown in Figure 52.
      Figure 52. Organize Imports dialog
      Figure 52. Organize Imports dialog
    7. The errors should now be gone. Save and close JSFStockPortletView.java.
      Figure 53. JSF preview
      Figure 53. JSF preview
  6. Your JSP is now fully developed with all the required functionality we require at this point. Save the JSP file. You can select the Preview tab to get an idea of what it will look like in a browser when deployed (Figure 53). When you are finished, close the JSP and the deployment descriptor.

Test your portlet using the WebSphere Portal V5 test environment

With our portlet built, we are ready to test it inside the WebSphere Portlet test environment. We will automatically create the test environment and quickly bring up the portlet. However, our EJB application needs to be added to the configuration first. We will add our necessary configuration to the server so that the EJB application can access DB2.

  1. Add a reference to the EJB in the web.xml file.
    1. From the Project Navigator view, double-click the Web Deployment Descriptor editor. (Figure 54)
      Figure 54. Project Navigator view
      Figure 54. Project Navigator view
    2. Select the References tab, then the EJB tab (Figure 55). Because the EJB project is in a different EAR, we need to type in the classes. Enter the following values, as shown in Figure 55:
      • JNDI Name: ejb/StockFacade
      • Type: Session
      • Home: com.deploybook.stock.ejb.StockFacadeHome
      • Remote: com.deploybook.stock.ejb.StockFacade
      Save and close the Web deployment descriptor editor.
      Figure 55. EJB References
      Figure 55. EJB References
    3. We are now ready to run our portlet. Right-click the JSFStockPortlet and select Run on Server. (Figure 56)
      Figure 56. Run on Server
      Figure 56. Run on Server
    4. After the server starts, the portlet will render successfully (Figure 57). However, if you try to execute the function, you will not get results because we have not deployed the EJB application.
      Figure 57. Rendered portlet
      Figure 57. Rendered portlet
  2. We will now add the EJB application to the server, along with a data source as well.
    1. From the bottom set of views, select the Server tab. Right-click on the WebSphere v5 Portal Test Environment and select Add and Remove Projects.
      Figure 58. Add and remove projects
      Figure 58. Add and remove projects
    2. Select StockSystemEAR, press the Add button, then Finish. (Figure 59)
      Figure 59. Add and Remove Projects dialog
      Figure 59. Add and Remove Projects dialog
    3. Double-click the server to open the Configuration editor.
      Figure 60. Select server for configuration
      Figure 60. Select server for configuration
    4. Go to the Environment tab and Add the following Variable (Figure 61):
      • Name: DB2UNIVERSAL_JDBC_DRIVER_PATH
      • Value: C:/Progra~1/IBM/SQLLIB/java
      Figure 61. Substitution Variables
      Figure 61. Substitution Variables
    5. Go to the Security tab and Add the following security alias (Figure 62):
      • Alias: DB2Alias
      • User ID: db2admin
      • Password: db2admin
      Figure 62. JAAS Authentication Entries
      Figure 62. JAAS Authentication Entries
    6. Next, on the Security tab, configure a JDBC™ provider. Under the Server Settings click Add next to the JDBC Provider list (Figure 63).
      Figure 63. Data sources
      Figure 63. Data sources
    7. Select IBM DB2 for the Database type, and select DB2 Universal JDBC Driver Provider for the JDBC provider type (Figure 64). Select Next.
      Figure 64. Create a JDBC Provider
      Figure 64. Create a JDBC Provider
    8. Enter DB2 for Name, then select the Add External JARs button and browse to C:\Progam Files\IBM\SQLLIB. (Figure 65)
      Figure 65. Select JDBC provider type
      Figure 65. Select JDBC provider type
    9. Select Common.jar and sqlj.zip. Select Open and OK. ( )
      Figure 66. Select JAR file
      Figure 66. Select JAR file
    10. Add the data source by selecting the Add button under the Data Source section. (Figure 67)
      Figure 67. Server settings
      Figure 67. Server settings
    11. On the Create a Data Source dialog, select DB2 Universal JDBC Driver Provider.
      Figure 68. Select JDBC provider type
      Figure 68. Select JDBC provider type
    12. Enter or select the following values (Figure 69):
      • Name: WSTRADE
      • JNDI name: jdbc/WSTRADE
      • Data source helper class name: com.ibm.websphere.rsadapter.DB2UniversalDataStoreHelper
      • Container-managed authentication alias: DB2Alias
      • Check Use the data source in container managed persistence (CMP)
      Select Next.
      Figure 69. Modify Data Source
      Figure 69. Modify Data Source
    13. Under Resource Properties, select databaseName and enter a Value of WSTRADE (Figure 70).
      Figure 70. Create resource properties for databaseName
      Figure 70. Create resource properties for databaseName
    14. Select driverType and enter a Value of 2.
      Figure 71. Create resource properties for driverType
      Figure 71. Create resource properties for driverType
    15. Select enableSQLJ and enter a Value of false. Select Finish.
      Figure 72. Create resource properties for enableSQLJ
      Figure 72. Create resource properties for enableSQLJ
    16. Close the Server Configuration editor and Save. From the Server view, right-click the server and select Restart.
      Figure 73. Restart server
      Figure 73. Restart server
    17. Go the Project view. Right-click the JSFStockPortlet project and select Run On Server.
      Figure 74. Run JSFStockPortlet
      Figure 74. Run JSFStockPortlet
    18. The portlet should re-render, similar to Figure 73. Enter IBM as the value for the stock Symbol field, then select Get Stock Data. The resulting data should be populated as shown in Figure 76.
      Figure 75. JSFStockPortlet
      Figure 75. JSFStockPortlet
      Figure 76. JSFStockPortlet results
      Figure 76. JSFStockPortlet results
    19. Close the browser and stop the server.

Conclusion

In this first part of this article series, we illustrated how you can build JavaServer Faces portlets that follow the JSR 168 Portlet specification, and how JSF can be used to rapidly develop your Web pages. In Part 2, we will continue this exercise by building a JSF portlet Web service client.


Download

DescriptionNameSize
Code sampleJSFPortletSeriesPart1.zip  ( HTTP | FTP )172 KB

Resources

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


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. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

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.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

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

 


All information submitted is secure.

Dig deeper into WebSphere on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=WebSphere
ArticleID=13477
ArticleTitle=IBM WebSphere Developer Technical Journal: Developing JavaServer Faces portlets using WebSphere Studio and the IBM Portal Toolkit -- Part 1
publish-date=06232004