You are on page 1of 41

Build dynamic Web sites

Using IBM Rational Application Developer

Skill Level: Introductory

Ron Ben-Natan (rbennata@hotmail.com)


Freelance writer

24 Mar 2005

This tutorial shows you how to use IBM Rational Application Developer V6.0 to build
dynamic Web sites. The tutorial walks you through a simple example that uses Java
servlets and JavaServer Pages to implement a simple messaging center. You'll learn
how to use Rational Application Developer to develop a dynamic Web site, then test
and debug your code.

Section 1. Before you start

About this tutorial


This tutorial shows you how to develop a Web application using JavaTM servlets and
JavaServer Pages (JSP) files, how to organize code in a project within IBM®
Rational® Application Developer Version 6.0, and how to use Java servlets and JSP
files to generate dynamic HTML content. It also shows you how to test and debug
code within Rational Application Developer and how to package a Web application
for deployment on a computer running IBM WebSphere® Application Server.

Rational Application Developer Version 6.0 is a very rich Integrated Development


Environment (IDE) that supports multiple Java frameworks for building Web user
interfaces (UIs) and Java applications. This includes JavaServer Faces (JSF),
Struts, and Service Data Objects (SDOs). In this tutorial, the most basic Java Web
technologies -- servlets and JSP files are used. For more information about JSF,

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 1 of 41
developerWorks® ibm.com/developerWorks

Struts, and SDOs within Rational Application Developer, refer to Resources.

This tutorial employs a simple application -- the messaging center. Using the
messaging center, users can log on and view messages that have been sent to
them. They can also send messages to any other user who has access to the
messaging center. Using Rational Application Developer in conjunction with Java,
Java servlet, and JSP technologies, you will build the following elements:

• User and Message Java classes


• Two JSP forms: login.jsp and messageCenter.jsp
• Two servlets: MessageCenterLoginServlet and AddMessageServlet

Prerequisites
This tutorial is written for developers and Web site builders who quickly want to learn
how to use Rational Application Developer to build dynamic Web sites. This tutorial
assumes that you have a basic knowledge of HTML and Java technology. Because
Rational Application Developer is easy to use, the tutorial is easy to follow, even if
you're new to HTML and Java technology.

Although downloading Rational Application Developer Version 6.0 is not a


prerequisite for completing this tutorial, it does make the tutorial easier to follow. To
run the examples in this tutorial, you need the following software:

• Rational Application Developer Version 6.0: You can download the


latest trial version of Rational Application Developer at no charge.
In addition, you can download a trial version of WebSphere Application Server
Version 6.0. Rational Application Developer Version 6 comes with the WebSphere
Application Server Version 6.0 test environment, so you don't have to use a separate
WebSphere Application Server machine. However, if you also want to try
WebSphere Application Server, you can download it at no charge:

• WebSphere Application Server Version 6.0. Download the latest trial


version of WebSphere Application Server.

Section 2. What's new in version 6.0?

Build dynamic Web sites


Page 2 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

Version 6.0
Rational Application Developer for WebSphere Software Version 6.0 (Rational
Application Developer, for short) is a major revision of IBM WebSphere Studio
Application Developer. Rational Application Developer is the first release of the
environment that is being branded within the Rational product line and also includes
many features above and beyond those that were available in Version 5.x. Being
part of the Rational family has many advantages -- for example, Rational Application
Developer is part of the IBM Software Development Platform, which allows you to
visualize applications with Unified Modeling Language (UML) diagrams, visually
build Java and Web applications, and visually design portals. Rational Application
Developer Version 6.0 includes:

• Portal tools for visually developing portal applications


• Automated code analysis and component testing tools to improve code
quality
• Enhanced run time analysis tools to identify and fix performance problems
early in the development cycle
• Built-in Crystal Reports tools for building powerful and interactive data
reports
• WebSphere Rapid Deploy to accelerate application deployment and
simplify system testing in Application Server
• Eclipse 3.0 support for a more responsive, attractive, and customizable UI
that increases developer productivity

Section 3. Elements of dynamic Web sites

The static Web


When the World Wide Web was born, it consisted of static Web sites. Web sites in
turn consisted of static documents (mostly HTML pages) that were accessible
through Web servers. Users used Web browsers to access these Web sites. A Web
browser communicated with a Web server over the Hypertext Transfer Protocol
(HTTP). Using an HTTP request, the browser communicated with the Web server
and requested access to a certain document. The Web server managed a set of
documents stored on a file system. When asked for a document, it would retrieve it

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 3 of 41
developerWorks® ibm.com/developerWorks

and return it within an HTTP response (see Figure 1).

Figure 1. The static Web

The evolution of the dynamic Web


Technology visionaries saw that the Web model could be more powerful if the pages
returned to the browser were not statically stored on a file system. Pages could be
generated by accessing data stored in databases, by accessing legacy applications
and reformatting their UIs, and by performing computations based on user inputs.

The shift to dynamic Web sites involves a new server -- the application server.
Values sent within the HTTP request are passed from the Web server to the
application server and used by application code. This application code executes
within the context of the application server and performs business logic, accesses
data stores, and more. The code then dynamically generates the HTML that is
returned to the browser within the HTTP response (see Figure 2).

Figure 2. The dynamic Web

A new generation of tools

Build dynamic Web sites


Page 4 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

Paralleling the advancements made on the server side, browsers also became
better. Early browsers could parse simple HTML and present the page. Today's
browsers include powerful layout engines, the ability to execute scripts, and even a
Java Virtual Machine (JVM) for running Java code on the client (in the form of
applets). Using a technology called Dynamic HTML (DHTML), the pages returned to
the browser can themselves include many dynamic components that make for a
better user experience.

Powerful application models require powerful tools. When Web sites consisted of
static HTML pages, developers used HTML editors to build static content. For
building dynamic Web sites, developers need a new generation of tools. These tools
need to facilitate building applications that include server-side components such as
servlets and JSP files. They also need to support the entire code/test/debug life
cycle and to combine advanced testing and debugging environments in addition to a
development environment. Rational Application Developer is just such a tool.

The rest of this section provides an overview of the client- and server-side
technologies that are an integral part of the message center application. If you're
familiar with these technologies, skip to Build a dynamic Web application .

Java, Java servlet, and JSP technology


Rational Application Developer Version 6.0 makes building Web applications easy.
In fact, using frameworks such as Struts and JSF, building Web applications is a
simple matter of dragging-and-dropping components and filling in attributes. Many of
the behind-the-scenes constructs include servlets, JSP files, and tag libraries; in this
section, you get a brief overview of what these constructs are.

Java technology has emerged as the premier environment for building server-side
application code. The Java programming language makes it easy to build
well-structured object-oriented code, access data stores, and build robust business
logic.

In the context of this tutorial, back-end Java code runs within a Java application
server. A Java application server uses a JVM to execute Java code. The Java code
in this tutorial includes objects representing real-world entities (such as users and
messages) as well as servlets and JSP files.

All your code in this tutorial is built with Rational Application Developer. (You can
also use IBM Rational Web Developer for WebSphere Software Version 6.0: The
screens and processes look the same.) This single integrated environment allows
you to simply compose your business entities, build the business transactions using
servlets, and build the JSP files used to generate the UI.

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 5 of 41
developerWorks® ibm.com/developerWorks

Servlets
Servlets are Java classes that implement the Servlet interface. The Servlet interface
defines a doGet and a doPost method for handling client requests. HTTP
Servlets handle HTTP requests encapsulated as an HTTPServletRequest
object. The HTTPServletRequest object is passed as an argument to the
service method. Using this object, the servlet developer accesses parameters sent
as part of the request, cookies delivered with the request, and headers within the
HTTP request. The servlet generates dynamic content, usually as HTML. Using an
HTTPServletResponse object, the servlet developer writes the dynamic content
onto a servlet output stream, which in turn creates the page returned to the browser.

As a simple example, the servlet shown in Listing 1 retrieves a username from the
request parameters and prints a "hello" string.

Listing 1. Servlet for retrieving a username

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleHelloServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) {
this.doPost(req, res);
}
public void doPost(HttpServletRequest req, HttpServletResponse res) {
String username = req.getParameter("username");
// tell the browser that the content is an HTML page
res.setContentType("text/html");
// Generate the dynamic content
PrintWriter out = res.getWriter();
out.println("<HTML><BODY><H3>");
out.println("Hello " + username);
out.println("</H3></BODY></HTML>");
out.close();
}

JavaServer Pages
Hard-coding HTML in Java code is bad form because it creates inflexible code.
HTML elements become strings hard-coded within Java print commands (as shown
in Servlets). That means that tools for building Web pages cannot be used and that
the role of the Web page designer -- which should be separate from that of the Java
developer -- is not well supported. JSP files solve this problem by embedding Java
code that generates dynamic content within the HTML page. As an example, you
can replace SimpleHelloServlet with the JSP page shown in Listing 2.

Listing 2. JSP page to replace SimpleHelloServlet

Build dynamic Web sites


Page 6 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

<HTML>
<BODY>
<H3> <% out.println(request.getParameter("username")); %>
</H3>
</BODY>
</HTML>

In this scheme, HTML elements are well represented, and Java code is embedded
using special scriplet tags (< % ... %> or <jsp:scriplet> ...
</jsp:scriplet>).

Servlets and JSP files are used to generate dynamic content. While this content can
be of any type, it's usually HTML when building dynamic Web sites.

Taglibs
JSP files allow you to embed Java code within tags from the HTML tag set, which
means that the tags in a JSP file come from a finite and limited group that deals
mostly with layout. This group is limited in terms of how expressive you can make
your tag-centric page; much of the behavior tends to be implemented as calls to
various Java methods, and the page ceases to "belong" to the page designer.

Rational Application Developer Version 6.0 supports custom tag libraries -- taglibs --
and includes many taglibs that make your Web development simple. Taglibs let you
extend the tag/element vocabulary of your JSP file by allowing you to define new
elements that can be used inside a JSP file as any other tag. By providing a tag
implementation class, you define how the Web container processes the tag when
the JSP file is evaluated. For example, you can easily implement a new tag that
prints the value of the username parameter, in which case the JSP code fragment
from the previous section could become simply:

<HTML>
<BODY>
<H3> <USERNAME/>
</H3>
</BODY>
</HTML>

This example would be relevant in the unlikely event that you decide to build a
specialized implementation for printing the username parameter. A more common
JSP page would result if you used one of the core tags in the JavaServer Pages
Standard Tag Library (JSTL), in which case the page would become:

<HTML>
<BODY>

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 7 of 41
developerWorks® ibm.com/developerWorks

<H3> <c:out value="${param.username}" />


</H3>
</BODY>
</HTML>

Taglibs make authoring JSP pages easier and increase productivity by encouraging
a division of labor between library developers and library users. Taglibs are created
by a developer who is an implementation expert and are used by Web page authors
who, by building on these libraries, can produce more functional and higher-quality
applications.

Because taglibs are part of the JSP standard, they are also portable and supported
by all major Java 2 Platform Enterprise Edition (J2EE) environments. This support,
in turn, means that many people write taglibs and that you can often find great
reusable resources. Two important starting points are the Sun Microsystems taglib
page at http://java.sun.com/products/jsp/taglibraries.html and the Jakarta taglib
project at http://jakarta.apache.org/taglibs.

Dynamic HTML
DHTML = HTML + JavaScript code + Document Object Model (DOM) + Cascading
Style Sheets (CSS).

DHTML isn't the topic of this tutorial, but remember that DHTML is an important
technology in building dynamic Web sites. DHTML is a collection of client-side
technologies. A DHTML page is delivered by the server and runs within the Web
browser, so the browser runs the code within the DHTML page.

A DHTML page is first and foremost an HTML page. The DHTML developer can
embed JavaScript scripts within this HTML page. These scripts run on the client and
improve the user experience. An example is the use of JavaScript code to perform
client-side validations to eliminate unnecessary network traffic.

Most of the scripts that run within the browser need to access the elements on the
page -- that is, the HTML elements. The DOM defines a set of objects that are
directly related to the HTML elements on the page. The DOM allows JavaScript
code to refer to each HTML element on the page as an object with attributes and
methods. For example, JavaScript code can access a text field in an HTML form as
an object, retrieve its current value, and even change the value. The JavaScript
code can even access an HTML table as an object and add rows by manipulating
the table object -- all completely within the browser.

CSSs are used to associate formatting information with HTML elements. Instead of
hard-coding this information as HTML markup (such as bold and italics), all
formatting information is externalized to a CSS file and associated with the HTML
elements. This association makes quickly and uniformly changing the appearance of

Build dynamic Web sites


Page 8 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

a complete Web site easier.

Armed with this impressive set of server-side and client-side technologies, you're
now ready to turn to the tutorial's example of a dynamic Web site -- the messaging
center application.

Section 4. Build a dynamic Web application

Getting started with Rational Application Developer


To help you understand how to use Rational Application Developer to develop
dynamic Web sites, this tutorial shows how to develop a simple Web application.
The messaging center application allows users to send messages to one another.
Every user can log in to the Web site and view all the messages sent to them. For
every message, users see who sent the message and the message text. A user can
then send a message to any other registered user.

The focus of this tutorial is using Rational Application Developer to build such a
dynamic Web application, not the application itself. The messaging center
application is not a complete application and includes many shortcuts. For example,
the set of possible users is limited (instead of maintaining the users in a database),
login doesn't require a password, no error-handling is performed, and messages
can't be edited or grouped.

Elements within the messaging center application


As mentioned, Rational Application Developer Version 6.0 supports building
applications using frameworks such as Struts and JSF. Using these technologies,
Rational Application Developer allows you to create Web application flow diagrams.
In this tutorial, you build the flow yourself. The following is a high-level view of the
components you build and how they interact with each other. Figure 3 shows an
example of how the code components flow.

Figure 3. Overview of code components

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 9 of 41
developerWorks® ibm.com/developerWorks

A user starts by accessing a login of the form


http://localhost/MessagingCenter/login.jsp. The JSP engine processes the JSP files
and generates an HTML form that the browser returns and displays. The user enters
a username and clicks Submit, which makes a call to the
MessageCenterLoginServlet servlet running on the application server. If an
error occurs, the servlet forwards handling to the login JSP file. The login JSP file
creates an error message and presents the login form for the user to try again. If the
username is correct, the servlet prepares the object with the message data and
forwards handling to the message center JSP file. The JSP file generates dynamic
content, which is based on the messages, as an HTML page that is returned to the
browser. Using an HTML form, the user can send a message to another user by
clicking Submit, which makes a call to AddMessageServlet.

Create the messaging center project


If you're following along with a running copy of Rational Application Developer:

Build dynamic Web sites


Page 10 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

1. Select File > New > Project to create a new project. A project contains
files and folders, and it's how you organize resources within the Rational
Application Developer workbench. Rational Application Developer Version
6.0 supports many types of projects, including J2EE, Server, and Web.

2. Open the Web folder, then select Dynamic Web Project.

3. Click Next. Rational Application Developer creates a new project for a


Web application and generates resources required for dynamic Web
applications, such as servlets, JSP files, and HTML pages.

4. Enter a project name -- MessagingCenter, in this example.

5. Click Show Advanced to able to control the servlet version and the
deployment of your project within Rational Application Developer. (As you
can see, Rational Application Developer Version 6.0 now supports the
Servlet 2.4 specification.)

6. Click Next. But before letting Rational Application Developer create the
project, you need to add a few standard tag libraries.

Select the standard tag libraries


You can add features to your Web project in the Features window (see Figure 4).

1. Select JSP Tag Libraries for adding Utility Tag Libraries and the JSP
Standard Tag Library.

2. Click Finish. Rational Application Developer creates the Web project and
the various resources needed for a Web application.
Figure 4. Add features to your Web project

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 11 of 41
developerWorks® ibm.com/developerWorks

3. If this is your first Web project, the Rational Application Developer


workbench asks whether you want to assume the Web perspective for
this project. Select the Remember my decision option, then click Yes.

The Project Explorer opens and includes both the MessagingCenter project and a
MessagingCenterEAR under the Enterprise Applications node (encapsulating your
work in an enterprise archive that you can later install on a production WebSphere
Application Server machine). A perspective defines the initial set and layout of panes
in the workbench. This concept introduces a role-based customization of the views
and editors; it's a user-centric metaphor bringing together all the tools useful for a
certain role. Views provide different ways to look at a certain resource, and editors
are used to create and modify code. Rational Application Developer Version 6.0

Build dynamic Web sites


Page 12 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

includes a variety of different editors suitable for specific file types, such as HTML
files, JSP files, and Java source files.

Now that you've created the project, you're ready to start creating some of the
resources.

Section 5. Build the back end: Java classes and servlets

Build User.java and Message.java


First, you need to build the Java class to represent the user. To create a Java class:

1. Right-click the Java Resources folder within the Project Explorer on the
workbench and select New > Other.

2. In the wizard that appears, open the Java folder and select Class.

3. Click Next to bring up the Java class editor. Enter the class name (User)
and the package name (com.ibm.tutorials.rational). All the rest
(including the superclass java.lang.Object) remains as default.

At this point, you also need to create a Java class that represents the message
object. You can see the code for both classes in User and Message class code.

User and Message class code


Listing 3 and Listing 4 show the code for the User.java and Message.java
classes, respectively. After you've created both classes, the Project Explorer
appears (see Figure 5).

Listing 3. The User.java class code

package com.ibm.tutorials.rational;
import java.util.Vector;
public class User {
private String name;
private Vector messages;
// Simple implementation of a set of users -

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 13 of 41
developerWorks® ibm.com/developerWorks

// only for illustration purposes. Normally users


// would have to be maintained and managed in a database
private static User[] hardCodedUsers = {
new User("Joe"),
new User("Jane"),
new User("Tony"),
new User("Tina") };
public static User[] getHardCodedUsers() {
return User.hardCodedUsers;
}
public User(String name) {
this.name = name;
messages = new Vector();
}
public String getName() {
return this.name;
}
public Vector getMessages() {
return messages;
}
public void addMessage(Message message) {
messages.addElement(message);
}
// Return a User object based on user name or a null if a user
// by that name does not exist
public static User getUser(String username) {
User[] allUsers = User.getHardCodedUsers();
for (int i = 0 ; i < allUsers.length ; i++)
if (allUsers[i].getName().compareTo(username) == 0)
return hardCodedUsers[i];
return null;
}
}

Listing 4. The Message.java class code

package com.ibm.tutorials.rational;
public class Message {
private String senderName = null;
private String text = null;
public Message(String senderName, String text) {
this.senderName = senderName;
this.text = text;
}
public String getSenderName() {
return this.senderName;
}
public String getText() {
return this.text;
}
}

Build dynamic Web sites


Page 14 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

Figure 5. Newly created Java classes

Build the project


You can rebuild the project at any point while you're editing resources. To perform a
clean build, select Project > Clean. Performing a clean build means that Rational
Application Developer tries to compile all Java code, perform syntax checking on all
resources, and check references between the different elements of the Web
application. Such a build is sometimes useful when you fix errors within JSP files
(such as repairing bean references). However, you don't really need to perform full
builds all the time. Rational Application Developer does a partial build every time you
save your changes. If, for example, you misspell the import statement for the class

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 15 of 41
developerWorks® ibm.com/developerWorks

String (as shown below, where I've imported java.lang.Strig instead of


java.lang.String), Rational Application Developer signals the error as well as
the error message and the location of the error.

After you've fixed all the errors, select Project > Clean, then save your current
workbench.

You're now all set with the back-end entities, and you're ready to build the servlets
that will implement the "business transactions."

Create MessageCenterLoginServlet
The MessageCenterLoginServlet servlet is responsible for looking up the user
based on the username and for preparing the collection of messages to be displayed
for that user. However, the servlet doesn't generate the dynamic content (such as
the HTML): A JSP file does that.

To create the servlet:

1. Right-click the com.ibm.tutorials.rational folder in the Project Explorer and


select New > Other.

2. Select Servlet, then click Next.

3. In the Create Servlet window, enter the name


(MessageCenterLoginServlet) and a description of the servlet.

4. Click Next.

5. Enter the package name (com.ibm.tutorial.rational). The


superclass remains javax.servlet.http.HttpServlet.

6. Click Next.

7. By default, both the doGet and doPost method options are selected for
code creation in the last window of the wizard (see Figure 6); if this is the
behavior you want, click Finish.
Figure 6. Select methods for your servlet

Build dynamic Web sites


Page 16 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

When the wizard completes its work, you'll have a skeleton servlet class with the
code shown in Listing 5.

Listing 5. Skeleton servlet class

package com.ibm.tutorials.rational;
import java.io.IOException;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 17 of 41
developerWorks® ibm.com/developerWorks

* @version 1.0
* @author
*/
public class MessageCenterLoginServlet extends HttpServlet implements Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public MessageCenterLoginServlet() {
super();
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet
(HttpServletRequest arg0, HttpServletResponse arg1)
*/
protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost
(HttpServletRequest arg0, HttpServletResponse arg1)
*/
protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
}

Implement MessageCenterLoginServlet
Now, you need to implement the behavior of the servlet. The servlet needs to
process both GET HTTP requests and POST HTTP requests in the same way. The
simplest thing is to change the doGet method so that it calls the doPost method.
Doing so ensures that the behavior is identical regardless of which action was used:

protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)


throws ServletException, IOException {
this.doPost(arg0, arg1);
}

Implement the doPost method. First, get the username from the request. If it's null,
enter an error message and dispatch the handling to the login JSP file. (JSP files
generate all the HTML.) The login JSP file then generates the HTML based on this
error message:

String username = arg0.getParameter("username");


if (username == null) {
// Can't perform a login with no user name.
// Set an error message and redirect to login page.
arg0.setAttribute("errorMessage", "User name not specified");

Build dynamic Web sites


Page 18 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

// Dispatch to login.jsp using the RequestDispacther


// Use a relative URL for simplicity
RequestDispatcher disp = getServletContext().getRequestDispatcher("/login.jsp");
disp.forward(arg0, arg1);
}

You also need to add the following line to the import section:

import javax.servlet.RequestDispatcher;

Use autocompletion to finish the servlet


One of the many useful features of Rational Application Developer Version 6.0 is
autocompletion. If you forget which methods are applicable within a certain context,
you can place the cursor after the period following a variable name and press CTRL
+ space to bring up a context-sensitive list of possible methods based on the object
in the context. For example, if you forget which method of the request object you
should use when entering the error message, you can bring up the coding assistant
(see Figure 7).

Figure 7. The coding assistant

Back to the code. With the username in hand, you can proceed to look up the User
object using the facilities coded in the User class. If no User object is found, you
can use another error message. If a User object is found, place it in the session
object and forward handling to the JSP file responsible for displaying the messages:

// Otherwise proceed to looking for the User object


User user = User.getUser(username);
if (user == null) {
arg0.setAttribute("errorMessage", "User not found");
RequestDispatcher disp = getServletContext().getRequestDispatcher("/login.jsp");

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 19 of 41
developerWorks® ibm.com/developerWorks

disp.forward(arg0, arg1);
}
// Put the user object in the session object and forward to messageCenter JSP
HttpSession session = arg0.getSession(true);
session.setAttribute("user", user);
RequestDispatcher disp = getServletContext().getRequestDispatcher("/messageCenter.jsp");
disp.forward(arg0, arg1);

This step completes the servlet responsible for accessing the "business objects."
You're ready for the servlet handling the "business transaction."

AddMessageServlet
AddMessageServlet is responsible for adding a new message to one of the users
-- in effect, sending a text message from one user to another. This functionality is
invoked from an HTML form within the message center.

Building the servlet follows the same process as that of building


MessageCenterLoginServlet, as Listing 6 shows. The method implementing
the sending of the message has two parameters: the username of the message
recipient and the text message to be sent. The originator of the message is retrieved
from the session object.

Listing 6. AddMessageServlet

package com.ibm.tutorials.rational;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class AddMessageServlet extends HttpServlet implements Servlet {
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#HttpServlet()
*/
public AddMessageServlet() {
super();
}
/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest arg0,
* HttpServletResponse arg1)
*/
protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
this.doPost(arg0, arg1);
}

Build dynamic Web sites


Page 20 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

/* (non-Java-doc)
* @see javax.servlet.http.HttpServlet#doPost(
* HttpServletRequest arg0, HttpServletResponse arg1)
*/
protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1)
throws ServletException, IOException {
String recipient = arg0.getParameter("recipient");
String messageText = arg0.getParameter("messageText");
// Get the session object. If it does not exist or if there is no User object
// in it then we cannot process the message send and need to ask the user
// to login once more
HttpSession session = arg0.getSession(false);
if (session == null) {
arg0.setAttribute("errorMessage", "Need to login before sending a message");
RequestDispatcher disp = getServletContext().getRequestDispatcher("/login.jsp");
disp.forward(arg0, arg1);
}
User user = (User)session.getAttribute("user");
if (user == null) {
arg0.setAttribute("errorMessage", "Need to login before sending a message");
RequestDispatcher disp = getServletContext().getRequestDispatcher("/login.jsp");
disp.forward(arg0, arg1);
}
// Need to check that there is a recipient and that it is a legal user
// This is omitted for lack of interest
// Otherwise proceed to send the message
User messageReceiver = User.getUser(recipient);
Message message = new Message(user.getName(), messageText);
messageReceiver.addMessage(message);
}
}

The back-end code is now ready. It's time to move on to building the presentation
layer.

Section 6. Build the presentation layer: JSP

login.jsp and messageCenter.jsp


The presentation layer consists of a set of JSP forms. JSP forms are the perfect
elements for implementing the messaging center screen generators, because the
screens need to be HTML pages but are dynamically created based on the back-end
entities. As a result of submissions from the HTML forms, methods within the
servlets described previously are invoked.

The JSP forms created in this section are as follows:

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 21 of 41
developerWorks® ibm.com/developerWorks

• login.jsp: Responsible for generating the HTML form for capturing the
username and invoking MessageCenterLoginServlet
• messageCenter.jsp: Responsible for displaying as an HTML table the
messages sent to the user who is currently logged in; also generates a
form allowing the user to send a message

Build login.jsp
Rational Application Developer Version 6.0 has an editor for building JSP files that
follows the feel of HTML builders. To create the JSP form:

1. Right-click the WebContent folder in the Project Explorer and select New
> JSP File.

2. In the New JSP File window, enter the JSP file name (see Figure 8).
Figure 8. Specify a name and location for login.jsp

Build dynamic Web sites


Page 22 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

3. The New JSP File Wizard can help you specify many of the JSP file's
attributes. While you can click Finish on the first page of the wizard, you
can also select the Configure advanced options option and continue
with the other windows in the wizard. Using the wizard, you can specify
explicit init and destroy method stubs, initialize parameters for the
servlet that is automatically generated from the JSP file, attach
stylesheets, define the document type definition (DTD) used in the JSP
file (IBM WebSphere Studio Version 5.1.1 supports Extensible HTML, or
XHTML), and specify the tag libraries to be used from within the JSP form
-- the topic of the next panel.

4. Click Next.

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 23 of 41
developerWorks® ibm.com/developerWorks

Import tag libraries


The New JSP File Wizard allows you to specify the tag libraries used from within the
JSP form. Click Add to open the next page of the wizard. Here, you can select the
tag libraries you want to use (see Figure 9).

Figure 9. Select tag libraries

Build dynamic Web sites


Page 24 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

Rational Application Developer shows you a form of a catalog of taglibs, including


tag libraries from the Apache Jakarta project, the JSTL core library, and much more.
You can also import additional tag libraries into the catalog by clicking Import.

Select the JSTL core library, then click OK. You can change the prefix used within
the JSP file, but the default for the core tag library is the letter c. On the page from

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 25 of 41
developerWorks® ibm.com/developerWorks

which you added the tag library, click Finish.

Note: Depending on which version of the JSP engine you use within your
application, you might need a different version of the JSTL core library. Both appear
in the wizard beneath the other. The first has a URI of http://java.sun.com/jstl/core
and the second has a URI of http://java.sun.com/jsp/jstl/core. If you are using JSP
2.0 you should use http://java.sun.com/jsp/jstl/core.

Now you're ready to start designing the JSP form. Use the central pane in the
workbench to design your page. You can drag and drop elements from the toolbar.
You can also insert elements from the Insert menu bar item.

Including a 'use bean' element


To build the login JSP page, you first need to include a use bean element. The
bean in the login.jsp page represents the error message that is displayed if, for
example, you enter a username that doesn't exist. Insert the use bean element
using the Insert JSP Bean tool by selecting JSP > Insert Bean. Set the properties of
the bean in the property editor (see Figure 10).

Figure 10. Set the bean properties

Build dynamic Web sites


Page 26 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

The identifier of the bean throughout the page is errorMessage, and the bean
should be retrieved from the Request object. (Remember from
MessageCenterLoginServlet that the error message is placed using
request.setAttribute(errorMessage).) The class of the bean is a
java.lang.String.

When this bean is available in the context of the page, you can display the message
using a JSP expression. Select JSP > Insert Expression to place the expression
element on the page and open the properties editor below the canvas (see Figure
11). Enter the JSP expression to print out the error message variable.

Figure 11. The JSP expression properties

Add the form to the page


Continue to build the page:

1. Add a horizontal rule from the HTML Tags section on the palette.

2. Add a Form element from the Form Tags section on the palette.

3. After the form is on the page, select a Text Field element from the Form
Tags section on the palette and drop it into the form. This form is used for
entering the username.

4. Give the input field an initial value using the properties editor below the
canvas.

5. Add a Submit button to the form by dropping a Submit Button component


from the Form Tags section on the palette onto the form. As you drop the
Submit button, a pop-up window prompts you for the button's label. The
Submit button causes the form data to be submitted, but you haven't

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 27 of 41
developerWorks® ibm.com/developerWorks

specified what URL should be called on the server.

6. Select the Form element on the designer.

7. Click the Properties tab. The most important property is the Action
property.

8. Click the Browse tool just to the right of the Action field.

9. Click the Servlet option.

Rational Application Developer lets you choose the action among all servlets that
you have already defined. For each available servlet, Rational Application Developer
lists the URL that will be used. Select MessageCenterLoginServlet, then click OK.
Figure 12 shows the resulting page in the designer.

Figure 12. The login.jsp servlet

Click Source at the bottom of the design pane to see the generated JSP source
code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<HTML>
<HEAD>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM Software Development Platform">
<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="theme/Master.css" rel="stylesheet"
type="text/css"\>
<TITLE>login.jsp</TITLE>
</HEAD>
<BODY>
<jsp:useBean id="errorMessage" scope="request"
class="java.lang.String"></jsp:useBean>

Build dynamic Web sites


Page 28 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

<%=errorMessage%>
<HR>
<P></P>
<FORM action="/MessagingCenter/MessageCenterLoginServlet"
name="LoginForm" target="_self"><INPUT
type="text" name="username" size="20" value="Enter user name"><INPUT
type="submit" name="submit" value="Login"></FORM>
</BODY>
</HTML>

You're done building your first JSP form and are ready to move on to the second.

Build messageCenter.jsp
The messageCenter JSP form is similar to the login JSP form. Start by creating a
new JSP file:

1. Right-click the Web Content folder in the Project Explorer and select New
> JSP File.

2. Enter messageCenter.jsp as the JSP form name, then click Next.

3. Add the JSTL taglib, then click Finish.

4. Moving over to the designer, drag the following elements onto the canvas:
• A bean element for getting the User: Select user as the ID, Session
as the scope, and com.ibm.tutorials.rational.User as the type.
• Static text: Simply type the text you want to display -- in this case, the
string "Welcome".
• Property display element for displaying the username: Drag a Get
Property element from the palette. In the JSP Get Property window,
expand user and select name. Click OK.
• Static text: "Your messages are as follows"
• HTML table: Start out with two columns and two rows. In the first row,
type the headings From and Text, then set the cell widths.
• Within the second table row (TR), place a Java loop: Each iteration of
the loop creates a new TR element with the message sender and text
in table data (TDs). The loop is created using the JSTL core tag
library, which supports iteration.
• Select JSP > Insert Custom: Doing so opens the Insert Custom Tag
Wizard that displays all the taglibs in your JSP form and the available
custom tags.

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 29 of 41
developerWorks® ibm.com/developerWorks

• Select forEach for an iteration loop, then click Insert: Iteration for this
element should be on ${user.messages}. To select this, click the
Properties tab, then select Iterate over the entire collection. Click
the ... tool to the right of the Items field, then expand the user entry
and select messages. Make sure to give the forEach element a
name so that you can reference it. The call is aMessage, because
each element is a message. Within each iteration, you create a TR
and two TDs. In each TD, insert an output component from the
palette; in the property editor, enter ${aMessage.senderName} and
${aMessage.text}, respectively. Your workbench should now look
like the one in Figure 13.
Figure 13. The messageCenter.jsp form

5. Finish building the page by adding these final items for sending a
message:
• An HR element from the HTML section in the palette
• A form for sending a new message from the Form Tags section in the
palette. In the Properties window, set the action to
/MessagingCenter/AddMessageServlet by clicking the tool to the
right of the Action field, selecting Servlet, then selecting
AddMessageServlet.

Build dynamic Web sites


Page 30 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

• A text field (named recipient) for the recipient of the message dropped
into the form
• A text area (named messageText) for the message text dropped into
the form
• A Submit button (with a label of Send Message) in the form

When you're done with the designer, the page should look like the one in Figure 14.

Figure 14. The final messageCenter.jsp form

Rational Application Developer generates the JSP code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">


<HTML>
<HEAD>

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 31 of 41
developerWorks® ibm.com/developerWorks

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM Software Development Platform">
<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="theme/Master.css" rel="stylesheet"
type="text/css">
<TITLE>messageCenter.jsp</TITLE>
</HEAD>
<BODY><jsp:useBean id="user" type="com.ibm.tutorials.rational.User"
scope="session"></jsp:useBean>
<P><BR>Welcome
<jsp:getProperty name="user" property="name" />. Your messages are as follows:<BR>
</P>
<TABLE border="1">
<TBODY>
<TR>
<TD width="196">From</TD>
<TD width="454">Text</TD>
</TR>
<c:forEach items="${user.messages}" var="aMessage">
<TR><TD width="196">
<c:out value="${aMessage.senderName}">
</c:out></TD><
TD width="454"><c:out
value="${aMessage.text}"></c:out></TD></TR>
</c:forEach>
</TBODY>
</TABLE>
<HR>
<FORM action="/MessagingCenter/AddMessageServlet"><INPUT type="text"
name="recipient" size="20"><BR>
<TEXTAREA rows="2" cols="20" name="messageText"></TEXTAREA>
<BR>
<INPUT type="submit" value="Send Message">
</FORM>
</BODY>
</HTML>

You're done with the coding of the application and can move on to testing the
message center.

Section 7. Test the message center

Start the server


To test your application, you can use the built-in WebSphere Application Server test
environment or, if you've installed WebSphere Application Server Version 6.0, you
can use that. (Refer to Resources at the end of this tutorial for download
information.) You are prompted for the location of the environment when you try to
launch the application.

Build dynamic Web sites


Page 32 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

To test the application:

1. Right-click login.jsp and select Run on Server.

2. Select WebSphere v6.0 Server from the Select the server type list and
select Set server as project default (do not prompt).

3. Click Finish (see Figure 15).


Figure 15. Select a server on which to run your application

The application is published to the server. You will see many printouts on the
console, and a Web browser window appears in your workspace.

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 33 of 41
developerWorks® ibm.com/developerWorks

Example of a message
The top right pane is a browser view that displays the login HTML (the HTML page
that login.jsp generated). If you proceed to log in using one of the fixed usernames,
you can start sending messages among the users. Remember that because
messages are not persistent, all these messages will be lost if you shut down the
server.

As an example, suppose you want to send a message from Joe to Jane. Log in as
Joe. In Joe's message center, enter the text for a message to send to Jane, then
click Submit (see Figure 16).

Figure 16. Joe's message center

Now, go back to the login form, and log in as Jane. Figure 17 shows Jane's
message center.

Figure 17. Jane's message center

Build dynamic Web sites


Page 34 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

Debug the application


One of the really great things about Rational Application Developer Version 6.0 is
that WebSphere Application Server is very tightly integrated. That means that you
don't have to develop your application, deploy it on a server (with all kinds of print
commands), look at the log files, and figure out what went wrong. You can do
everything within one integrated development environment using a single set of
tools.

For example, suppose that an exception occurs when you run the application. You
can add a breakpoint by right-clicking on the left border of the code and setting a
breakpoint (see Figure 18).

Figure 18. Set a breakpoint

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 35 of 41
developerWorks® ibm.com/developerWorks

You can also simply double-click the right border of the pane. Doing so sets a
breakpoint in the code, displayed as a blue circle.

When running the application, the server stops at the breakpoint. Note that you have
to run the server in Debug mode: Instead of selecting Run on Server, right-click
login.jsp, then select Debug > Debug on Server. If you were already running the
server, you'll be prompted to restart the server.

When the program hits the breakpoint for the first time, Rational Application
Developer asks whether you want to switch to the Debug perspective. The Debug
perspective allows you to step through your code, look at variables, and perform all
your debugging from the convenience of your workbench (see Figure 19).

Figure 19. Debug code from your workbench

Build dynamic Web sites


Page 36 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

The Inspector
The Inspector is another useful tool. Suppose that after you've stopped at the
breakpoint, you want to know what string value is stored in the username variable.
Double-click the variable to mark it, then right-click the variable and select Inspect.
A pop-up window (see Figure 20) allows you to view the value of the marked
variable (in this case, the value is Jane).

Figure 20. View the value of the marked variable

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 37 of 41
developerWorks® ibm.com/developerWorks

Finally, remember that Rational Application Developer is a well-integrated


environment. If you change code even within a running application, the changes take
effect immediately -- all within one environment.

Packaging
Now that you've tested the message center and feel comfortable with the Web
application, you're ready to deploy it on a computer running WebSphere Application
Server Version 6.0. You need to package your Web application in a Web Archive
(WAR) file within an Enterprise Archive (EAR).

1. In the Web perspective, navigate to the Project Explorer and open the
Enterprise Applications folder.

2. Right-click MessagingCenterEAR and select Export > EAR File.

3. In the EAR project drop-down list, select MessagingCenterEAR.

4. In the Destination field, type the location and name of the EAR file you
want to create and click Finish.

Section 8. Summary
In this tutorial, you learned how to use Rational Application Developer Version 6.0 to
develop an end-to-end Web application. Using servlets and JSP forms, the tutorial

Build dynamic Web sites


Page 38 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

demonstrated how to use Rational Application Developer to develop a basic


messaging center. Starting with the back-end Java code for managing users and
messages, you then built a set of servlets and JSP files implementing messaging
functionality and generating a presentation layer in the form of HTML pages. These
HTML pages were dynamically generated based on the data maintained by the Java
objects. When development was complete, you used the Rational Application
Developer Version 6.0 server tools to test and debug your dynamic Web site. Finally,
you learned how to package your Web application for deployment to a computer
running WebSphere Application Server.

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 39 of 41
developerWorks® ibm.com/developerWorks

Resources
Learn
• A tutorial on building Java HTTP servlets is available on IBM developerWorks.
• Join a live IBM Rational Software Development Platform webcast and
participate in the Q&A session or replay the recorded webcasts at your
convenience.
• The Java Servlet technology home page includes the latest specification as well
as a reference servlet server implementation.
• The JavaServer Pages home page includes the latest specifications as well as
pointers to custom tag libraries and other advanced JSP technologies.
• The DHTML school Web page includes resources, examples, and reference
materials.
• For information about the Rational family of development tools, see WebSphere
software home page.
• The Eclipse project can be found at www.eclipse.org.
• The Apache Jakarta Taglib project can be found at
http://jakarta.apache.org/taglibs.
• The Sun tag library page can be found at
http://java.sun.com/products/jsp/taglibraries.html.
• Check out SDO for a good introduction on Service Data Objects (SDO).
• For a good article on Struts and JSF, see the IBM developerWorks article
Integrating Struts, Tiles, and JavaServer Faces.
• For a good tutorial on using JSF, see the IBM developerWorks tutorial IBM
WebSphere Developer Technical Journal: Developing JSF Applications using
WebSphere Studio V5.1.1 -- Part 1.
Get products and technologies
• Register to download Rational Application Developer Version 6.0.
• Register to download a copy of WebSphere Application Server Version 6.0.
Discuss
• Participate in the discussion forum for this content.

About the author

Build dynamic Web sites


Page 40 of 41 © Copyright IBM Corporation 1994, 2008. All rights reserved.
ibm.com/developerWorks developerWorks®

Ron Ben-Natan
Ron Ben-Natan, a Studio B author, is CTO and VP, R&D, at Guardium Inc. -- a
leader in data access security solutions. Prior to that, he worked for companies such
as Intel, AT&T Bell Laboratories, Merrill Lynch, J.P. Morgan, and ViryaNet. He has a
Ph.D. in Computer Science in the field of distributed computing and has been
architecting and developing distributed applications for more than 15 years. His
hobby is writing about how technology is used to solve real problems, and he has
authored and co-authored numerous books, including Implementing Database
Security and Auditing, Mastering IBM WebSphere Portal, CORBA: A Guide to
Common Object Request Broker Architecture, The San Francisco Developer's Guide,
and IBM WebSphere: The Complete Reference. He has also written numerous
articles and tutorials.

Build dynamic Web sites


© Copyright IBM Corporation 1994, 2008. All rights reserved. Page 41 of 41

You might also like