Developing and Invoking a Servlet from a Portlet using WebSphere Studio

This article demonstrates how to create a servlet and a portlet for your Web application, and then package them into a single Web archive file using WebSphere Studio Application Developer 4.0.3 and the IBM Portal Toolkit plug-in. This articles then describes how to display an HTML form from the portlet code, and how to invoke the servlet from the portlet by passing the user submitted form values.

Sukumar Konduru (konduru@us.ibm.com), Advisory Software Engineer, Developer Technical Support Center, IBM Dallas

Sukumar Konduru is an Advisory Software Engineer at the IBM Dallas, Developer Technical Support Center. He holds an M. S. in Computer Science from the University of Houston. You can reach Sukumar at konduru@us.ibm.com.



19 February 2003

Introduction

IBM ® WebSphere® Portal 4.1.2 for Multiplatforms provides the Portal Toolkit plug-in, which integrates with IBM WebSphere Studio Application Developer, Version 4.0.3 (hereafter called WebSphere Studio). Use WebSphere Studio together with the Portal Toolkit plug-in to create portlets. The Portal Toolkit generates XML files needed to package a portlet application, and generates skeleton code for a basic portlet, MVCPortlet, etc. To debug portlet code, you would need to install WebSphere Portal on WebSphere Application Server Advanced Single Server Edition 4.0.2.

This article demonstrates how to create a servlet and a portlet for your Web application, and then package them into a single Web archive (WAR) file using WebSphere Studio and the Portal Toolkit plug-in. This articles then describes how to display an HTML form from the portlet code, and how to invoke the servlet from the portlet by passing the user-submitted form values. The sample code you will create calculates monthly mortgage payments; you can use the servlet code you develop here for your own servlet development. You will use WebSphere Studio to develop a portlet and a servlet, and then you can run the WAR file on WebSphere Portal installed on WebSphere Application Server to run the WAR file. The article assumes that you have a basic understanding of how to deploy a WAR file on WebSphere Portal, and how to customize page to have the portlet. For details on how to install a WAR file and customize the page to have the portlet, refer to Ron Lynn's article, Hello World - The simplest portlet for WebSphere Portal, Version 4.1.


Prerequisites

  • WebSphere Studio Application Developer, Version 4.0.3
  • WebSphere Portal 4.1 and the Portal Toolkit plug-in

Note: If you want to debug portlet code, you also need to install WebSphere Portal on WebSphere Application Server Advanced Single Server Edition 4.0.2.


Overview of the sample

The sample application demonstrates how to create a portlet to calculate monthly mortgage payments. The portlet displays a form which lets the user submit principal, interest rate, and number of years. Upon submission, the portlet invokes the servlet, and passes values to the servlet using an object of type, RequestDispatcher. The portlet then receives monthly payments from the servlet, and displays the result in the portlet window.


Generating the portlet code

  1. Launch WebSphere Studio.
  2. Select File => New => Other to open the Select wizard.
    Figure 1. Creating a new project
    Screen capture showing File => New => Other selected in WebSphere Studio to create a new project
  3. In the Select page of the New wizard, select Portlet development, and then select Portlet application project on the right.
    Figure 2. Selecting portlet application project
    Screen capture showing the portlet application project selected in the New - Select wizard
  4. Click Next. The Create a Portlet Project wizard opens.
  5. In the Project Name field, enter MortgageCalculator, and in the Enterprise Application project name field, enter MortgageCalculatorEAR.
    Figure 3. Entering a project name
    Screen capture showing a project name entered in the Define the a portlet project wizard
  6. Click Next. The Portlet Selection page of the Create a Portlet Project wizard opens.
  7. Select Basic portlet.
    Figure 4. Selecting portlet type
    Screen capture showing the portlet type selected in the Portlet selection wizard
  8. Click Next. The Basic Portlet Parameters page of the wizard open.
  9. In the Portlet class name field, enter com.ibm.dr.MortgagePortlet.
    Figure 5. Basic portlet parameters
    Screen capture showing the basic portlet parameters in the Basic portlet parameters wizard
  10. Click Finish. The portlet.xml file now opens in WebSphere Studio's Portlet view.
  11. Select Portlet application. In the UID field, enter com.ibm.dr.MortgageCalculatorPortlet.
    Figure 6. Modifying the UID of the portlet application
    Screen capture showing how to modify the UID of the portlet application
  12. Select Concrete portlet application. In the UID field, enter com.ibm.dr.MortgagePortlet.concrete.

    You do not need to change the UIDs of the portlet application and concrete portlet application. However, it is conventional to use fully qualified class names as the UID for portlet applications. In this case, append this fully qualified class name with concrete as the UID for the concrete portlet application.
    Figure 7. Modifying the UID of the concrete portlet application
    Screen capture showing the UID of the concrete portlet application being modified
  13. Expand Concrete portlet application, and select Portlet_1.
  14. In the Description field, enter This portlet calculates mortgage.
  15. In the Short title field, enter Mortgage.
    Figure 8. Defining title and description
    Screen capture showing the title and description being defined
  16. Save the file.

Creating the JSP page to display the form

In this section, you will modify the view.jsp file to display an HTML form. You must encode all variable names of the form with the encodeNameSpace tag element. This HTML form displays text fields for Loan Amount, Mortgage Rate, and Years to Pay.

  1. In WebSphere Studio's Navigator view, expand MortgageCalculator => webApplication => jsp. Delete the html directory because you will not be using this directory here.
    Figure 9. Deleting the html directory
    Screen capture showing the html directory highlighted to be deleted
  2. Click Yes to confirm.
  3. Double-click on view.jsp under the jsp folder to open the file.
  4. Select the Source view.
  5. Replace the contents of view.jsp with the following code, and save the file.
Listing 1. New contents of view.jsp
<%@ taglib uri='/WEB-INF/tld/portlet.tld' prefix='portletAPI'%> 
<portletAPI:init/> 
 
<FORM  ACTION="<portletAPI:createURI/>" METHOD="POST"> 
 
  <TABLE class="Portlet" width="100%" border="0"  
     cellspacing="0" cellpadding="0"> 
    <TR> 
	  <TD width="100%" align="left">Loan Amount:</TD> 
    </TR> 
 
    <TR> 
	  <TD width="100%" align="left"> 
        $<INPUT type="text" name="<portletAPI:encodeNamespace  
           value='loan_amount' />" size="10"> 
      </TD> 
    </TR> 
    <TR> 
	  <TD width="100%" align="left"> 
	  <BR> 
            Mortgage Rate: </TD> 
    </TR> 
    <TR> 
	  <TD width="100%" align="left"> 
        <INPUT type="text" name="<portletAPI:encodeNamespace  
           value='mortgage_rate' />" size="4">% 
      </TD> 
    </TR> 
    <TR> 
	  <TD width="100%" align="left"> 
	  <BR> 
            Years to Pay: </TD> 
    </TR> 
    <TR> 
	  <TD width="100%" align="left"> 
        <INPUT type="text" name="<portletAPI:encodeNamespace  
           value='years_to_pay' />" size="2"> 
      </TD> 
    </TR> 
     </TABLE> 
	<BR> 
	  <INPUT type="submit" name="Save_Button"  
         value="Calculate" size=35> 
</FORM>
Figure 10. Replacing contents of view.jsp
Screen capture showing the contents of view.jsp being replaced

Generating the servlet code

In this section, you will create a servlet using WebSphere Studio. You will modify the doPost() method to extract the values of loan_amount, mortgage_rate, and years_to_pay from the object of type HttpServletRequest. The calculated monthly payment is then displayed.

  1. In the Navigator view, select the MortgageCalcutor project. Click the Create a servlet icon, Screen capture of the Create a servlet icon , in the toolbar. The Create the Servlet Class wizard opens.
  2. In the Servlet Name field, enter MortgageCalculatorServlet, and in the Package field, enter com.ibm.dr.
  3. Click Next.
    Figure 11. Defining the servlet
    Screen capture showing the servlet defined in the Create a servlet class wizard
  4. Click Finish.
  5. Click Yes to confirm.
  6. Edit the MortgageCalculatorServlet.java file.
  7. Enter the following code in the doPost() method:
    Listing 2. Contents of the doPost() method
    PrintWriter pw = response.getWriter(); 
    int loanAmount =  
       Integer.parseInt( (String)request.getAttribute("loan_amount")); 
    float  mortgageRate =  
       Float.parseFloat( (String)request.getAttribute("mortgage_rate")); 
    int  yearsToPay =  
       Integer.parseInt( (String)request.getAttribute("years_to_pay")); 
    int monthsToPay = yearsToPay * 12; 
    float monthlyRate = mortgageRate/(100 *12); 
    double payment = 
       ((loanAmount * Math.pow((1+ monthlyRate),monthsToPay)  
          *monthlyRate))/ 
    (Math.pow((1+ monthlyRate),monthsToPay) -1); 
    java.text.DecimalFormat dfObj = new java.text.DecimalFormat("#.00"); 
    pw.println("Monthly payment is: $" +  
       dfObj.format(payment) + "" );
  8. In the editor, right-click on the on the MortgageCalculatorServlet.java file, and select Organize imports from the context menu. This adds import statements of the packages needed for using classes such as PrintWriter.
  9. Save the file.

Modifying the web.xml file

When installing the WAR file onto WebSphere Portal, make sure that all servlet elements have an id attribute. However, WebSphere Studio does not generate an id attribute when you create a servlet. You need to manually add the id attribute for all servlets in order for the WAR file to install successfully. Execute the following steps to update the web.xml file. Listing 3 illustrates a sample servlet element:

  1. Open the web.xml file.
  2. Select the Source view tab.
  3. Add id="servlet_2" to the servlet element of the MortgageCalculatorServlet.
  4. Save the file.
Listing 3. Sample servlet element
<servlet id="Servlet_2"> 
  <servlet-name>MortgageCalculatorServlet</servlet-name> 
  <display-name>MortgageCalculatorServlet</display-name> 
  <servlet-class>com.ibm.dr.MortgageCalculatorServlet</servlet-class> 
</servlet>

You do not have to add IDs for portlets since Portal Toolkit automatically assigns IDs for the servlet elements of a portlet.


Invoking the servlet from the portlet

In this section, you will modify the portlet's doView() method. You will extract the encoded parameters loan_amount, mortgage_rate, and years_to_pay from the object of type, PortletRequest, and set the parameters into this object as attributes using the setAttributemethod of the HttpServletRequest class. Then, you will invoke the MortgageCalculatorServlet servlet from the portlet using the object of type RequestDispatcher.

  1. Open the MortgagePortlet.java file.
  2. Add the import javax.servlet.ServletException; statement.
  3. Add the following code at the end of the doView() method:
    Listing 4. Contents of the doView() method
    String loanAmount = request.getParameter("loan_amount"); 
    String mortgageRate = request.getParameter("mortgage_rate"); 
    String yearsToPay = request.getParameter("years_to_pay"); 
     
    PrintWriter pw = response.getWriter(); 
    if(loanAmount== null || loanAmount==""|| mortgageRate==null||mortgageRate==""|| 
    yearsToPay==null || yearsToPay== "") 
    	return; 
    request.setAttribute("loan_amount", loanAmount); 
    request.setAttribute("mortgage_rate", mortgageRate); 
    request.setAttribute("years_to_pay", yearsToPay); 
    try{ 
    RequestDispatcher rd=this.getServletContext().getRequestDispatcher 
       ("/MortgageCalculatorServlet"); 
    	rd.include(request,response); 
    }catch(ServletException se){ 
    }
  4. In the editor, right-click on the on the MortgageCalculatorServlet.java file, and select Organize imports from the context menu.
  5. Save the MortgagePortlet.java file.

Exporting the WAR file

  1. In the Navigator view, right-click MortageCalculator, and click Export WAR from the context menu.
  2. In the Where do you want to export resources to? field, enter a directory structure with the WAR file name, for example, D:\sampportlets\mortgageportlet.war.
    Figure 12. Exporting the WAR file
    Screen capture of the WAR Export wizard with the WAR file selected for export
  3. Click Finish.

Displaying the portlet

  1. Install the exported WAR file using Install Portlet.
  2. Create a page and customize it to contain MortgageCalculator portlet.
    Figure 13. The MortgageCalculator portlet
    Screen capture showing the MortgageCalculator portlet displayed in the Web browser
  3. Enter values in the Loan Amount, Mortgage Rate, and Years to Pay fields. Click Calculate.

The monthly payment is now displayed:

Figure 14. Mortgage calculator result
Screen capture showing the Mortgage Calculator result displayed in the Web browser

Tips for using WebSphere Studio to develop portlets

The portlet is only a part of a page, so the portlet's output stream must not contain tags such as, <body>, <html>, etc. When you create a JSP page using WebSphere Studio, it generates all of these HTML tags into the JSP file. To disable this function in WebSphere Studio, complete the following:

  1. From the menu, select Window => Preferences.
  2. Expand Webtools, and select Files.
  3. Uncheck the Insert this DOCTYPE on and Include GENERATOR in HTML source check boxes.
  4. Click OK.
    Figure 15. Preferences window
    Screen capture of the Preferences window

When you assign <portletAPI:createURI> to the action attribute of the form, WebSphere Studio will complain that it is a broken link. To prevent WebSphere Studio from doing this, complete the following:

  1. In the Tasks view, click on the Filter icon Screen capture of the filter icon. The Filter Tasks wizard opens.
  2. Uncheck the Broken Links check box under Problem.
  3. Click OK.
    Figure 16. Filter Tasks window
    Screen capture of the Filter Tasks window

Conclusion

The article demonstrated how to develop portlets and servlets using WebSphere Studio Application Developer and the Portal Toolkit plug-in. If you have existing servlets, you can import them into the portlet project, and then invoke the servlet from the portlet code. If desired, you can install WebSphere Portal on WebSphere Application Server Advanced Single Server Edition to debug the portlets.


Acknowledgments

The author would like to thank Doug Phillips and William Trotman for reviewing the article, and providing valuable suggestions and contributions.

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=13963
ArticleTitle=Developing and Invoking a Servlet from a Portlet using WebSphere Studio
publish-date=02192003