11.2 Sample scenario

 < Day Day Up > 

This section provides a sample scenario for creating a sample portlet project that uses the JDBC interface to interact with relational database back end systems. You will create, deploy and run this portlet application. This sample scenario will allow you understand the techniques used to develop portlets that retrieve information from databases using JDBC.

The development workstation has already been created for you and its components can be seen in Figure 11-12.

Figure 11-12. Development workstation

graphics/11fig12.gif

11.2.1 Overview

In this section, you will review and understand the sample scenario. You will create a sample portlet based on a Basic portlet type. You will then import the code to use JDBC to interact with databases. In this sample scenario, it is assumed that the database has already been created and populated .

This example shows how the JDBC interface is used to read information from a Cloudscape sample table. In your portlet Edit mode, you will provide the information needed to establish a connection with the database in order to retrieve the content in View mode. The sample scenario is illustrated in Figure 11-13 on page 354.

Figure 11-13. JDBC scenario

graphics/11fig13.gif

The sequence flow for this sample scenario is as follows :

  1. Initially, the doView method is executed.

  2. A JSP is invoked in View mode to render the initial screen containing a welcome message telling the user to enter the database inquiry values in Edit mode.

  3. The user clicks Edit to go into Edit mode.

  4. The Edit mode method executes and invokes a JSP (include).

  5. The JSP renders the form.

  6. The user enters the database name , user ID, password and SQL statement.

    Note : A user ID and password have not been implemented for this version of Cloudscape, therefore any user ID and password can be used.

  7. The user submits the request (post) to the previous mode (View mode). An action event is generated.

  8. The actionPerformed() method executes and the following processes take place:

    1. The database, user ID, password, and SQL statement are extracted and sent to the JDBCPortletResults Bean.

    2. A connection object is created.

    3. A DBResults object is created. This object encapsulates the database inquiry.

    4. Database Utilities (another bean) is invoked to execute the actual database inquiry.

    5. Results are stored as a String in the request object.

  9. The doView method executes again:

    1. Results are obtained in View mode.

    2. Results are rendered directly in View mode.

11.2.2 Creating HRPortlet

The portlet will be created based on a Basic portlet type using the wizard. In this section you create a portlet application with name HRPortlet . The portlet application will also be published and executed in the Portal Test Environment.

  1. If not already running, start the IBM WebSphere Studio Site Developer and click Start -> Programs -> IBM WebSphere Studio -> Site Developer 5.0 .

  2. Select File -> New -> Portlet Application Project .

    Note : If you do not see this option, select File -> New -> Other and then Portlet Development and Portlet Application Project .

    Figure 11-14. Starting creation of Portlet project

    graphics/11fig14.gif

  3. In Define Portlet Project, enter HRPortlet for the project name. Click Next .

    Figure 11-15. Define the Portlet Project

    graphics/11fig15.jpg

  4. In the J2EE Settings Page, click Next to accept default values.

    Figure 11-16. J2EE Settings Page

    graphics/11fig16.jpg

  5. In Portlet Settings, check Change code generation options and enter HRPortlet for the Class prefix. Click Finish to generate the framework for your project.

    Figure 11-17. Portlet Settings

    graphics/11fig17.jpg

  6. If you have any portlets in the DefaultEAR project, remove them at this time. For example:

    1. Open the DefaultEAR / META-INF folder.

    2. Double-click om application.xml file.

    3. Select Module .

    4. Remove all WAR modules except for HRPortlet.

    5. In the workspace, click File -> Save All .

Figure 11-18. Removing a WAR module

graphics/11fig18.jpg

11.2.3 Importing the WAR file

A WAR file is provided for this sample scenario. By importing this WAR file into your project, you will replace the original files previously created by the wizard. For example:

  • HRPortlet.java (Portlet class)

  • HRPortletSessionBean.java (Session bean)

  • HRPortletEditBean.java (Bean)

  • HRPortletEdit.jsp (Edit Mode)

  • HRPortletView.jsp (View Mode)

  • portlet.xml (Portlet deployment descriptor)

  • web.xml (Web deployment descriptor)

  • A new class SQLUtilities.java (Utility) to set the DBSelect properties values and create methods to execute SQL statements

  • A new class SQLUtilitiesRow.java (Utility) to retrieve each row of the result set

  • A new class HRPortletViewBean.java (Bean) to store the DBResult object

Follow these steps to import the WAR file:

  1. Import the WAR file by selecting File -> Import .

    Figure 11-19. Importing a WAR file

    graphics/11fig19.gif

  2. Select WAR file and click Next .

    Figure 11-20. Select WAR file

    graphics/11fig20.jpg

  3. In the Import Resources from a WAR file window, enter the following information:

    1. WAR file: browse to C:\LabFiles\JDBC\HR\HRPortlet.war

      Note : The sample scenario included in this chapter requires that you download the sample code available as additional materials. See Appendix C, "Additional material" on page 543.

    2. Web project: select Existing . In the box that pops up, select HRPortlet and click OK .

    3. Context root: this will change to /HRPortlet .

    4. Select in Options: Overwrite existent resources without warning .

    Figure 11-21. Importing the provided WAR file

    graphics/11fig21.jpg

  4. Click Finish .

11.2.4 Reviewing the portlet code

In this section, you will review the portlet code used in this sample scenario. For example, to view the source code to HRPortlet.java, double-click the file name. This file is located in the /Java Source/hrportlet/ folder.

  1. The actionPerformed() method in this portlet does the following (see Example 11-1) when an edit action occurs.

    1. It gets the parameters (database, user ID, password and SQL statement) from the request (PortletRequest).

    2. It sets these values in the HRPortletSessionBean.java bean.

    Example 11-1. HRPortlet.java - actionPerformed() method
     .....       // ActionEvent handler       String actionString = event.getActionString();       // Add action string handler here       PortletRequest request = event.getRequest();       HRPortletSessionBean sessionBean = getSessionBean(request);  if (EDIT_ACTION.equals(actionString)) {   String dbname = (String) request.getParameter("dbname")  ;  String userid = (String) request.getParameter("userid")  ;  String password = (String) request.getParameter("password")  ;  String sqlstring = (String) request.getParameter("sqlstring")  ;  sessionBean.setDbName(dbname)  ;  sessionBean.setUserId(userid)  ;  sessionBean.setPassword(password)  ;  sessionBean.setSqlString(sqlstring)  ;  }  if (FORM_ACTION.equals(actionString)) {          // Set form text in the session bean          sessionBean.setFormText(request.getParameter(TEXT));       }    } ..... 
  2. The doEdit() method in the portlet does the following:

    1. It creates an instance of HRPorltetEditBean bean.

    2. It adds the action which will be executed when the form is submitted and sets this value in the edit mode bean.

    3. When the database, user ID, password and SQL statement values exist for the session, it will also store these values in the edit mode bean.

    4. The edit mode bean is passed in the request to the HRPortletEdit.jsp.

    Example 11-2. HRPortlet.java - doEdit() method
     .....       HRPortletEditBean editBean = new HRPortletEditBean();       PortletURI formActionURI = response.createReturnURI();       formActionURI.addAction(EDIT_ACTION);       editBean.setFormActionURI(formActionURI.toString());       HRPortletSessionBean sessionBean = getSessionBean(request);       String sqlstring = sessionBean.getSqlString();       if (sqlstring != null) {          String dbname = sessionBean.getDbName();          String userid = sessionBean.getUserId();          String password = sessionBean.getPassword();          editBean.setDbname(dbname);          editBean.setPassword(password);          editBean.setUserid(userid);          editBean.setSqlstring(sqlstring);       }       request.setAttribute(EDIT_BEAN, editBean);       // Invoke the JSP to render       getPortletConfig().getContext().include(EDIT_JSP + getJspExtension(request),          request, response); ..... 
  3. The doView() method does the following:

    1. It checks to see whether there is a HRPortletSessionBean in the session. The first time this method is invoked, the session bean will be null.

    2. If there is an HRPortletSessionBean in session, it gets the database, user ID, password and SQL sentence values stored in it and creates an instance of HRPortletViewBean.

    3. The execute() method of SQLUtilities class is called to execute the SQL statement and the result is stored in the view mode bean by calling populateData() method in the SQLUtilities class.

    4. The view mode bean is passed in the request to HRPortletView.jsp.

    Example 11-3. HRPortlet.java - doView() method
     .....       // Check if portlet session exists       HRPortletSessionBean sessionBean = getSessionBean(request);       if (sessionBean == null) {          response.getWriter().println("<b>NO PORTLET SESSION YET</b>");          return;       }  String sqlstring = sessionBean.getSqlString()  ;  if (sqlstring != null && !sqlstring.equals("")) {   String dbname = sessionBean.getDbName()  ;  String userid = sessionBean.getUserId()  ;  String password = sessionBean.getPassword()  ;          // Make a view mode bean          HRPortletViewBean viewBean = new HRPortletViewBean();  SQLUtilities sqlUtility = new SQLUtilities()  ;  try {   sqlUtility.execute(userid, password, dbname, sqlstring)  ;  } catch (SQLException e) {   e.printStackTrace()  ;  }   sqlUtility.populateData(viewBean)  ;          request.setAttribute(VIEW_BEAN, viewBean);          // Set actionURI in the view mode bean          PortletURI formActionURI = response.createURI();          formActionURI.addAction(FORM_ACTION);          viewBean.setFormActionURI(formActionURI.toString());       }       // Invoke the JSP to render       getPortletConfig().getContext().include(VIEW_JSP + getJspExtension(request),          request, response); ..... 
  4. The HRPortletEdit.jsp is used to prompt for the database, user ID, password and SQL statement parameters. Double-click this file (located in /Web Content/hrportlet/jsp/html/ folder) to view its source code.

    1. Notice that the database name, user ID, password and SQL fields all have the HTML tag value="<%=editBean.getXXX()%> ". This allows the JSP to display the persistent data stored in the bean.

    Example 11-4. HRPortletEdit.jsp (Edit mode sample code)
     ..... <% HRPortletEditBean editBean = (HRPortletEditBean)portletRequest.getAttribute("hrportlet.HRPortletEditBean"); %> <HTML> <BODY> <h4>Complete with your database information and click Submit</h4> <FORM method="post" action="<portletAPI:createReturnURI><portletAPI:URIAction name='<%=editBean.getFormActionURI()%>'/></portletAPI:createReturnURI>""> <TABLE border="0">    <TBODY>       <TR>          <TD>          <TABLE border="0">             <TBODY>                <TR>                   <TD>Database :</TD>                   <TD><INPUT type="text"  value="<%=editBean.getDbname()  %>"                      name='<portletAPI:encodeNamespace value="dbname"/>' size="20"></TD>                 </TR>                 <TR> ..... 
  5. Once the database parameters are collected, the request is processed by the actionPerformed() and doView() methods. The results are displayed by HRPortletView.jsp. Double-click this file to view its source code.

    1. This JSP tests to see whether there is a HRPortletViewBean.java bean in the request. If there isn't then displays a message to go to Edit mode and configure and SQL statement. If the bean exists then the results of the query are displayed.

    Example 11-5. HRPortletView.jsp (View mode sample code)
     ..... <%    HRPortletViewBean viewBean = (HRPortletViewBean)portletRequest.getAttribute(HRPortlet.VIEW_BEAN); %> <% if (viewBean == null) { %> <HTML> <BODY> <B>This is the JDBC Sample Portlet. Go to Edit mode and configure a SQL query</B> <% } else {    com.ibm.db.beans.DBSelect results = viewBean.getResultFromDatabase(); %> ..... 
  6. The classes SQLUtilities.java and SQLUtilitiesRow.java have been generated in the data perspective. In the data perspective, you can create a connection to database, import the tables, create SQL statements and generate Java beans for the statements. These classes contain the methods to execute and retrieve information from database. The execute() method is called by the doView() method of HRPortlet.java when there is a statement in the session and the information retrieved is stored in the view mode bean by calling the populateData() method of SQLUtilities.java.

Example 11-6. SQLUtilities.java
 public void execute(String userid,String password,  String url,String   command  )       throws SQLException {       try {  select.setUrl(url)  ;  select.setCommand(command)  ;          select.setUsername(userid);          select.setPassword(password);          select.execute();       }       // Free resources of select object.       finally {          select.close();       }    }  public void populateData(HRPortletViewBean viewBean) {   viewBean.setResultFromDatabase(select)  ;  }  

11.2.5 Running the HRPortlet application

  1. Before you run the portlet, run the batch file to populate the test database to be used in this sample scenario. Click c:\LabFiles\Cloudscape\CreateCloudTable.bat to do this.

    Note : The sample scenario included in this chapter requires that you download the sample code available as additional materials. See Appendix C, "Additional material" on page 543.

    Figure 11-22. Populating the test database

    graphics/11fig22.jpg

  2. Run the HRPortlet portlet application by right-clicking HRPortlet in the Navigator panel and selecting Run on server . Wait for Portal to start and run your portlet.

    Note : Click OK if you are prompted to use the Test Environment.

  3. The portlet will run and you will see it in the built-in browser.

    The View mode is shown with a message indicating that you have to provide an SQL query; you will also need to switch the portlet into Edit mode (as indicated in Figure 11-23) so you can enter these values.

    Figure 11-23. HRPortlet in View mode before query

    graphics/11fig23.jpg

  4. When in Edit mode, the JSP for this mode renders the form requesting the database parameters.

  5. For the first example, enter the following information and select Submit :

    - Database: jdbc:db2j:C:\LabFiles\Cloudscape\WSSAMPLE

    - Note : The sample scenario included in this chapter requires that you download the sample code available as additional materials. See Appendix C, "Additional material" on page 543.

    - User: db2admin

    - Password: db2admin

    - SQL statement: select * from jobs

    Figure 11-24. HRPortlet portlet in Edit mode

    graphics/11fig24.jpg

  6. Clicking Submit generates a createReturnURI and the portlet will return to View mode showing the results of your query against the WSSAMPLE database.

    Figure 11-25. HRPortlet in View mode with the query results in View mode

    graphics/11fig25.jpg

  7. Enter Edit mode again. Notice that the database name, user ID, password and SQL statement which were stored in Session are persistent.

    Figure 11-26. Persistence of data

    graphics/11fig26.jpg

  8. Enter a new query, for example select * from survey , and click Submit . You will be presented with the results of your new query.

Figure 11-27. Results of the second query

graphics/11fig27.jpg

 < Day Day Up > 


IBM WebSphere Portal V5 A Guide for Portlet Application Development
IBM Websphere Portal V5: A Guide for Portlet Application Development
ISBN: 0738498513
EAN: 2147483647
Year: 2004
Pages: 148

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net