Tip

Java development methodologies -- Part II

Java Development Methodologies: Part I

Introduction

You have already seen some examples earlier in the series, where I've tried to illustrate how to do something without going into much detail. In this

    Requires Free Membership to View

entry, we will build upon what we know so far and create some examples of the different component types.

Component Types and Examples

  • AbstractPortalComponent
  • DynPage
  • JSPDynPage

AbstractPortalComponent

You have seen the most basic of examples being rendered using the AbstractPortalComponent type in an earlier blog entry in this series. Today we'll create a more involving example. We'll also use one of our examples to showcase some of the UI components that SAP has made available via HTMLB for Java API provided by SAP.

Note: for details on how to do these steps, please refer to my previous blog entry Java Development Methodologies: Part I.

Create a new Portal Project called MyAddressBook:
File > New > Project > Portal Application > Create a Portal Application Project

Create a new Portal Object of type AbstractPortalComponent:
File > New > Other > Portal Application > Create a new Portal Application Object

Choose AbstractPortalComponent from the list of Portal Components:
Name the object NewContacts and use com.democompany.demoapps.myaddressbook as the package name

The following file and the code it contains should be auto-generated for you: NewContacts.java in the src.core directory structure. This is just one of the files that gets created, there are other files, the most important of which is the deployment descriptor, portalapp.xml.

package com.umairsalam.demoapps.myaddressbook; import com.sapportals.portal.prt.component.*; public class NewContacts extends AbstractPortalComponent { public void doContent(IPortalComponentRequest request, IPortalComponentResponse response) { // this is where you'd write your code! } }

Pretty impressive, huh? You ain't seen nothin' yet!

Add the following code snippet within the curly brackets:

  response.write(" <html>< " +
   "<body><<form name='newaddress' action='http://localhost:50000/irj/servlet/prt/portal/prtroot/pcd!3aportal_content!2fcom.umairsalam.demoapps.myaddressbook/submitNewContact' ><" +
   "</head><");
  response.write("<center><<b><<center><Add New Contact Information</center><</b><<br><");
  response.write("<table border='7' bgcolor='eeeeee'>< ");
  response.write("<tr><<td colspan=2><<b>< Contact Form</b>< </td><</tr><");
  response.write("<tr><<td class='urLblStd'><Last Name</td><<td class='urEdf2Whl'><<input class='urEdf2TxtEnbl urEdf2TxtRo' type='text'name='lname' value=''><</td><</tr><");
  response.write("<tr><<td class='urLblStd'><First Name</td><<td class='urEdf2Whl'><<input class='urEdf2TxtEnbl urEdf2TxtRo' type='text'name='fname' value=''><</td><</tr><");
  response.write("<tr><<td class='urLblStd'><Home Phone</td><<td class='urEdf2Whl'><<input class='urEdf2TxtEnbl urEdf2TxtRo' type='text'name='phone1' value=''><</td><</tr><");
  response.write("<tr><<td class='urLblStd'><Cell Phone</td><<td class='urEdf2Whl'><<input class='urEdf2TxtEnbl urEdf2TxtRo' type='text'name='phone2' value=''><</td><</tr><");
  response.write("<tr><<td class='urLblStd'><Work Phone</td><<td class='urEdf2Whl'><<input class='urEdf2TxtEnbl urEdf2TxtRo' type='text'name='phone3' value=''><</td><</tr><");
  response.write("<tr><<td class='urLblStd'><Street Address</td class='urEdf2Whl'><<td><<input class='urEdf2TxtEnbl urEdf2TxtRo' type='text'name='address1' value=''><</td><</tr><");
  response.write("<tr><<td class='urLblStd'><Apartment</td><<td class='urEdf2Whl'><<input class='urEdf2TxtEnbl urEdf2TxtRo' type='text'name='address2' value=''><</td><</tr><");
  response.write("<tr><<td class='urLblStd'><City</td><<td class='urEdf2Whl'><<input class='urEdf2TxtEnbl urEdf2TxtRo' type='text'name='city' value=''><</td><</tr><");
  response.write("<tr><<td class='urLblStd'><State</td><<td class='urEdf2Whl'><<input class='urEdf2TxtEnbl urEdf2TxtRo' type='text'name='state' value=''><</td><</tr><");
  response.write("<tr><<td class='urLblStd'><Zip Code</td><<td class='urEdf2Whl'><<input class='urEdf2TxtEnbl urEdf2TxtRo' type='text'name='zipcode' value=''><</td><</tr><");
  response.write("<tr><<td class='urLblStd'><Country</td><<td class='urEdf2Whl'><<input class='urEdf2TxtEnbl urEdf2TxtRo' type='text'name='country' value=''><</td><</tr><");
  response.write("<tr><<td class='urLblStd'><E-mail</td><<td class='urEdf2Whl'><<input class='urEdf2TxtEnbl urEdf2TxtRo' type='text'name='email' value=''><</td><</tr><");
  response.write("<tr><<td><<input type='submit' value='Search'><</td><<td><<input type='reset' value='Reset'><</td><</tr><</table><</form>< </center><</body><</html><");

Don't worry about the ancient looking cryptic code above. Its only for illustration purposes here. I'd rather you use the JSPDynPage template and write UI code in the JSP page. Our code, when rendered as an iView in the Portal accomplishes the following:

DynPage

Next we'll take a quick look at the DynPage template to see how it differs from the above AbstractPortalComponent format. Also, we'll introduce HTMLB for Java libraries.

Create a new Portal Object of type DynPage:
File > New > Other > Portal Application > Create a new Portal Application Object

Choose DynPage from the list of Portal Components:
Name the object SearchContacts and use com.democompany.demoapps.myaddressbook as the package name

The following file and should be auto-generated for you: SearchContacts.java in the src.core directory structure. Add the following code for some UI elements:

package com.umairsalam.demoapps.myaddressbook;

import com.sapportals.htmlb.page.DynPage;
import com.sapportals.htmlb.page.PageException;
import com.sapportals.portal.htmlb.page.PageProcessorComponent;

import com.sapportals.htmlb.*;
import com.sapportals.htmlb.enum.*;

public class SearchContacts extends PageProcessorComponent {

  public DynPage getPage() {
    return new SearchContactsDynPage();
  }

  public static class SearchContactsDynPage extends DynPage {

    /**
     * Initialization code executed once per user.
     */
    public void doInitialization() {

 // called first, used to create, initialize and setup data
    }

    /**
     * Input handling code. In general called the first 
time with the second page request from the user.
     */
    public void doProcessAfterInput() throws PageException {

 // called after user input, use for event handling
    }

    /**
     * Create output. Called once per request.
     */
    public void doProcessBeforeOutput() throws PageException {
      Form myForm = this.getForm(); // get the form from DynPage

      // create your GUI here....


  Form myForm = this.getForm(); // get the form from DynPage
  GridLayout gl = new GridLayout();

  // FirstName
  Label lbFirstName = new Label("lb_firstname");
  lbFirstName.setText("First Name:");
  InputField inpFirstName = new InputField(FIELD_FIRSTNAME);
  lbFirstName.setLabelFor(inpFirstName);
      
  gl.addComponent(1,1,lbFirstName);
  gl.addComponent(1,2,inpFirstName);

  // LastName
  Label lbLastName = new Label("lb_lastname");
  lbLastName.setText("Last Name:");
  InputField inpLastName = new InputField(FIELD_LASTNAME);
  lbLastName.setLabelFor(inpLastName);
      
  gl.addComponent(2,1,lbLastName);
  gl.addComponent(2,2,inpLastName);


  // eMail
  Label lbEmail = new Label("lb_email");
  lbEmail.setText("Email:");
  InputField inpEmail = new InputField(FIELD_EMAIL);
  lbEmail.setLabelFor(inpEmail);
  gl.addComponent(3,1,lbEmail);
  gl.addComponent(3,2,inpEmail);
  
  
    // DropdownListBox
    Label lbDisplayType = new Label("lb_Province");
    lbDisplayType.setText("Province: ");
  
  DropdownListBox ddl = new DropdownListBox(FIELD_DISPLAYTYPE);
  ddl.setWidth("300");
  ddl.addItem(ALBERTA, "Alberta");
  ddl.addItem(ONTARIO, "Ontario");
  ddl.addItem(BRITISH_COLUMBIA, "British Columbia");
  ddl.addItem(NEW_FOUNDLAND_LABRADOR, "New Foundland & Labrador");
  ddl.addItem(NORTHWEST_TERRITORIES, "Northwest Territories");
  ddl.addItem(NEW_BRUNSWICK, "New Brunswick");
  ddl.addItem(NOVA_SCOTIA, "Nova Scotia");
  ddl.addItem(MANITOBA, "Manitoba");
  ddl.addItem(QUEBEC, "Quebec");
  ddl.addItem(SASKATCHEWAN, "Saskatchewan"); 
  ddl.addItem(YUKON, "Yukon");
  ddl.addItem(PEI, "Prince Edward Island");
  ddl.addItem(NUNAVUT, "Nunavut");
  ddl.setWidth("130");
  ddl.setTooltip("Select Province");
  
  
  lbDisplayType.setLabelFor(ddl);
  gl.addComponent(4,1,lbDisplayType);
  gl.addComponent(4,2, ddl);  
  
    // Button
  Button btn = new Button("submit");    
  
  btn.setText("Submit Details");
  btn.setDesign(ButtonDesign.EMPHASIZED);
  btn.setOnClientClick("javascript:alert('Button was clicked!')");
  gl.addColSpanComponent(5,1,btn,2);
      
  myForm.addComponent(gl);
  myForm.setDefaultButton(btn);

    }
  }
}

A quick glance at the code above shows that the main difference between the simplistic AbstractPortalComponent and DynPage approaches is that there are different methods act as place holders for your code and make it easier to build and understand. However, there is more than meets the eye (I've wanted to use this phrase in my writing for a long while and finally got a chance!): the structure of the application is more flexible and lets you use the HTMLB for Java libraries easily and the three default methods let you break your code down into easily digestible chunks. Even though you can use the HTMLB for Java libraries with AbstractPortalComponent, the DynPage and JSPDynPage approaches make the task for GUI development much easier.

The doInitialization method gets called first. This is an ideal place for creating, initializing and setting up data.

The doProcessAfterInput method gets called whenever the client sends the form to the server or when an event occurs (caused when input is received from the user). So all event handling code should go here.

The doProcessBeforeOutput method gets called before the form is sent to the web client, every time, even when doInitialization is called. Therefore this is the place for the code to build GUI for the iView.

JSPDynPage

Finally, we'll take a look at the JSPDynPage approach for building Java iViews in the Portal. JSPDynPage is by far the most flexible and advanced way of building robust J2EE based iViews.

Create a new Portal Object of type DynPage:
File > New > Other > Portal Application > Create a new Portal Application Object

Choose JSPDynPage from the list of Portal Components.

When you run the wizard to start the JSPDynPage application object, you get the following:

  • JSPDynPage class file
  • JSP file
  • Bean file (optional)

    For brevity, I've left out everything but the three methods I want to point out.

    JSPDynPage Class:

        public void doInitialization(){
          IPortalComponentProfile profile = ((IPortalComponentRequest)
    getRequest()).getComponentContext().getProfile();
          Object o = profile.getValue("myBean");
          if(o==null || !(o instanceof JSPDynPageBean)){
            myBean = new JSPDynPageBean();
            profile.putValue("myBean",myBean);
          } else {
              myBean = (JSPDynPageBean) o;
          }
          // fill your bean with data here...
        }
    
        public void doProcessAfterInput() throws PageException {
    // event handling code goes here
        }
    
        public void doProcessBeforeOutput() throws PageException {
          this.setJspName("jspexample.jsp");
        }

    Bean Class:

    package bean;
    import java.io.Serializable;
    
    public class JSPDynPageBean implements Serializable {
     
     String firstName ="";
     String lastName = "" ;
     String eMail="";
     String phone = "" ;
    
    
    
     /**
      * @return
      */
     public String getEMail() {
      return eMail;
     }
    
     /**
      * @return
      */
     public String getFirstName() {
      return firstName;
     }
    
     /**
      * @return
      */
     public String getLastName() {
      return lastName;
     }
    
     /**
      * @return
      */
     public String getPhone() {
      return phone;
     }
    
     /**
      * @param string
      */
     public void setEMail(String string) {
      eMail = string;
     }
    
     /**
      * @param string
      */
     public void setFirstName(String string) {
      firstName = string;
     }
    
     /**
      * @param string
      */
     public void setLastName(String string) {
      lastName = string;
     }
    
     /**
      * @param string
      */
     public void setPhone(String string) {
      phone = string;
     }
    
    }

    JSP file:

    <%@ taglib uri="tagLib" prefix="hbj" %>
    <jsp:useBean id="myBean" scope="application" class="bean.JSPDynPageBean" />
    <hbj:content id="myContext" >
      <hbj:page title="PageTitle">
       <hbj:form id="myFormId" >
    
       <hbj:group id="TestJspDynPage" 
             design="SAPCOLOR" 
             width="100%" > 
         <hbj:groupBody>
          <hbj:textView
         id="jspdynpageexample"
         design="HEADER3"
         encode="false"
         text="Just some sample text in a text box..."  
       > 
      </hbj:textView>
        </hbj:groupBody> 
     </hbj:group>
    
    
         <hbj:tableView  id="myTableView"
                              model = "myBean.myModel"
                              design = "ALTERNATING"
                              headerVisible = "true"
                              footerVisible = "false"
                              fillUpEmptyRows = "true"
                              navigationMode = "BYLINE"
                              onNavigate = "onNavigation" >
              <%for (int i=1; i <= myTableView.
    getRowCount() ; i++ ){    }  %>
            </hbj:tableView>
    
    <hbj:button
           id="save"
           text="Save"
           width="100"
           onClick="onSaveButtonClicked" 
           design="EMPHASIZED"
           encode="True">
         </hbj:button>
    
    <hbj:button
           id="cancel"
           text="Cancel"
           width="100"
           onClick="onCancelButtonClicked" 
           design="EMPHASIZED"
           encode="True">
         </hbj:button>
    
       </hbj:form>
      </hbj:page>
    </hbj:content>

    Although, there is a lot more code to look at in this example, it is much more flexible than the previous approaches. You'll notice that the same three methods (doInitialization, doProcessAfterInput, doProcessBeforeOutput) are available here as well, however, the initialization is that of the Bean and the GUI is built in the JSP file, which is called by the doProcessBeforeOutput method: which means, you can have additional JSP files such as error pages and other jsp pages that the application might require. The bean is a tool for storing data, models and other business logic.

    Summary

    As you can see, various approaches are available for creating Java based iViews. There is no best approach for everything; it just depends on the task at hand. For example, I wouldn't use a JSPDynPage approach for creating a simple iView to display some text/image where I probably wouldn't need a Bean component.

    Umair Salam is an SAP Enterprise Portal Developer, in the HR area, developing in Java/JSP and SAP's new and exciting Web DynPro technology.


    This content is reposted from the SAP Developer Network.
    Copyright 2006, SAP Developer Network

    SAP Developer Network (SDN) is an active online community where ABAP, Java, .NET, and other cutting-edge technologies converge to form a resource and collaboration channel for SAP developers, consultants, integrators, and business analysts. SDN hosts a technical library, expert blogs, exclusive downloads and code samples, an extensive eLearning catalog, and active, moderated discussion forums. SDN membership is free.

    Want to read more from this author? Click here to read Umair Salam's Weblog. Click here to read more about Java Programming on SDN.



    This was first published in November 2006

  • There are Comments. Add yours.

     
    TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

    REGISTER or login:

    Forgot Password?
    By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
    Sort by: OldestNewest

    Forgot Password?

    No problem! Submit your e-mail address below. We'll send you an email containing your password.

    Your password has been sent to:

    Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.