100% found this document useful (1 vote)
835 views870 pages

WSAD Programming Guide

This edition applies to Version 5 of WebSphere Studio Application Developer and WebSphere Application Server. This book is a rewrite of the IBM redbook, SG24-6585, which was based on Version 4 of the products. Before using this information and the product it supports, read the information in "Notices" on page xix.

Uploaded by

prabhanjan_kumar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
835 views870 pages

WSAD Programming Guide

This edition applies to Version 5 of WebSphere Studio Application Developer and WebSphere Application Server. This book is a rewrite of the IBM redbook, SG24-6585, which was based on Version 4 of the products. Before using this information and the product it supports, read the information in "Notices" on page xix.

Uploaded by

prabhanjan_kumar
Copyright
© Attribution Non-Commercial (BY-NC)
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 870

Front cover

WebSphere Studio
Application Developer
Version 5 Programming Guide
Develop Java, Web, XML, database, EJB,
and Web services applications

Test with built-in and remote


servers

Deploy to WebSphere
Application Server

Ueli Wahli
Ian Brown
Fabio Ferraz
Maik Schumacher
Henrik Sjostrand

ibm.com/redbooks
International Technical Support Organization

WebSphere Studio Application Developer Version 5


Programming Guide

July 2003

SG24-6957-00
Note: Before using this information and the product it supports, read the information in
“Notices” on page xix.

First Edition (July 2003)

This edition applies to Version 5 of WebSphere Studio Application Developer and WebSphere
Application Server.

This book is a rewrite of the IBM Redbook, WebSphere Studio Application Developer
Programming Guide, SG24-6585, which was based on Version 4 of the products.

© Copyright International Business Machines Corporation 2003. All rights reserved.


Note to U.S. Government Users Restricted Rights -- Use, duplication or disclosure restricted by GSA ADP
Schedule Contract with IBM Corp.
Contents

Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xx

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxi
The team that wrote this redbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxii
Become a published author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiii
Comments welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxiv
Summary of changes from SG24-6585 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv
July 2003, First Edition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xxv

Part 1. Introducing WebSphere Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Chapter 1. Introduction and concepts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Eclipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Platform architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Workbench features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Plug-in based tooling. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Role-oriented development with consistent look and feel . . . . . . . . . . . . . . . 7
Vertical and horizontal integration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Open standards. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Open team development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
File-based IDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
WebSphere Studio products . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
What is new in Application Developer Version 5 . . . . . . . . . . . . . . . . . . . . . . . 11
Migration from previous versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Web development tools. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Relational database tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
XML tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Java development tools (JDT) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Web services development tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
EJB development tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Team collaboration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Debugging tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Performance profiling tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Server tools for testing and deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Plug-in development tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Sample code in this book . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

© Copyright IBM Corp. 2003. All rights reserved. iii


EJBBANK database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Naming convention . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20

Chapter 2. Setting up your Workbench and workspace preferences . . . . 21


Workbench basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Workspace basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Application Developer’s log files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
Automatic builds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
File associations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Local history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Perspectives preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
Internet preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
Java development preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Java classpath variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33
Appearance of Java elements. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Code formatter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
Compiler options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36
Java Editor settings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
Installed JREs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
Javadoc documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
Organize imports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

Chapter 3. Perspectives, views, and editors. . . . . . . . . . . . . . . . . . . . . . . . 47


Integrated development environment (IDE) . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Application Developer help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Perspectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Views. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Perspective layout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
Switching perspectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Specifying the default perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Organizing and customizing perspectives. . . . . . . . . . . . . . . . . . . . . . . . . . 54
Perspectives walkthrough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
J2EE perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
Resource perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Web perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Java perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61
Java Browsing perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

iv WebSphere Studio Application Developer Version 5 Programming Guide


Java Type Hierarchy perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Server perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
XML perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
XSL Debug perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Data perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
Debug perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
Profiling perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Component Test perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
CVS Repository Exploring perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
Install/Update perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Plug-in Development perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

Chapter 4. Projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
J2EE architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Web containers and EJB containers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
EAR files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
WAR files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
JAR files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Projects and folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Application Developer’s project types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Simple project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Java project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 82
Enterprise Application project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
Web project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
EJB project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84
Application Client project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Server project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85
Creating a new project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Project properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87
Using templates to create application projects . . . . . . . . . . . . . . . . . . . . . . . . . 88
Running the Application Template Wizard . . . . . . . . . . . . . . . . . . . . . . . . . 88
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

Part 2. Developing applications. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

Chapter 5. Developing Java applications . . . . . . . . . . . . . . . . . . . . . . . . . . 93


Creating and working with a Java project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Creating a Java project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
Creating Java packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Creating Java classes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Running your programs. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
Exporting code and running outside Application Developer . . . . . . . . . . . 106
Locating compile errors in your code . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108

Contents v
Debugging your code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Preparing a utility project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Banking model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Importing the implementation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Testing the model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Programming assists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Pluggable JDK . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Java Scrapbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
Code assist . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Navigating through your code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
Import generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
Tasks view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
Refactoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122
Code generation actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
Smart compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Java search and working sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
Bookmarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
Javadoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Generating Javadoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
Using Ant to generate Javadoc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137

Chapter 6. Developing database applications . . . . . . . . . . . . . . . . . . . . . 139


JDBC overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
Data source versus direct connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Application Developer database operations . . . . . . . . . . . . . . . . . . . . . . . . . . 142
XMI and DDL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
Data perspective . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
DB Servers view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Data Definition view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143
Navigator view. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
Using the DB Servers view. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Creating a database connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
Importing database objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Generate DDL and XML schema files. . . . . . . . . . . . . . . . . . . . . . . . . . . . 151
Creating database objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Create database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155
Create schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Create table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157
Create table with foreign key. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
Define the database schema in a database system . . . . . . . . . . . . . . . . . 163

vi WebSphere Studio Application Developer Version 5 Programming Guide


Creating SQL statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Using the SQL Statement Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
Using SQL Query Builder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 171
Accessing databases from a Java application . . . . . . . . . . . . . . . . . . . . . . . . 174
Access using the DriverManager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
Access using a data source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
J2EE client application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178

Chapter 7. Developing Web applications . . . . . . . . . . . . . . . . . . . . . . . . . 179


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Sample application: RedBank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
Controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
Facade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Application flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
Creating a Web project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
Adding the banking model as a utility JAR . . . . . . . . . . . . . . . . . . . . . . . . 188
Module dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Project properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
Web project directory structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
Importing existing resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 192
Creating static Web resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
Create a simple HTML page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194
Using the Page Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
Using the CSS Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
Creating dynamic Web resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Working with servlets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
Working with JSPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Creating a server for testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
Testing the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Working with filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
Creating a filter in Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . 227
Editing the filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
Working with listeners . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
Creating a listener in Application Developer . . . . . . . . . . . . . . . . . . . . . . . 233
Editing the listener. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
Creating Web pages from a JavaBean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Completing the code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
Tailoring the generated files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Running the generated application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

Contents vii
Chapter 8. Developing Web applications with database access . . . . . . 247
Accessing databases from a Web application . . . . . . . . . . . . . . . . . . . . . . . . 248
Creating a Web project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
Generate Web pages from SQL queries . . . . . . . . . . . . . . . . . . . . . . . . . . 249
Defining a data source in the server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
Testing the database application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
Accessing a database using DB Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
Creating a JSP using DB Beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
Accessing a database using JSP taglib . . . . . . . . . . . . . . . . . . . . . . . . . . 262
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270

Chapter 9. Developing applications with stored procedures . . . . . . . . . 271


What is a stored procedure? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Creating a Java stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272
Importing the database definition into a Web project . . . . . . . . . . . . . . . . 272
Using the Stored Procedure Wizard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
Building the stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
Executing the stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279
Accessing a Java stored procedure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Using a main program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
Generate a JavaBean to access the stored procedure . . . . . . . . . . . . . . . 281
Using the JSP tag library. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285
Generate JavaBean Web pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
Creating a stored procedure with multiple statements . . . . . . . . . . . . . . . . . . 287
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292

Chapter 10. Developing Struts applications . . . . . . . . . . . . . . . . . . . . . . . 293


What is Struts? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
MVC architectural pattern. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
Model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
View . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
Controller. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
Dependencies between MVC layers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
MVC framework with Struts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
Application Developer support for Struts . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300
Developing a Web application using Struts . . . . . . . . . . . . . . . . . . . . . . . . . . 301
Creating a Struts Web project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302
Copying the facade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Importing RedBank Web content . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Updating ApplicationResources.properties . . . . . . . . . . . . . . . . . . . . . . . . 306
Creating the Struts Web diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
Implementing the Struts Web diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
Developing the form beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310

viii WebSphere Studio Application Developer Version 5 Programming Guide


Developing the JSPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 316
Developing the actions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
Using the Struts configuration file editor . . . . . . . . . . . . . . . . . . . . . . . . . . 336
Testing the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 342
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344

Chapter 11. Developing XML applications . . . . . . . . . . . . . . . . . . . . . . . . 345


XML overview and technologies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
XML and XML processor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
DTD and XML schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
Schema and style using XSLT and XSL . . . . . . . . . . . . . . . . . . . . . . . . . . 347
XML namespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
XPath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
Application Developer XML tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
Tools demonstrated in this chapter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 349
Setting up your sample project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
Creating a new XML file from scratch . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
Creating an XML schema . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
XML generators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
Generating a DTD from XSD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
Validate XML files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
Generating an XML file from an XML schema . . . . . . . . . . . . . . . . . . . . . 359
Creating an XSL file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
Transforming XML files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
Debugging XSL . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
Generating JavaBeans from DTD or XSD . . . . . . . . . . . . . . . . . . . . . . . . 371
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372

Chapter 12. Developing EJB applications. . . . . . . . . . . . . . . . . . . . . . . . . 373


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
EJB server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
EJB container . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
EJB components . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
Sample Application: RedBank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 384
Creating an EJB project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
Data transfer objects and helper classes . . . . . . . . . . . . . . . . . . . . . . . . . 388
Implementing the model with entity beans . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
Creating the entity beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389
Editing the entity beans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
Creating entity relationships . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
Updating the TransRecord create method . . . . . . . . . . . . . . . . . . . . . . . . 404
Creating custom finders . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406

Contents ix
Object-relational mapping . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
Implementing the session facade . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
Creating the session bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
Creating an EJB reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
Editing the session bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
Generating the deployed code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 426
Completing the EJB deployment descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . 427
Changing the data source for EJB access . . . . . . . . . . . . . . . . . . . . . . . . 428
Testing the EJBs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
Universal test client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
Adapting the Web applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
Web project dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
EJB references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
Testing the Web interface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440

Chapter 13. Developing Web services. . . . . . . . . . . . . . . . . . . . . . . . . . . . 441


The concept of a service-oriented architecture (SOA) . . . . . . . . . . . . . . . . . . 442
Web services approach for an SOA architecture . . . . . . . . . . . . . . . . . . . . . . 443
Web services tools in Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . 445
Bottom-up development of a Web service . . . . . . . . . . . . . . . . . . . . . . . . 445
Top-down development of a Web service . . . . . . . . . . . . . . . . . . . . . . . . . 445
Client development . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Preparation for samples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Creating a Web service from a JavaBean . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
Creating the Web service using the Web Service wizard . . . . . . . . . . . . . 447
Generated files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
Testing the Web service . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
Using the sample test application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
Using the universal test client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
Creating a Web service client. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
Run the Web Service Client wizard. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
Creating a Web service from a session bean. . . . . . . . . . . . . . . . . . . . . . . . . 464
Implementing a real client application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
More information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467

Chapter 14. Developing GUI applications . . . . . . . . . . . . . . . . . . . . . . . . . 469


Introduction to the Visual Editor for Java . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
Sample GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 470
Setting up your sample project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
Launching the Visual Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
Create a visual class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 473

x WebSphere Studio Application Developer Version 5 Programming Guide


Open an existing class with the Visual Editor . . . . . . . . . . . . . . . . . . . . . . 475
Visual Editor look and feel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
Customizing the appearance of the Visual Editor . . . . . . . . . . . . . . . . . . . . . 478
Changing the default Java Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
Working with the Visual Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
Resizing a JavaBean component . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
Code synchronization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
Add JavaBeans to a visual class. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
Working with the Properties view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
Working with the Java Beans view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
Extending the sample GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
Adding data to the JavaBean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
Adding additional methods to the sample GUI . . . . . . . . . . . . . . . . . . . . . . . . 500
Writing event handling code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
Running and testing JavaBeans. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
Running the sample GUI as a JavaBean . . . . . . . . . . . . . . . . . . . . . . . . . 505
Running the sample GUI as a Java application . . . . . . . . . . . . . . . . . . . . 507
Testing the sample GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
Running the sample outside of Application Developer . . . . . . . . . . . . . . . . . . 508
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 509

Part 3. Testing and debugging applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511

Chapter 15. Servers and server configurations . . . . . . . . . . . . . . . . . . . . 513


Server tools feature . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
Supported run-time environments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
Creating server and server configuration automatically . . . . . . . . . . . . . . . . . 516
Creating server and server configuration manually . . . . . . . . . . . . . . . . . . . . 519
Creating a Server project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
Creating a remote server and file transfer mechanism . . . . . . . . . . . . . . . 520
Creating a server configuration manually . . . . . . . . . . . . . . . . . . . . . . . . . 527
Assigning a server configuration to a server . . . . . . . . . . . . . . . . . . . . . . . 530
Creating a server and server configuration together . . . . . . . . . . . . . . . . . . . 530
Assigning a project to a server configuration . . . . . . . . . . . . . . . . . . . . . . . . . 531
Configuring the data source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
Starting and stopping servers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
Changing the applications to run on a remote server. . . . . . . . . . . . . . . . . . . 538
Apache Tomcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 539
TCP/IP Monitor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 540
Configuring the TCP/IP Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
Using the TCP/IP Monitor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
Customizing server configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544
Server page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 544

Contents xi
Configuration page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
Applications page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
Administrative console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 548
Applying Fix Packs to the WebSphere test environment . . . . . . . . . . . . . . . . 549
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 551

Chapter 16. Testing and debugging. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553


Debugging a Web application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
Setting breakpoints in a servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 554
Setting breakpoints in a JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
Testing the application with breakpoints enabled. . . . . . . . . . . . . . . . . . . . . . 557
Debug view with stack frames. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
Debug functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
Breakpoints view . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
Watching variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
Inspecting variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 562
Evaluating an expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
Debugging a JSP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 564
Debugging on a remote WebSphere Application Server . . . . . . . . . . . . . . . . 566
Configuring the remote server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 566
Attaching to remote server in Application Developer . . . . . . . . . . . . . . . . 567
Connecting to the remote server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
Debugging on the remote server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
Disconnecting from the remote server . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572

Chapter 17. JUnit and component testing . . . . . . . . . . . . . . . . . . . . . . . . 573


What is JUnit? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
Unit testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
Why unit testing?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 574
Benefits of a unit testing framework . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 575
Testing with JUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 576
TestCase class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
TestSuite class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
Creating the test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
Importing the model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
Preparing for JUnit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
Creating a test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
The setUp and tearDown methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
Test methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 582
Creating a TestSuite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 584
Running the test case. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
Testing the Web applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588

xii WebSphere Studio Application Developer Version 5 Programming Guide


Component testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
Creating a Java test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 589
Preparing a Java test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
Updating code of Java test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 593
Running a Java test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
Report test case results . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
Creating an HTTP test case . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603

Part 4. Deploying and profiling applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605

Chapter 18. Deploying enterprise applications . . . . . . . . . . . . . . . . . . . . 607


Enterprise application deployment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
Importing the enterprise application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
Working with deployment descriptors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 608
EJB deployment descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
Web deployment descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 611
Application client module deployment descriptor . . . . . . . . . . . . . . . . . . . 613
Building an application client module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
Exporting an enterprise application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 616
Configuring WebSphere Application Server . . . . . . . . . . . . . . . . . . . . . . . . . . 617
Start the server and the administrative console . . . . . . . . . . . . . . . . . . . . 617
Configuring a server (optional) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 618
Configuring a JDBC driver and data source . . . . . . . . . . . . . . . . . . . . . . . 618
Save the configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 621
Installing an enterprise application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 622
Regenerating HTTP Server plug-in configuration . . . . . . . . . . . . . . . . . . . 627
Starting the enterprise application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 627
Testing the applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 628
Remote debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
Command line tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
Batch commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
Scripting tool: wsadmin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 630
Classpath . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 632

Chapter 19. Building applications with Ant . . . . . . . . . . . . . . . . . . . . . . . 633


What is Ant? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 634
Sample demo project and application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
Ant build files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 635
Ant tasks. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
Creating a simple build file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 636
Project definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 638
Global properties . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639

Contents xiii
Build targets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 639
Running Ant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
Where is the output? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
Rerunning Ant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 643
Forced build . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
Classpath problem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
Building J2EE applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 644
Using or importing a J2EE project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
Ant J2EE build script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
Running Ant for J2EE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 650
Building Javadoc with Ant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651
Running Ant outside of Application Developer . . . . . . . . . . . . . . . . . . . . . . . . 652
Preparation of the command file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
Running the command file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 654

Chapter 20. Profiling applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655


Profiling architecture. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
Profiling Java processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657
Agent Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 657
Profiling an application in the WebSphere Test Environment . . . . . . . . . . 658
Attaching to a Java process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658
Start monitoring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 662
Performance analysis views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
Launch Java process for profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
Profiling remote processes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 665
Performance analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 666
Package statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
Class method statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
Method statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
Heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
Method invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674
Method execution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
Execution flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
Sequence diagram . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
Instance statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682
Object references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
Some things to be aware of . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685

Part 5. Team programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687

Chapter 21. Version control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689


Local history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690

xiv WebSphere Studio Application Developer Version 5 Programming Guide


Comparing files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690
Replacing files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691
Restoring deleted files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
Preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
Team development. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
Application Developer team support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
Terminology comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 700

Chapter 22. Using Concurrent Versions System . . . . . . . . . . . . . . . . . . . 701


Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
Installing CVS on the Windows platform . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
Creating a CVS repository on CVSNT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
Configuring CVS in Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . . . 706
What is new in Application Developer Version 5?. . . . . . . . . . . . . . . . . . . 706
CVS preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
What changes could impact your work? . . . . . . . . . . . . . . . . . . . . . . . . . . 710
Ignoring resources from version control . . . . . . . . . . . . . . . . . . . . . . . . . . 711
Label decorations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712
CVS console . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 712
Development scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713
Creating and sharing the project (step 1 - stade1) . . . . . . . . . . . . . . . . . . 714
Adding a shared project to the workspace (step 2 - stade2) . . . . . . . . . . . 719
Synchronizing with repository (step 3 - stade1) . . . . . . . . . . . . . . . . . . . . 722
Parallel development (step 4 - stade1 and stade2). . . . . . . . . . . . . . . . . . 723
Resolving conflicts (step 5 - stade1) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 724
Versioning (step 6 - stade1) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 730
CVS resource history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731
Branches in CVS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 733
Branching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 734
Merging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736
Defining branch tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739
Working with patches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740
Creating a patch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740
Applying a patch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742
Disconnecting a project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746

Chapter 23. Using ClearCase . . . . . . . . . . . . . . . . . . . . . ....... ...... . 747


What is Rational ClearCase? . . . . . . . . . . . . . . . . . . . . . . . ....... ...... . 748
Basic ClearCase terminology . . . . . . . . . . . . . . . . . . . . . . . ....... ...... . 749
Installing ClearCase LT . . . . . . . . . . . . . . . . . . . . . . . . . . . ....... ...... . 749

Contents xv
Installing ClearCase LT Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750
Installing the ClearCase LT client . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 752
ClearCase integration with Application Developer . . . . . . . . . . . . . . . . . . . . . 752
ClearCase help in Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . 753
ClearCase preferences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
Using ClearCase with Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . 754
Setting up ClearCase for a new project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
Creating a new VOB . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
Creating new ClearCase project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
Joining a ClearCase project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
Creating a Web project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 762
Adding a project to ClearCase source control. . . . . . . . . . . . . . . . . . . . . . 762
Development scenario . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765
Developer 1 adds a servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765
Developer 1 delivers work to the integration stream . . . . . . . . . . . . . . . . . 768
Developer 1 makes a baseline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770
Developer 2 joins the project. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 772
Developer 2 imports projects into Application Developer . . . . . . . . . . . . . 774
Developer 2 adds a new servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 776
Developer 2 delivers work to the integration stream . . . . . . . . . . . . . . . . . 778
Developer 2 makes a new baseline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
Developers synchronize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 782

Part 6. Appendixes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 783

Appendix A. Product installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785


Installing DB2 UDB. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
Installing WebSphere Application Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
Hardware prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
Software prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
Installation Application Server 5.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
Verifying the installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
Installing Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
Hardware prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
Software prerequisites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 790
Installing Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
Installing the Agent Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 792
Update Application Developer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793
Using the Update Manager . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 793
Manual update . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798

Appendix B. Keyboard shortcuts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 801


Workbench shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802

xvi WebSphere Studio Application Developer Version 5 Programming Guide


Editing shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 802
Java editor shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
Java development tools shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804
Debug perspective shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
Page and CSS Designer shortcuts. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
Page Designer source page shortcuts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807

Appendix C. Additional material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809


Locating the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
Using the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810
System requirements for downloading the Web material . . . . . . . . . . . . . 810
How to use the Web material . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810
Installing the EJBBANK database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811
Installing the ItsoProGuide.ear file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 812
Installing the server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814
Installing other projects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814
DB2 user ID and password . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814

Abbreviations and acronyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815

Related publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817


IBM Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817
Other publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 818
Online resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 818
How to get IBM Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 821

Contents xvii
xviii WebSphere Studio Application Developer Version 5 Programming Guide
Notices

This information was developed for products and services offered in the U.S.A.

IBM may not offer the products, services, or features discussed in this document in other countries. Consult
your local IBM representative for information on the products and services currently available in your area.
Any reference to an IBM product, program, or service is not intended to state or imply that only that IBM
product, program, or service may be used. Any functionally equivalent product, program, or service that
does not infringe any IBM intellectual property right may be used instead. However, it is the user's
responsibility to evaluate and verify the operation of any non-IBM product, program, or service.

IBM may have patents or pending patent applications covering subject matter described in this document.
The furnishing of this document does not give you any license to these patents. You can send license
inquiries, in writing, to:
IBM Director of Licensing, IBM Corporation, North Castle Drive Armonk, NY 10504-1785 U.S.A.
The following paragraph does not apply to the United Kingdom or any other country where such provisions
are inconsistent with local law: INTERNATIONAL BUSINESS MACHINES CORPORATION PROVIDES
THIS PUBLICATION "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF NON-INFRINGEMENT,
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Some states do not allow disclaimer
of express or implied warranties in certain transactions, therefore, this statement may not apply to you.

This information could include technical inaccuracies or typographical errors. Changes are periodically made
to the information herein; these changes will be incorporated in new editions of the publication. IBM may
make improvements and/or changes in the product(s) and/or the program(s) described in this publication at
any time without notice.

Any references in this information to non-IBM Web sites are provided for convenience only and do not in any
manner serve as an endorsement of those Web sites. The materials at those Web sites are not part of the
materials for this IBM product and use of those Web sites is at your own risk.

IBM may use or distribute any of the information you supply in any way it believes appropriate without
incurring any obligation to you.

Information concerning non-IBM products was obtained from the suppliers of those products, their published
announcements or other publicly available sources. IBM has not tested those products and cannot confirm
the accuracy of performance, compatibility or any other claims related to non-IBM products. Questions on
the capabilities of non-IBM products should be addressed to the suppliers of those products.

This information contains examples of data and reports used in daily business operations. To illustrate them
as completely as possible, the examples include the names of individuals, companies, brands, and products.
All of these names are fictitious and any similarity to the names and addresses used by an actual business
enterprise is entirely coincidental.

COPYRIGHT LICENSE:
This information contains sample application programs in source language, which illustrates programming
techniques on various operating platforms. You may copy, modify, and distribute these sample programs in
any form without payment to IBM, for the purposes of developing, using, marketing or distributing application
programs conforming to the application programming interface for the operating platform for which the
sample programs are written. These examples have not been thoroughly tested under all conditions. IBM,
therefore, cannot guarantee or imply reliability, serviceability, or function of these programs. You may copy,
modify, and distribute these sample programs in any form without payment to IBM for the purposes of
developing, using, marketing, or distributing application programs conforming to IBM's application
programming interfaces.

© Copyright IBM Corp. 2003. All rights reserved. xix


Trademarks
The following terms are trademarks of the International Business Machines Corporation in the United States,
other countries, or both:

AIX® ^™ Redbooks™
BookMaster® Informix® Redbooks (logo) ™
Cloudscape™ IBM® SAA®
CICS® ibm.com® VisualAge®
Domino™ IMS™ WebSphere®
DB2® Lotus® z/OS®
™ Notes®

The following terms are trademarks of International Business Machines Corporation and Rational Software
Corporation, in the United States, other countries or both.

ClearCase® Rational®

The following terms are trademarks of other companies:

Intel, Intel Inside (logos), MMX, and Pentium are trademarks of Intel Corporation in the United States, other
countries, or both.

Microsoft, Windows, Windows NT, and the Windows logo are trademarks of Microsoft Corporation in the
United States, other countries, or both.

Java and all Java-based trademarks and logos are trademarks or registered trademarks of Sun
Microsystems, Inc. in the United States, other countries, or both.

UNIX is a registered trademark of The Open Group in the United States and other countries.

SET, SET Secure Electronic Transaction, and the SET Logo are trademarks owned by SET Secure
Electronic Transaction LLC.

Other company, product, and service names may be trademarks or service marks of others.

xx WebSphere Studio Application Developer Version 5 Programming Guide


Preface

This IBM® Redbook is a programming guide for the application development


tool, WebSphere® Studio Application Developer V5. This tool is not only
intended for the Java™ developer, but also for the Web designer who creates
Web pages. The WebSphere Studio Application Developer basic tooling and
team environment is presented along with the development and deployment of
Web applications.

WebSphere Studio Application Developer provides integrated development tools


for all e-business development roles, including Web developers, Java
developers, business analysts, architects, and enterprise programmers. The
customizable, targeted, role-based approach of WebSphere Studio Application
Developer will be characteristic of all new products built on the WebSphere
Studio Workbench. It is well integrated with WebSphere Application Server and
provides built-in server test environments that can be used for testing and
profiling Web applications.

This redbook consists of six parts:


򐂰 Introducing WebSphere Studio Application Developer
򐂰 Developing applications
򐂰 Testing and debugging applications
򐂰 Deploying and profiling applications
򐂰 Team programming
򐂰 Appendixes and additional material

© Copyright IBM Corp. 2003. All rights reserved. xxi


The team that wrote this redbook
This redbook was produced by a team of specialists from around the world
working at the International Technical Support Organization, Raleigh Center.

Ian Maik Ueli Fabio Henrik

Ueli Wahli is a Consultant IT Specialist at the IBM International Technical


Support Organization in San Jose, California. Before joining the ITSO 19 years
ago, Ueli worked in technical support at IBM Switzerland. He writes extensively
and teaches IBM classes worldwide on application development, object
technology, VisualAge® for Java, WebSphere Application Server, and lately
WebSphere Studio products. In his ITSO career Ueli has produced over 25 IBM
Redbooks™. Ueli holds a degree in Mathematics from the Swiss Federal
Institute of Technology.

Ian Brown is a Consultant for ASTECH Solutions Inc. in Aurora, Ontario,


Canada. He has 5 years of experience in the field of information technology, and
2 years of experience in analysis, design and development of Web and J2EE
applications. He holds a degree in Computer Science from the University of
Waterloo. His areas of expertise include application development using the
Eclipse platform, Java, and WebSphere Application Server administration.

Fabio Ferraz is the Chief Consultant for e-Voilà Enabling in Rio de Janeiro,
Brazil. He has years 11 years of experience in the IT field, and 8 of those
dedicated to e-business.

xxii WebSphere Studio Application Developer Version 5 Programming Guide


Maik Schumacher is an IT Specialist at IBM Software Services for Lotus® in
Cologne, Germany. He has 9 years of experience in the field of information
technology and he has been with IBM for two years, mainly working on an
architecture of e-business solutions. Maik is a Principal Certified Lotus
Professional and holds a degree in Computer Science with Business from the
University of Applied Sciences in Dortmund, Germany. His areas of expertise are
in software development, e-business, and Internet design.

Henrik Sjostrand is an Advisory IT Specialist working for IBM Sweden since 8


years. He has 12 years of experience in the field of information technology.
During his time with IBM he has had a number of different positions from
consulting and education to pre-sales activities. The last 3 years he has focused
on e-business application development, and WebSphere Application Server
architecture and deployment. Henrik is certified in WebSphere Application
Server 4.0 and holds a Master of Science in Electrical Engineering from
Chalmers University of Technology in Gothenburg, Sweden, where he lives.

Thanks to the following people for their contributions to this project:

Osamu Takagiwa, Joseph Korchmar, Arne Lindquist, and Martin Vojtko, who
wrote the original redbook, WebSphere Studio Application Developer
Programming Guide, SG24-6585.

Yvonne Lyon, for technical editing


International Technical Support Organization, San Jose Center

Become a published author


Join us for a two- to six-week residency program! Help write an IBM Redbook
dealing with specific products or solutions, while getting hands-on experience
with leading-edge technologies. You'll team with IBM technical professionals,
Business Partners and/or customers.

Your efforts will help increase product acceptance and customer satisfaction. As
a bonus, you'll develop a network of contacts in IBM development labs, and
increase your productivity and marketability.

Find out more about the residency program, browse the residency index, and
apply online at:
ibm.com/redbooks/residencies.html

Preface xxiii
Comments welcome
Your comments are important to us!

We want our Redbooks to be as helpful as possible. Send us your comments


about this or other Redbooks in one of the following ways:
򐂰 Use the online Contact us review redbook form found at:
ibm.com/redbooks
򐂰 Send your comments in an Internet note to:
[email protected]
򐂰 Mail your comments to:
IBM Corporation, International Technical Support Organization
Dept. HZ8 Building 662
P.O. Box 12195
Research Triangle Park, NC 27709-2195

xxiv WebSphere Studio Application Developer Version 5 Programming Guide


Summary of changes from SG24-6585
This section describes the technical changes made in this edition of the book and
in previous editions. This edition may also include minor corrections and editorial
changes that are not identified.

Summary of Changes
for SG24-6957-00
for WebSphere Studio Application Developer Version 5 Programming Guide
as created or updated on July 16, 2003.

July 2003, First Edition


This book is a major rewrite of WebSphere Studio Application Developer
Programming Guide, SG24-6585. The previous book was based on Application
Developer Version 4, this book is based on Version 5.

This revision reflects the addition, deletion, or modification of new and changed
information described below.

New information
򐂰 Support for J2EE 1.3, including EJB 2.0, Servlet 2.3, and JSP 1.2 levels
򐂰 New chapters on XML development, EJB development, Web services
development, Struts development, GUI application development
򐂰 Filters and listeners in Web development
򐂰 Support for DB2® stored procedures
򐂰 Component testing in the JUnit chapter
򐂰 Usability enhancements for Common Versions System

Changed information
򐂰 General update of existing information to Version 5

Deleted information
򐂰 Migration—covered very well in the migration guide that is shipped with the
product
򐂰 Plugin development—Very good information in a new book: The Java
Developer’s Guide to Eclipse (see “Other publications” on page 818)

Preface xxv
xxvi WebSphere Studio Application Developer Version 5 Programming Guide
Part 1

Part 1 Introducing
WebSphere Studio
Part 1 introduces WebSphere Studio Application Developer with concepts about
the Workbench, tools, workspace, perspectives, and projects.

© Copyright IBM Corp. 2003. All rights reserved. 1


2 WebSphere Studio Application Developer Version 5 Programming Guide
1

Chapter 1. Introduction and concepts


This chapter contains an introduction to the concepts behind Application
Developer. An overview of the features and the WebSphere Studio family is
provided as well. The following topics are discussed:
򐂰 Eclipse
򐂰 Platform architecture
򐂰 Workbench features
򐂰 WebSphere Studio products
򐂰 What is new in Application Developer Version 5
򐂰 Tools
򐂰 Sample code in this book

© Copyright IBM Corp. 2003. All rights reserved. 3


Introduction
WebSphere Studio Application Developer (hereafter called Application
Developer) is one of the WebSphere Studio family of products that has been
developed based on the Eclipse Workbench.

The Eclipse Workbench platform was designed by IBM and released to the open
source community. It is an open, portable, universal tooling platform that provides
frameworks, services, and tools for building tools.

In essence, the Workbench provides the tool infrastructure. With this


infrastructure in place, the tool builders are able to focus on the actual building of
their tools. The Workbench has been designed for maximum flexibility to support
the development of tools for new technologies that may emerge in the future.

Development environments written for the Workbench should support a


role-based development model, in which the outcomes of the developers’ work
will be consistent. The developers should not have to be concerned with how
different individual tools may be treating their files.

The WebSphere Studio product family is based on an integrated development


environment (IDE) for developing, testing, debugging, and deploying
applications. It provides support for each phase of the application development
life cycle.

Eclipse
Eclipse is an open platform for tool integration built by an open community of tool
providers. With a common public license that provides royalty free source code
and world wide redistribution rights, the Eclipse platform provides tool developers
with ultimate flexibility and control over their software technology.

Industry leaders like IBM, Borland, Merant, QNX Software Systems, Rational®
Software, RedHat, SuSE, TogetherSoft, and WebGain formed the initial
eclipse.org board of directors of the Eclipse open source project. Visit the
Eclipse Web Site for more information about the project:
http://www.eclipse.org

Platform architecture
Figure 1-1 shows an overview of the Eclipse platform.

4 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 1-1 Eclipse platform

Eclipse is a platform that has been designed from the ground up for building
integrated regardless of presentation technology and application development
tooling. By design, the platform itself does not provide a great deal of end user
functionality. The value of the platform is what it encourages: rapid development
of integrated features based on a plug-in model.

Eclipse provides a common user interface (UI) model for working with tools. It is
designed to run on multiple operating systems while providing robust integration
with each underlying OS. Plug-ins can be programmed to the Eclipse portable
APIs and run unchanged on any of the supported operating systems.

The Eclipse platform uses the model of a common Workbench to integrate the
tools from the end user's point of view. Tools that you develop can be plugged
into the Workbench using well defined hooks called extension points.

The underlying platform runtime uses the same extension model to allow plug-in
developers to add support for additional file types and customized installations,
such as Web servers, workgroup servers, and repositories. The artifacts for each
tool, such as files and other data, are coordinated by a common platform
resource model.

The platform gives the users a common way to work with the tools, and provides
integrated management of the resources they create with plug-ins.

Chapter 1. Introduction and concepts 5


Workbench features
The Eclipse Workbench provides a set of APIs, models, and frameworks for
developing source editors and other user interfaces, as well as access to
common services for resource management, debugging, and team
programming.

The main features of the Eclipse Workbench are:


򐂰 Plug-in based tooling
򐂰 Role-oriented development tools
򐂰 Vertical and horizontal integration
򐂰 Open standards
򐂰 Open team environment
򐂰 File based IDE

Plug-in based tooling


The Workbench provides a flexible plug-in platform. Different tools can plug in to
the Workbench, with each tool providing new functionality to be added to the
Workbench or to already existing plug-ins. Each plug-in integrates with the
Workbench and with the other tools. Ideally the end-user should not notice any
difference when moving from one tool to another.

By programming to the portable Eclipse APIs, plug-ins can run unchanged on


any of the supported operating systems using a common user interface model.
The Workbench is designed to run on multiple operating systems while providing
robust integration with each one.

At the core of Eclipse is an architecture for dynamic discovery of plug-ins. The


platform handles the logistics of the base environment and provides a standard
user navigation model. Each plug-in can focus on performing a small number of
tasks well, without having to provide the supporting infrastructure. Some
examples of such tasks are defining, testing, animating, publishing, compiling,
debugging, and diagramming.

Because the Workbench is based on an open architecture, each plug-in


development team can focus on their area of expertise. This enables the team
management experts to build the back-end interfaces and the usability experts to
build the end user tools. If these are well designed, and use the standard APIs,
significant new features and levels of integration can be added to the Workbench
and Workbench based products without impacting other tools.

6 WebSphere Studio Application Developer Version 5 Programming Guide


Role-oriented development with consistent look and feel
The Workbench is designed to provide special support for a particular e-business
development role, or for a set of roles.

Within the Workbench based products, task-oriented perspectives filter out much
of the overall complexity, and present the developer only with those functions that
are relevant to the task at hand.

Users can switch perspectives depending on what they are working on at any
given moment, or depending on their current role in the project.

Because different developers are accustomed to working in different ways, any


perspective can be further customized. And because all tools and perspectives
are built using the Eclipse Workbench technology, they share a common look and
feel, which reduces learning curves and help maximize developer productivity.

All development resources for all projects are stored in a single repository,
therefore developers have consistent team support for their projects, and are
able to easily share their work products.

Vertical and horizontal integration


Traditionally software vendors have provided vertical tools, forcing customers to
do their own integration. The purpose of the Eclipse Workbench is to provide a
platform that software vendors can easily extend. ISVs have already embraced
this technology and are actively building tools on this base.

As an example, every WebSphere Studio family of products that is built on the


Workbench offers a set of already integrated tools, freeing you to focus on
building applications rather than on integrating tools. Furthermore, you can easily
integrate other tools (from other vendors or locally developed), as long as they
conform to the Workbench standard plug-in protocol.

Open standards
The whole Eclipse Workbench, as well as all products of the WebSphere Studio
family of products, are built on open standards and the code that they generate
also complies with open standards.

This allows you to build and deploy state-of-the-art, server-side applications that
conform to the Servlet 2.2, JavaServer Pages 1.1, and EJB 1.1 specifications.

Chapter 1. Introduction and concepts 7


Open team development
Application development teams are becoming more distributed, more diverse,
and are under increasing pressure to deliver solutions quickly. In such an
environment it is critical to have development tools that can support these needs,
while at the same time addressing personalized requirements. The team
development environment for all products based on the Eclipse Workbench
supports pluggable repositories rather than mandating any proprietary
repository, and support an optimistic concurrency model.

File-based IDE
The Eclipse Workbench is a platform for building file-based IDEs. All content is
saved as files. Workbench resources, such as Java classes and HTML files, are
stored in the file system, making them easy to access.

WebSphere Studio products


The WebSphere Studio product family is built on top of the Eclipse Workbench as
a set of plug-ins conforming to the Workbench’s open standard APIs.

The WebSphere Studio family of products currently has the following members
(Figure 1-2):
򐂰 WebSphere Studio Site Developer Advanced
򐂰 WebSphere Studio Application Developer
򐂰 WebSphere Studio Application Developer Integration Edition
򐂰 WebSphere Studio Enterprise Developer

These products provide support for end-to-end development, testing, and


deployment of Web and J2EE applications.

The WebSphere Studio product family provide integrated development tools for
most e-business development roles including Web developers, Java developers,
business analysts, architects, and enterprise programmers. The customizable,
targeted and role-oriented approach of the Workbench will be a common
characteristic of future products in the WebSphere Studio family.

8 WebSphere Studio Application Developer Version 5 Programming Guide


Enterprise Developer
User: Enterprise
Application Developer Integration Edition Developer
Function:
Application Developer Create new EIS
applications as part
Site Developer User: Advanced J2EE of a J2EE app
Developer EGL Tools
User: Web Developer User: J2EE Developer
Function: Develop/Maintain
Function: Function:
Access existing EIS z/OS Apps
HTML/JSP/Servlet EJB Tools applications using COBOL
Struts Tools
Web Services Tools
+ Performance and
Trace tools
Component Test tools
+ JCA
Visual Service Flow + PL/I
ASM
XML Tools Choreography COBOL XML
Java Visual Editor ClearCase LT OEM Target Runtime: Enablement
Target Runtime: Target Runtime: WAS AE, ND, WAS E Target Runtime: WAS
WAS AE, WAS ND WAS AE, WAS ND AE, ND, WAS E, z/OS

WebSphere Studio Workbench


IBM's commerically supported version of Eclipse Basis for IBM Tooling

Eclipse Workbench
Provides frameworks for tool builders
to focus on tool building

Figure 1-2 WebSphere Studio family

WebSphere Studio Site Developer


Site Developer is an IDE intended for Web developers who develop and manage
complex Web sites. It is an easy-to-use environment that minimizes the time and
effort required to create, manage, and debug multi-platform Web sites. It is
designed according to the J2SE and J2EE specifications and supports JSPs,
servlets, HTML, JavaScript, and DHTML. It further includes tools for developing
images and animated GIFs.

Site Developer enables Web developers to use their favorite content creation
tools in conjunction with the built-in local and remote publishing capabilities.

Using Site Developer, you can develop Web applications that use the following
technologies.
򐂰 JSPs—A simple, fast, and consistent way to extend Web server functionality
and create dynamic Web content. JSPs enable rapid development of Web
applications that are server and platform-independent.
򐂰 Servlets—Server code that executes within a Web Application Server.
򐂰 Web services—Self-contained, modular applications that can be described,
published, located, and invoked over the Internet or within intranets.

Chapter 1. Introduction and concepts 9


WebSphere Studio Application Developer
Application Developer is designed for professional developers of Java and J2EE
applications, who require integrated Java, Web, XML, and Web services support.

It includes all of the features of Site Developer, and adds tools for developing EJB
applications, as well as performance profiling and logging tools for both local and
remote execution.

Developers can quickly build and test business logic and enhance the
presentation artifacts with built-in Web creation tools inside the Application
Developer IDE before deploying to a production server.

Using the performance profiling and tracing tools, it is possible to detect


application performance bottlenecks early in the development cycle.
Furthermore, the built-in test environment for WebSphere Application Server and
advanced tools for code generation help shorten the test cycle.

WebSphere Studio Application Developer Integration Edition


Integration Edition includes all of the functionality in Application Developer, plus:
򐂰 Powerful graphical tools to help you quickly and easily build custom
application adapters to integrate your J2EE application with your back-end
systems, helping you save time and money by reusing existing resources.
򐂰 Visual flow-based tools that increase developers productivity by allowing them
to visually define the sequence and flow of information between application
artifacts such as adapters, Enterprise JavaBeans components and Web
services.
򐂰 Wizards that help in building and deploying complex Web services out of
adapters, EJB components, flows, and other Web services.
򐂰 Support for the full set of Enterprise services provided by WebSphere
Application Server Enterprise Edition such as business rule beans,
internationalization, and work areas that deliver additional integration
capabilities, developer productivity, and business agility.

WebSphere Enterprise Developer


Enterprise Developer includes all of the functionality in WebSphere Studio
Application Developer Integration Edition, plus among others:
򐂰 Integrating transactional environments such as CICS® and IMS™
򐂰 Creating new EIS applications as part of a J2EE application
򐂰 Developing and maintaining z/OS® applications
򐂰 Supporting Java, COBOL, PL/I, and EGL (enterprise generation language)
development

10 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Implementing Struts-based MVC applications using connectors and EGL.

Here is another core technology that is integrated within Enterprise Developer:


򐂰 WebSphere Studio Asset Analyzer (WSAA)—Identifies application processes
and connecting points, and provides the ability to generate components from
existing code.

Enterprise Developer provides a visual construction and assembly based


environment supporting the implementation of enterprise level applications,
including support for the multiple developer roles and technologies required by
those applications. Some examples of technologies supported are HTML, JSPs,
servlets, EJBs, COBOL, EGL, PL/I, and connectors.

What is new in Application Developer Version 5


Application Developer Version 5 contains many new and improved features. For
details about changes to specific product features, refer to the readme file located
in the readme subdirectory of both the installation CD and the WebSphere Studio
installation directory (Windows® users can also access the readme file directly
from the Start menu, after installing WebSphere Studio).

Here are some highlights of the new features:


򐂰 Support for J2EE 1.3, including EJB 2.0, Servlet 2.3, and JSP 1.2 levels
򐂰 Concurrent support for WebSphere Application Server V4 (J2EE 1.2) and
WebSphere Application Server V5 (J2EE 1.3)
򐂰 Enables WebSphere Application Server Version 4 users to adopt the latest
innovations from Eclipse Version 2, and enhancements from Application
Developer Version 5 without server upgrade
򐂰 Numerous updates and new functions for Java, Web services, XML,
Database, Test and Analysis, and Web components
򐂰 Specialized support for Struts, which is a set of Java classes and JSP tag
libraries that provide a conceptual framework for developing Web applications
򐂰 New Visual Editor for Java (Java-based client for building GUI components
with Swing or AWT)
򐂰 XSL source editor; new wizards to help you create your XSL files

Chapter 1. Introduction and concepts 11


Migration from previous versions
The root directory of Application Developer’s installation CD contains a migration
guide that is provided in the migrate.pdf and the migrate.html files.

This migration guide discusses how you can:


򐂰 Target WebSphere Application Server Version 4.0.x versus Version 5
򐂰 Migrate from WebSphere Studio Application Developer Version 4.0.x
򐂰 Migrate from WebSphere Studio Application Developer Version 5 Beta
򐂰 Migrate from WebSphere Studio Classic to WebSphere Studio Application
Developer
򐂰 Migrate from VisualAge for Java to WebSphere Studio Application Developer
򐂰 Migrate from WebSphere Studio Application Developer for Linux
򐂰 Migrate enterprise beans from VisualAge for Java to WebSphere Studio
Application Developer
򐂰 Migrate from EJB 1.0 to EJB 1.1 or to EJB 2.0
򐂰 Migrate from VisualAge for Java Visual Composition Editor to Visual Editor for
Java
򐂰 Convert from VisualAge for Java Persistence Builder to EJB 2.0
򐂰 Build setup (library JARs, dependant project JARs, Ant builds)

The migration guide also provides some migration examples that show you, step
by step, how to migrate to Version 5 from previous versions.

Tools
The WebSphere Studio product family include the following basic tools:
򐂰 Web development
򐂰 Relational database
򐂰 XML
򐂰 Java development
򐂰 Web services development
򐂰 Team collaboration
򐂰 Integrated debugger
򐂰 Server tools for testing and deployment
򐂰 Enterprise JavaBean development tools (not in Site Developer Advanced)
򐂰 Performance profiling (not in Site Developer Advanced)
򐂰 Plug-in development

12 WebSphere Studio Application Developer Version 5 Programming Guide


Web development tools
The professional Web development environment provides the necessary tools to
develop sophisticated Web applications consisting of static HTML pages, JSPs,
servlets, XML deployment descriptors, and other resources.

Wizards are available to generate ready to run Web applications based on SQL
queries and JavaBeans. Links between Web pages can be automatically
updated when content is moved or renamed.

The Web development environment brings all aspects of Web application


development into one common interface. Everyone on your Web development
team, including content authors, graphic artists, programmers, and Web
masters, can work on the same projects and access the files they need.

Such an integrated Web development environment makes it easy to


collaboratively create, assemble, publish, deploy, and maintain dynamic,
interactive Web applications.

The Web development tools provide the following features:


򐂰 Support for latest Web technology with an intuitive user interface
򐂰 Advanced scripting support to create client-side dynamic applications with
VBScript or JavaScript
򐂰 Web Art Designer to create graphic titles, logos, buttons, and photo frames
with professional-looking touches
򐂰 Animated GIF Designer to create life-like animation from still pictures,
graphics, and animated banners
򐂰 Over 2,000 images and sounds in the built-in library
򐂰 Integrated, easy-to-use visual layout tool for JSP and HTML file creation and
editing
򐂰 Web project creation, using the J2EE-defined hierarchy
򐂰 Creation and visual editing of the Web application deployment descriptor
(web.xml) file
򐂰 Automatic update of links as resources are moved or renamed
򐂰 A wizard for creating servlets
򐂰 Generation of Web applications from database queries and JavaBeans
򐂰 J2EE WAR/EAR deployment support (not in Site Developer)
򐂰 Integration with the WebSphere unit test environment

Chapter 1. Introduction and concepts 13


Relational database tools
The database tools provided with the WebSphere family products allow you to
create and manipulate the data design for your project in terms of relational
database schemas.

You can explore, import, design, and query databases working with a local copy
of an already existing design. You can also create an entirely new data design
from scratch to meet your requirements.

The database tools provide a metadata model used by all other tools that need
relational database information, including database connection information. In
that way, tools, although unaware of each other, are able to share connections.

The SQL Statement Wizard and SQL Query Builder provide a GUI-based
interface for creating and executing SQL statements. When you are satisfied with
your statement, you can use the SQL to XML Wizard to create an XML
document, as well as XSL, DTD, XSD, HTML, and other related artifacts.

The relational database tools support connecting to, and importing from, several
database types, including DB2, Oracle, SQL Server, Sybase, and Informix®.

XML tools
The comprehensive XML toolset provided by the WebSphere Studio family of
products includes components for building DTDs, XML schemas (XSD) and XML
files. With the XML tools you can perform all of the following tasks:
򐂰 Create, view, and validate DTDs, XML schemas, and XML files.
򐂰 Create XML documents from a DTD, from an XML schema, or from scratch.
򐂰 Generate JavaBeans from a DTD or XML schema.
򐂰 Define mappings between XML documents and generate XSLT scripts that
transform documents.
򐂰 Create an HTML or XML document by applying an XSL style sheet to an XML
document.
򐂰 Map XML files to create an XSL transformation script and to visually step
through the XSL file.
򐂰 Define mappings between relational tables and DTD files, or between SQL
statements and DTD files, to generate a document access definition (DAD)
script, used by IBM DB2 XML Extender. This can be used either to compose
XML documents from existing DB2 data or to decompose XML documents
into DB2 data.
򐂰 Generate DADX, XML, and related artifacts from SQL statements and use
these files to implement your query in other applications.

14 WebSphere Studio Application Developer Version 5 Programming Guide


Java development tools (JDT)
All WebSphere Studio family of products provide a professional-grade Java
development environment with the following capabilities:
򐂰 Application Developer Version 5 ships with JDK 1.3
򐂰 Pluggable run-time support for JRE switching and targeting of multiple
run-time environments from IBM and other vendors
򐂰 Incremental compilation
򐂰 Ability to run code with errors in methods
򐂰 Crash protection and auto-recovery
򐂰 Error reporting and correction
򐂰 Java text editor with full syntax highlighting and complete content assist
򐂰 Refactoring tools for reorganizing Java applications
򐂰 Intelligent search, compare, and merge tools for Java source files
򐂰 Scrapbook for evaluating code snippets

Web services development tools


Web services represent the next level of function and efficiency in e-business.
Web services are modular, standards-based e-business applications that
businesses can dynamically mix and match in order to perform complex
transactions with minimal programming.

The WebSphere Studio family of products that include the Web services feature,
help you to build and deploy Web services-enabled applications across the
broadest range of software and hardware platforms used by today's businesses.
These tools are based on open, cross-platform standards such as Simple Object
Access Protocol (SOAP), Web Services Description Language (WSDL), and
Universal Description Discovery and Integration (UDDI).

EJB development tools


The WebSphere Studio family of products, except Site Developer Advanced,
feature full EJB support (Application Developer V5 supports EJB 1.1 and 2.0), an
updated EJB test client, an enhanced unit test environment for J2EE, and
deployment support for Web application archive (WAR) files and enterprise
application archive (EAR) files. Entity beans can be mapped to databases, and
EJB components can be generated to tie into transaction processing systems.
XML provides an extended format for deployment descriptors within EJB.

Chapter 1. Introduction and concepts 15


Team collaboration
Team developers do all of their work in their individual Workbenches, and then
periodically release changes to the team code. This model allows individual
developers to work on a team project, share their work with others as changes
are made, and access the work of other developers as the project evolves. At any
time, developers can update their Workbenches by retrieving the changes that
have been made to the team code.

All products of the WebSphere Studio family support the Concurrent Versions
System (CVS) and the Rational ClearCase® LT products.

Other software configuration management (SCM) repositories can be integrated


through the Eclipse Workbench SCM adapters. SCM adapters for commercial
products are provided by the vendors of those products.

Debugging tools
The WebSphere Studio family of products include a debugger that enables you to
detect and diagnose errors in your programs running either locally or remotely.
The debugger allows you to control the execution of your program by setting
breakpoints, suspending launches, stepping through your code, and examining
the contents of variables.

You can debug live server-side code as well as programs running locally on your
workstation.

The debugger includes a debug view that shows threads and stack frames, a
process view that shows all currently running and recently terminated processes,
and a console view that allows developers to interact with running processes.
There are also views that display breakpoints and allow you to inspect variables.

Performance profiling tools


The WebSphere Studio family of products (except for Site Developer) provide
tools that enable you to test the performance of your application. This allows you
to make architectural and implementation changes early in your development
cycle, and significantly reduces the risk of finding serious problems in the final
performance tests.

The profiling tools collect data related to a Java program's run-time behavior, and
present this data in graphical and non-graphical views. This assists you in
visualizing program execution and exploring different patterns within the
program.

16 WebSphere Studio Application Developer Version 5 Programming Guide


These tools are useful for performance analysis and for gaining a deeper
understanding of your Java programs. You can view object creation and garbage
collection, execution sequences, thread interaction, and object references. The
tools also show you which operations take the most time, and help you find and
plug memory leaks. You can easily identify repetitive execution behavior and
eliminate redundancy, while focusing on the highlights of the execution.

Server tools for testing and deployment


The server tools provide a unit test environment where you can test JSPs,
servlets and HTML files, (EJB testing is supported in Application Developer and
Enterprise Developer). You also have the capability to configure other local or
remote servers for integrated testing and debugging of J2EE applications.

The following features are included:


򐂰 A copy of the complete WebSphere Application Server run-time environment.
򐂰 Standalone unit testing.
򐂰 Ability to debug live server-side code using the integrated debugger.
򐂰 Support for configuring multiple servers.

The server tools support the following run-time environments, which can be
installed locally or remotely and support testing of Web applications:
򐂰 WebSphere Application Server Version 5.0
򐂰 WebSphere Application Server Express Version 5.0
򐂰 WebSphere Application Server Version 4.0 (AEs)
򐂰 Apache Tomcat Version 4.1
򐂰 Apache Tomcat Version 4.0
򐂰 Apache Tomcat Version 3.2

Plug-in development tools


The WebSphere Studio product family (except for Site Developer) include the
plug-in development environment (PDE) that is designed to help you develop
platform plug-ins while working inside the platform Workbench and it provides a
set of platform extension contributions (views, editors, perspectives, etc.) that
collectively streamline the process of developing plug-ins inside the Workbench.
The PDE is not a separate tool, but it is a perspective.

The following project types are supported:


򐂰 Plug-in project—Application Developer is based on the concept of plug-ins
that have a clearly defined structure and specification. This project supports
the ability to create, test, and deploy a plug-in in the PDE.

Chapter 1. Introduction and concepts 17


򐂰 Fragment project—A plug-in fragment is used to provide additional plug-in
functionality to an existing plug-in after it has been installed. Fragments are
ideal for shipping features like language or maintenance packs that typically
trail the initial products by a few months.
򐂰 Plug-in component—PDE attaches a special component nature to plug-in and
fragment projects to differentiate them from other project types. The project
must have a specific folder structure and a component manifest. The project
must be set up with references to all of the plug-in and fragment projects that
will be packaged into the component.

Sample code in this book


All the code examples in this book are based on a banking model (Figure 1-3).
This model was used in the IBM Redbook EJB 2.0 Development with WebSphere
Studio Application Developer, SG24-6819.

business logic
Bank
Deposit, Withdraw,
1:m Transfer

Customer
update create

m:m
1:m
Account TransRecord

Checking Savings

Figure 1-3 Banking model

The banking model is supported by a relational database called EJBBANK. In this


book we only use a subset of the model: Customer, Account, and TransRecord.

For simple Java and Web development we implement the model in memory. For
advanced development, such as Web with database and EJB, we use the
relational database.

18 WebSphere Studio Application Developer Version 5 Programming Guide


EJBBANK database
The database consist of the tables shown in Table 1-1. Only the shaded tables
are used in the examples in this document.

Table 1-1 EJBBank tables


Table Description

CUSTOMER Bank customer with ID, title, firstname, lastname, user ID, password,
and address.

ACCOUNT Bank account with ID, balance, interest rate, account type, overdraft
amount (CHECKING) and minimum amount (SAVINGS).

TRANSRECORD Transaction record with ID, account ID, transaction type (deposit,
withdraw), and amount.

CUSTACCT Relationship table between CUSTOMER and ACCOUNT.

CUSTADDRESS Customer address with customer ID, street, city, state, zipcode (not
used in this book).

CUSTOMERINFO Customer information, for example picture (not used in this book).

CHECKING Checking account, subtype of account, with overdraft amount (not


used in this book)

SAVINGS Savings account, subtype of account, with minimum amount (not


used in this book).

See Appendix C, “Additional material” on page 809 for instructions on how to


create and load the EJBBANK database.

Naming convention
All projects and packages used in this book follow a naming convention:
򐂰 ItsoProGuideXxxxx for projects
򐂰 itso.xxxx for packages

Chapter 1. Introduction and concepts 19


Summary
This chapter introduced the concepts behind Application Developer and gave an
overview of the features of the various members of the WebSphere Studio family
of tools. The following topics were discussed:
򐂰 Eclipse
򐂰 Platform architecture
򐂰 Workbench features
򐂰 WebSphere Studio products
򐂰 What is new in Application Developer Version 5
򐂰 Tools
򐂰 Sample code in this book

20 WebSphere Studio Application Developer Version 5 Programming Guide


2

Chapter 2. Setting up your Workbench


and workspace preferences
After you have installed Application Developer, and before you start creating your
projects, you may want to modify some of the default Workbench settings to suit
your needs or site standards. This chapter describes the most important areas
where you can customize the Application Developer setup.

The following topics are discussed in this chapter:


򐂰 Workbench basics
򐂰 Java development preferences

Note: Installation of Application Developer is covered in Appendix A, “Product


installation” on page 785.

© Copyright IBM Corp. 2003. All rights reserved. 21


Workbench basics
Once you have started Application Developer, you will see it opened in a single
window. Application Developer initially displays a perspective — the J2EE
perspective. A perspective contains views, such as the J2EE Navigator view, and
editors. More information regarding perspectives and views are provided in
Chapter 3, “Perspectives, views, and editors” on page 47.

Figure 2-1 shows Application Developer’s initial Workbench.

Figure 2-1 Application Developer Workbench

At the far left of the window is a shortcut bar that allows you to open new
perspectives and navigate between perspectives that are already open. The
name of the active perspective is shown in the title of the window and its icon in
the shortcut bar (left side) is a pushed button.

The J2EE Hierarchy, Tasks, and Outline views are open, along with an editor on
the welcome page. The welcome page provides a quick starting point if you are
eager to customize your Workbench or learn about other installed features.

22 WebSphere Studio Application Developer Version 5 Programming Guide


The term Workbench refers to the desktop development environment. Each
Workbench window of Application Developer contains one or more perspectives.
Perspectives contain views and editors and control what appears in certain
menus and toolbars.

Workspace basics
The Application Developer workspace is a private work area for the individual
developer. It holds the environment metadata and the loaded projects’ data in
regular files.

Every time you save a resource, the changes are reflected in the file system.
Normally this is your local file system, but you can also choose to store your
workspace in a network file system (NFS) as well.

Note: The advantages of storing workspaces in NFSs are such as ease of


backup—it is easier for the administrators to back up a team’s workspaces if
they all stand in the same machine—and increased mobility, as you may
connect to the workspace from any machine on the network. The
disadvantage, though, is decreased performance and mobility (laptop).

Application Developer also allows you to open more than one Workbench at a
time. To open a new Workbench in another window, click Window -> New
Window and a new Workbench with the same perspective opens in a new
window.

If you do not specify otherwise, Application Developer creates a default


workspace which is placed in the directory:
My Documents\IBM\wsad\workspace

However, you can change the default workspace by starting Application


Developer with the -data workspacePath parameter where the workspacePath
points to your preferred workspace directory. Relative paths are interpreted
relative to the directory that Application Developer was started from.

Tip: If for some reason you ever need to clean your workspace and start over
from scratch, the quickest way would be to exit Application Developer and
rename the workspace directory. Upon restarting Application Developer, you
would have a clean workspace. You could then import the resources that you
still require from the old workspace directory.

Chapter 2. Setting up your Workbench and workspace preferences 23


By using the -data parameter you can start a second instance of Application
Developer that uses a different workspace. To start a new instance of Application
Developer, start Application Developer with the -data workspacePath parameter.

For example, if your second instance should use the NewWorkspace workspace
folder, you can launch Application Developer with this command (this assumes
Application Developer has been installed in the default installation directory):
c:\Program Files\IBM\WebSphere Studio\wsappdev.exe -data c:\NewWorkspace

There are a number of parameters that you can add when launching Application
Developer (Table 2-1).

Table 2-1 Startup parameters


Command Description

-data workspacedirectory Start Application Developer with a specific workspace.

-configuration The location for the platform configuration file,


configurationFileURL expressed as a URL. The configuration file determines
the location of the platform, the set of available plug-ins,
and the primary feature. Note that relative URLs are not
allowed. The configuration file is written to this location
when Application Developer is installed or updated.

-vm vmPath This optional option allows you to set the location of Java
Runtime Environment (JRE) to use to run Application
Developer. Relative paths are interpreted relative to the
directory that Eclipse was started from.

-vmargs -Xmx256M For large-scale development you should modify your VM


arguments to make more heap available. This example
allows the Java heap to grow to 256MB. This may not be
enough for large projects.

-debug [optionsFileURL] Puts the platform in debug mode and loads the debug
options from the file at the given URL, if specified. This
file indicates which debug points are available for a
plug-in and whether or not they are enabled. If a file path
is not given, the platform looks in the directory that
Application Developer was started from for a file called
".options". Note that relative URLs are not allowed.

-consolelog Mirrors the Eclipse platform's error log to the console


used to run Eclipse. Handy when combined with -debug.

-setworkspace This flag forces Application Developer to display a


prompt dialog for selecting of the workspace directory.

24 WebSphere Studio Application Developer Version 5 Programming Guide


Setting the workspace with a prompt dialog
If you specify the flag -setworkspace, Application Developer displays a startup
dialog for selecting the workspace directory (Figure 2-2).

Figure 2-2 Select workspace

Do not select the check box Use this workspace as the default..., otherwise you
are not prompted again.

Tip: If you want to work with multiple workspaces create a duplicate startup
icon for Application Developer and use the -data flag to point to the
workspace.

All other startup parameters are described in Application Developer’s help facility.

Memory consideration
Use the -vmargs flag to set limits to the memory that is used by Application
Developer.

For example, with only 512 MB RAM you may be able to get better performance
by limiting the memory:
-vmargs -Xmx150M

You can also modify VMArgs initialization parameters in the wsappdev.ini file (in
the installation directory):
VMArgs=-Xms64M -Xmx150M -Xquickstart -Xgcpolicy:optavgpause

These arguments significantly limit the memory utilization. Setting the -Xmx
argument below 150M does begin to degrade performance.

For more information on memory management for the built-in WebSphere server,
see “Environment page” on page 547.

Chapter 2. Setting up your Workbench and workspace preferences 25


Application Developer’s log files
Application Developer provides logging facilities for plug-in developers to log and
trace important events, primarily expected or unexpected errors. Log files are a
crucial part of the Application Developer problem determination process.

The only reason to use log files is if you encounter unexpected program behavior.
In some cases, an error message tells you explicitly to look at the error log.

There are two main log files in the .metadata directory of the workspace folder:
򐂰 .log—The .log file is used by the Workbench to capture errors, and any
uncaught exceptions from plug-ins. The .log file is cumulative, each new
session of Application Developer appends its messages to the end of the .log
file without deleting any previous messages. This enables you to see a history
of past messages over multiple Application Developer sessions, each one
starting with the !SESSION string.
򐂰 LoggingUtil.log—The LoggingUtil.log file is provided by the Application
Developer specific tools (a set of plug-ins added on top of the Workbench).
The Application Developer plug-ins use LoggingUtil.log to log various
events, errors, and caught exceptions through a logging API.

Both log files are ASCII files and can be viewed with any text editor.

Preferences
Application Developer’s preferences can be modified by selecting Window ->
Preferences from the menu bar. Opening the preferences displays the dialog
shown in Figure 2-3.

In the left pane you can navigate through many entries. Each entry has its own
preferences page, where you can change the initial options.

This section describes the most important options. Application Developer’s help
manual contains a complete description of all options available in the preferences
dialogs.

Tip: Each page of Application Developer’s preferences dialog contains a


Restore Defaults button. When you click this button, Application Developer
restores the settings of the current dialog to its initial values.

26 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 2-3 Workbench preferences

Automatic builds
By default, builds in Application Developer are done automatically whenever a
resource has been modified and saved. If you require more control regarding
builds you can disable the auto-building feature. To perform a build you have to
explicitly start it. This may be a desirable in cases where you know that building is
of no value until you finish a large set of changes.

If you want to turn off the automatic build feature, select Windows -> Preferences
-> Workbench and deselect the Perform build automatically on resource
modification check box (see previous Figure 2-3).

Chapter 2. Setting up your Workbench and workspace preferences 27


In this dialog you can also specify whether or not you want unsaved resources to
be saved before performing a manual build. Check the Save all modified
resources automatically prior to manual build check box to enable this feature.

File associations
The File Associations preferences page (Figure 2-4) enables you to add or
remove file types recognized by the Workbench. You can also associate editors
or external programs with file types in the file types list.

Figure 2-4 File associations preferences

The top right pane allows you to add and remove the file types. The bottom right
pane allows you to add or remove the associated editors.

If you want to add, for example, the Internet Explorer as an additional program to
open your .gif files, select *.gif from the file types list and click Add next to the
associated editors pane.

28 WebSphere Studio Application Developer Version 5 Programming Guide


A new dialog opens (Figure 2-5) where you have to select the External Programs
option, then click Browse and select iexplore.exe from the folder where Internet
Explorer is installed and confirm the dialog with Open.

Figure 2-5 File association editor selection

Confirm the Editor Selection dialog with OK and you will notice that the program
has been added to the editors list. Optionally you can set this program as the
default program for this file type by clicking Default.

Now you can open the file by using the context menu on the file and select Open
With and select the appropriate program.

Local history
A local edit history of a file is maintained when you create or modify a file. A copy
is saved each time you edit and save the file. This allows you to replace the
current file with a previous edit or even restore a deleted file. You can also
compare the content of all the local edits. Each edit in the local history is uniquely
represented by the data and time the file has been saved.

Note: Only files have local history. Projects and folders do not have a local
history.

Chapter 2. Setting up your Workbench and workspace preferences 29


To compare a file with the local history, select Compare With -> Local History
from its context menu. To replace a file with an edit from the local history, select
Replace With -> Local History from its context menu.

Select Window -> Preferences -> Workbench -> Local History to open its
preferences page (Figure 2-6).

Figure 2-6 Local history preferences

Table 2-2 explains the options for the local history preferences.

Table 2-2 Local history settings


Option Description

Days to keep files Indicates for how many days you want to maintain changes
in the local history. History state older than this value will be
lost.

Entries per file This option indicates how many history states per file you
want to maintain in the local history. If you exceed this value,
you will lose older history to make room for new history.

Maximum file size (MB) Indicates the maximum size of individual states in the history
store. If a file is over this size, it will not be stored.

30 WebSphere Studio Application Developer Version 5 Programming Guide


Perspectives preferences
The Perspectives preferences page enables you to manage the various
perspectives defined in the Workbench. To open the page, click Window ->
Preferences -> Workbench -> Perspectives (Figure 2-7).

Figure 2-7 Perspectives preferences

Here you can change the following options:


򐂰 Open a new perspective in the same or in a new window
򐂰 Open a new view within the perspective or as a fast view (docked to the side
of the current perspective)
򐂰 Open a new project in the same window, in a new window or do not switch the
perspective

Chapter 2. Setting up your Workbench and workspace preferences 31


There is also a list with all available perspectives where you can select the
default perspective. If you have added one or more customized perspectives you
can delete them here if you want to.

Internet preferences
When using Application Developer and working within an intranet, you may want
to use a proxy server to get across the firewall to access the Internet.

To be able to access the Internet from Application Developer, you have to set
preferences for the HTTP proxy server within the Workbench. You can do this by
clicking Window -> Preferences and selecting Internet (Figure 2-8).

Figure 2-8 Internet preferences

32 WebSphere Studio Application Developer Version 5 Programming Guide


Java development preferences
Application Developer provides a number of coding preferences. Some of these
are described in this section. Chapter 5, “Developing Java applications” on
page 93 also provides information regarding these preferences and Java coding.

Java classpath variables


Application Developer provides a number of default classpath variables.
classpath variables can be used in a Java build path to avoid a reference to the
local file system. Using a variable entry, the classpath only contains a variable.
This is a good idea when developing within a team as the team members do not
have to change their directory structure.

Depending on the type of Java coding you plan to do, you may have to add
variables pointing to other code libraries. For example, this can be driver classes
to access relational databases or locally developed code that you would like to
reuse in other projects.

Once you have created a Java project, you can add any of these variables to the
project’s classpath. Chapter 5, “Developing Java applications” on page 93
provides more information on adding classpath variables to a Java project.

To view and change the default classpath variables, click Window -> Preferences
and select Java -> Classpath Variables from the list. A list of the existing
classpath variables is displayed as shown in Figure 2-9.

You can create, edit and remove variables by using this dialog. Click New to add
a new variable. A new dialog comes up where you have to enter the name of the
variable and specify its path and file.

Chapter 2. Setting up your Workbench and workspace preferences 33


Figure 2-9 Classpath variables preferences

Figure 2-10 shows the New Variable Entry dialog with a DB2Java variable that
points to the DB2 JDBC driver class. The name of the file containing the class,
db2java.zip, is specified along with the file system path to it.

Figure 2-10 New Variable Entry dialog

34 WebSphere Studio Application Developer Version 5 Programming Guide


Appearance of Java elements
The page Java -> Appearance provides a dialog with some settings regarding the
appearance of Java elements in viewers. Here you can change the following
options:
򐂰 Show method return types, methods in views display their return types.
򐂰 Show override indicators in outline and hierarchy displays an indicator for
overridden and implemented methods in the Outline and the Type Hierarchy
views.
򐂰 Show members in Package Explorer, if enabled, displays Java elements
below the level of Java files and Class files as well
򐂰 Compress package name segments, if enabled, compresses package names
according to the compression pattern
򐂰 Stack views vertically in the Java Browsing perspective stacks the views in the
Java Browsing perspective vertically rather than horizontally

Code formatter
The Java editor in the Workbench can be configured to format code in
conformance with personal preferences or team standards. When setting up the
Workbench you can decide what formatting should be applied.

To modify the default code formatting select Windows -> Preferences -> Java ->
Code Formatter as shown in Figure 2-11.

Use the tabs at the top of the page to modify various aspects of the code
formatting. The sample code in the bottom right pane shows you a preview of the
effects of changes that you make.

The code formatting options are almost self explaining. However, a detailed
description of each option is provided in Application Developer’s help manual.

Note: To apply the formatting rules defined here, select Format from the Java
editor context menu. Some formatting, for example indenting of braces, will be
done on the fly while you are editing the source code.

Chapter 2. Setting up your Workbench and workspace preferences 35


Figure 2-11 Code Formatter preferences

Compiler options
Problems detected by the compiler are classified as either warnings or errors.
The existence of a warning does not affect the execution of the program. The
code executes as if it had been written correctly. Compile-time errors (as
specified by the Java Language Specification) are always reported as errors by
the Java compiler.

For some other types of problems you can, however, specify if you want the Java
compiler to report them as warnings, errors or to ignore them. To change the
default settings, use the Window > Preferences > Java > Compiler preferences
page (Figure 2-12).

36 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 2-12 Java compiler preferences dialog

Note: The Java compiler can create .class files even in presence of
compilation errors. In the case of serious errors (for example, references to
inconsistent binaries, most likely related to an invalid build path), the Java
builder does not produce any .class file.

Java Editor settings


By default the Java editor will use the standard Workbench font. If you want to
change the font, click Windows -> Preferences -> Java -> Editor and click
Change in the Editor dialog.

Chapter 2. Setting up your Workbench and workspace preferences 37


Besides the font, the following Java editor preferences can be set on this page:
򐂰 Appearance
򐂰 Syntax
򐂰 Code Assist
򐂰 Problem Indication

Figure 2-13 shows the Java editor preferences dialog.

Figure 2-13 Java editor preferences

There are a number of options for the code assist feature, which specify the
behavior and appearance of code assist. A description of how to use the code
assist feature is provided in “Code assist” on page 118. Also Application
Developer’s help manual contains a detailed description of each option of the
code assist feature.

38 WebSphere Studio Application Developer Version 5 Programming Guide


Installed JREs
Application Developer allows you to specify which Java Runtime Environment
(JRE) should be used by the Java builder. By default the standard Java VM that
comes with Application Developer is used, but if you have special requirements
you may want to add another JRE to be used as default or for special projects.

Select Window -> Preferences -> Java -> Installed JREs to display the dialog as
shown in Figure 2-14.

Figure 2-14 Installed JREs

By default, the JRE used to run the Workbench will be used to build and run Java
programs. It appears with a check mark in the list of installed JREs. You can add
another JRE and indicate whether it should be the default JRE or not.

When setting up the project you can also choose which of the JREs you would
like to use. If you do not explicitly specify the JRE for the project, the default JRE
is used.

Chapter 2. Setting up your Workbench and workspace preferences 39


You can either add, edit or remove a JRE by using this dialog. To add a new JRE
click Add. This brings up a new dialog (Figure 2-15).

Figure 2-15 Add JRE dialog

In the JRE type field, select the type of JRE you want to add from the drop-down
list and enter a unique name in the JRE name field. In the JRE home directory
field, type or click Browse to select the path to the root directory of the JRE
installation (usually the directory containing the bin and lib directories for the
JRE). This location is checked automatically to make sure it is a valid path.

In the Javadoc URL field, type or click Browse to select the URL location. The
location is used by the Javadoc export wizard as a default value. If you want to
use the default libraries and source files for this JRE, select the Use default
system libraries check box. Otherwise, clear it and customize as desired. Source
can be attached for the referenced JARs as well.

Javadoc documentation
Application Developer supports the creation of Javadoc documentations.
Javadoc is the tool from Sun Microsystems for generating API documentation in
HTML format from doc comments in source code.

40 WebSphere Studio Application Developer Version 5 Programming Guide


For more information regarding Javadoc, see this Web site:
http://java.sun.com/j2se/javadoc/

The JDT uses the Javadoc command (typically available in JDK distributions) to
generate Javadoc documentation from source files. Before you create Javadoc
documentation, you have to set the location of the Javadoc command.

Select Window -> Preferences -> Java -> Javadoc to open the Javadoc
preferences page (Figure 2-16).

Figure 2-16 Javadoc preferences

In the Javadoc command field you have to enter the absolute path to the Javadoc
command. A javadoc.exe file is located any JDK installed on your system, for
example, the JDK within the built-in WebSphere Application Server:
<wsadhome>\runtimes\base_v5\java\bin\javadoc.exe

Chapter 2. Setting up your Workbench and workspace preferences 41


Once you have set the Javadoc command, you can start creating Javadoc
documentation. Therefore, select the set (containing one or more elements) of
packages, source folders or projects for which you want to generate Javadoc
documentation. Then open the Export wizard by selecting File -> Export from the
menu bar and Javadoc and click Next. Now you have to go through three pages
of a wizard to customize the Javadoc export:
򐂰 In the first page of the wizard, select the types for which Javadoc will be
generated and the members with visibility. Also specify the destination folder
where the documentation should be created.
򐂰 In the second page of the wizard, you can specify a style sheet, the document
title, document tags and basic options as well as the referenced classes to
which Javadoc should create links.
򐂰 In the third page of the wizard you can specify some extra Javadoc options
and save the settings of the export as an Ant script.

For an example of Javadoc generation see “Javadoc” on page 133.

Organize imports
You can specify how you want the Java editor to handle imports when using the
automatic import generation feature. For more information on this feature see
“Import generation” on page 120.

In the Organize Imports preferences (Figure 2-17) you can specify the order of
the import statements. You can also control at what stage <package name>.*
import statements should be generated rather than fully qualified import
statements. The default number of fully-qualified import statements that are
allowed from the same package before <package>.* is 99.

Use the Up and Down buttons to change the order to imports. You can also add,
edit and remove imports. To add a new import entry, click New.

In the new dialog, simply type the package name or the package name prefix you
would like a add to the import statements list and confirm the dialog with OK.

Tip: You can also save and load your import statements settings by using the
Load and Save buttons. This might be a good idea when working in a team
where you have to apply coding standards.

42 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 2-17 Organize Imports preferences

Refactoring
Refactoring refers to the process of moving or renaming Java elements. A more
detailed description about Application Developer’s refactoring capabilities and
the refactoring preferences is provided in “Refactoring” on page 122.

Templates
Application Developer also provides templates. Templates are often reoccurring
source code patterns. The JDT of Application Developer offers support for
creating, managing, and using templates.

You can use a template in the Java editor by pressing Ctrl-Space (see “Code
assist” on page 118 for more information) and the templates appear in the
presented list. Note that the list is filtered as you type, so typing a few first
characters of a template name will reveal it.

Chapter 2. Setting up your Workbench and workspace preferences 43


The symbol in front of each template, shown Figure 2-18, in the code assist list is
colored yellow, so you can distinguish between a template and a Java statement
entry.

Figure 2-18 Using templates for code assist

The Templates preference page allows you to create new and edit existing
templates. A template is a convenience for the programmer to quickly insert often
reoccurring source code patterns.

To open the Templates preferences page, click Window -> Preferences -> Java
and select Templates from the Java tree, as shown in Figure 2-19.

Figure 2-19 Templates preferences

44 WebSphere Studio Application Developer Version 5 Programming Guide


The Templates preferences page opens where you can perform the following
tasks:
򐂰 Create templates
򐂰 Edit existing templates
򐂰 Remove templates
򐂰 Import templates from XML files
򐂰 Export selected or all templates to a XML file
򐂰 Enable or disable selected or all templates for code assist.

To create a new template, click New. The New Template dialog comes up as
shown in Figure 2-20. Here you have to enter the name of the template, the
description and its pattern.

Figure 2-20 Creating a new template

The name you enter here, will be displayed in the code assist list when you press
Ctrl-Space. In the Pattern field you have to enter the actual code you want to be
inserted by using the template.

There are also some predefined variables available. These variables can be
inserted by clicking Insert Variable. This will bring up a list and a brief description
of the variable.

Tip: Application Developer provides additional templates that are located in


the following directory of Application Developer’s installation:
wstools\eclipse\plugins\com.ibm.etools.jbcf.codegen_5.0.1\Examples\Templates

You can import all templates in a directory by selecting the AllTemplates.xml


files of the specific sub directory.

Chapter 2. Setting up your Workbench and workspace preferences 45


To import these templates, launch the templates preferences dialog and click
Import to open a file browser, and then navigate to the directory containing the
template files.

You can also enable or disable specific or all templates by either using the check
boxes in front of the template or using the Enable All or Disable All buttons.

Exporting templates exports them to an XML file in a folder you can specify.

Summary
In this chapter we covered the basic functionality of the Workbench and the
underlying Java development environment.

In particular, we discussed setting up workspaces and preferences.

46 WebSphere Studio Application Developer Version 5 Programming Guide


3

Chapter 3. Perspectives, views, and


editors
Application Developer supports a role-based development model. It does so by
providing several different perspectives on the same project. Each perspective is
suited for a particular role and provides the developer with the necessary tools to
work on the tasks associated with that role.

This chapter provides information about these topics:

Integrated development environment (IDE)


Resource perspective XSL Debug perspective
Java perspective Plug-in Development perspective
Java Browsing perspective Data perspective
Java Type Hierarchy perspective Debug perspective
Web perspective Profiling perspective
J2EE perspective Component Test perspective
Server perspective CVS Repository Exploring perspective
XML perspective Install/Update perspective

© Copyright IBM Corp. 2003. All rights reserved. 47


Integrated development environment (IDE)
An integrated development environment (IDE) is a set of software development
tools such as source editors, compilers, and debugger, that are accessible from
a single user interface.

In Application Developer, the IDE is called the Workbench. Application


Developer’s Workbench supports customizable perspectives that support
role-based development. It provides a common way for all members of a project
team to create, manage, and navigate resources easily. It consists of a number
of interrelated views and editors.

Views provide different ways of looking at the resource you are working in.
Editors allow you to create and modify the resource. Perspectives are a
combination of views and editors that show various aspects of the project
resource, and are organized by developer role or task. For example, a Java
developer would work most often in the Java perspective, while a Web designer
would work in the Web perspective.

Several perspectives are provided in Application Developer, and team members


also can customize them, according to their current role of preference. You can
open more than one perspective at a time, and switch perspectives while you are
working with Application Developer.

Before describing the perspectives, we take a look at Application Developer’s


help feature.

Application Developer help


Application Developer’s online help system provides access to the
documentation, and lets you browse, search, and print help content. It also has a
full-text search engine included as well as context-sensitive help.

Application Developer provides the help content in a separate window that you
can open by selecting Help -> Help Contents from the menu bar (Figure 3-1).

48 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 3-1 Help windows bookshelf

In the new help window you see the available books in the left pane and the
content in the right pane. When selecting a book in the left pane, the appropriate
table of contents opens up and you can select a topic.

At any time, you can return to the bookshelf by clicking the Table of Contents
button .

You can navigate through the help documents by using the Go Back and Go
Forward buttons on the top right side. There are also buttons for printing the
document, toggling and synchronizing the navigation. Synchronizing the
navigation synchronizes the navigation frame with the current topic. This is
helpful if you have followed several links to related topics in several files, and
want to see where the current topic fits into the navigation path.

Figure 3-2 shows the help window with the table of contents of the Application
developer information book.

Chapter 3. Perspectives, views, and editors 49


Figure 3-2 Application Developer help

Application Developer’s help manual contains a lot of useful information about


the tool and technologies. It provides information about the different concepts
used by the Workbench, the different Tasks you can do within the Workbench,
and some useful samples and tutorials.

The Search field allows you to do a search over all books. The link Advanced
Search opens a dialog box where you can specify your search in more detail
(Figure 3-3).

Note: The first time you search the online help, the help system initiates an
index-generation process. This process builds the indexes for the search
engine to use. It may take several minutes, depending on the amount of
documentation. Each time you add or modify the documentation set (for
example, when you install a new feature or update an existing one), the index
will be updated to reflect the new information set.

50 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 3-3 Advanced Search dialog for help

Enter your search expression in the appropriate field of the search dialog and
select the set of books to searched. Click Search to start your search.

Perspectives
Perspectives provide a way to look at a project through different “glasses”.
Depending on the role you are in and/or the task you have to do, you open a
different perspective. A perspective defines an initial set and layout of views and
editors for performing a particular set of development activities, for example, EJB
development, profiling, and so forth. You can change the layout and the
preferences and save a perspective that you can have customized, so that you
can open it again later.

Views
Views provide alternative presentations of resources or ways of navigating
through the information in your Workbench. For example, the Navigator view
displays projects and other resources that you are working as a folder hierarchy.
Application Developer provides synchronization between different views and
editors.

A view might appear by itself, or stacked with other views in a tabbed notebook
arrangement. A perspective determines the views that you are likely to need. For
example, the Java perspective includes the Packages view and the Hierarchy
view to help you work with Java packages and hierarchies.

Chapter 3. Perspectives, views, and editors 51


Editors
When you open a file, Application Developer automatically opens the editor that
is associated with that file type. For example, an HTML editor is opened for
.html, .htm and .jsp files while a Java editor is opened for .java and .jav files.

Editors that have been associated with specific file types open in the editor area
of the Workbench. By default, editors are stacked in a notebook arrangement
inside the editor area. You also have the option of tiling open files. However, if
there is no associated editor for a resource, Application Developer will attempt to
launch an external editor outside the Workbench.

Perspective layout
Most of Application Developer’s perspectives use a similar layout. Figure 3-4
shows a layout of a perspective which is quite common.

Menu bar / Toolbar

Source Editor (Code) Outline view


Navigator view Design View (Visual Editor) Properties
Package view
Explorer view
Hierarchy view synchronize

synchronize
synchronize

Task view (show compilation errors)


Search view (display search results)
Console view (program output, server status)

Figure 3-4 Perspective layout

52 WebSphere Studio Application Developer Version 5 Programming Guide


On the left side you have views that help you to navigate through your project’s
files, where in the middle of the Workbench you find a larger pane, usually the
source editor or the design pane. This allows you to change the code and design
of files in your project. The right pane usually contains the Outline or the
Properties views.

In some perspectives you can see that the editor pane is a little larger and the
Outline or Properties view is placed at the bottom left corner of the perspective.

The content of the views is synchronized. This means that if you change a value
in the Properties view, for example, the Editor view is automatically updated to
reflect the change.

Switching perspectives
There are two ways to open another perspective. You can use the Open a
Perspective icon in the top left corner of the Workbench working area and
select the appropriate perspective from the list. Alternatively, you can click
Window -> Open Perspective and either select a perspective or click Other to
bring up the Select Perspective dialog (Figure 3-5).

Figure 3-5 Select Perspective dialog

Select the perspective you would like to open and confirm the dialog with OK.

Chapter 3. Perspectives, views, and editors 53


Tips:
򐂰 The name of the perspective is shown in the window title area.
򐂰 The vertical toolbar at the left side of the Workbench, called the shortcut
bar, provides icons that you can use to quickly switch between the
perspectives that you have opened.
򐂰 To close a perspective, right-click that perspective's button on the shortcut
bar and select Close.
򐂰 After working with Application Developer for some time, you have opened
several perspectives. You might have the impression that Application
Developer is working slower. It is good practice to close perspectives,
because they can consume a lot of memory; hence, they slow down the
overall performance.

Specifying the default perspective


The J2EE perspective is Application Developer’s default perspective. You can
also change the default perspective from the preferences dialog:
򐂰 From the main menu bar, select Window > Preferences -> Workbench ->
Preferences.
򐂰 Select the perspective that you want to define as the default, and click Make
Default.
򐂰 Click OK.

Organizing and customizing perspectives


Application Developer provides the following features to organizing perspectives:
򐂰 Open perspectives
򐂰 Customize perspectives
򐂰 Reset perspectives
򐂰 Save perspectives
򐂰 Close perspectives

These actions can be found in the Window menu. To customize a perspective,


click Window -> Customize Perspective. The Customize Perspective dialog
opens (Figure 3-6).

54 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 3-6 Customize perspective

In the dialog you can use the check boxes to select which elements you want to
see on drop-down menus of the selected perspective. Items you do not select
are still accessible by clicking the Other menu option. These options can be
customizes:
򐂰 The New menu
򐂰 The Window -> Open Perspective menu
򐂰 The Window -> Show View menu
򐂰 Action sets (icons) that show up on the toolbar

You can also customize a perspective by adding, closing, moving, and resizing
views. To add a new view to the perspective, simply click Window -> Show View
and select the view you would like to add to the currently open perspective.

You can move a view to another pane by using drag and drop. To move a view,
simply select its title bar, drag the view, and drop it on top of another view. Both
views are now stacked and you can use the tabs at the bottom of the view to
switch between them.

While you drag the view, the mouse cursor changes into a drop cursor. The drop
cursor indicates what will happen when you release the view you are dragging:
The floating view appears below the view underneath the cursor.

Chapter 3. Perspectives, views, and editors 55


The floating view appears to the left of the view underneath the
cursor.
The floating view appears to the right of the view underneath the
cursor.
The floating view appears above the view underneath the cursor.

The floating view appears as a tab in the same pane as the view
underneath the cursor. You can also drop the view on the
perspective toolbar to make it a fast view.
You cannot dock the floating view at this point.

Once you have configured the perspective to your preferences, you can save it
as your own perspective by selecting Window -> Save Perspective As.

To restore the currently opened perspective to its original layout, select Window
-> Reset Perspective.

Tip: You can double-click a view’s title bar to maximize the view. Double-click
again to restore it to the original size. Alternatively, you can press CTRL-M to
maximize and restore the view.

Perspectives walkthrough
In this section we describe the perspectives that we are using to develop, test,
and deploy the samples in this document.

J2EE perspective
The default perspective of Application Developer is the J2EE perspective, shown
in Figure 3-7. Application Developer lets you change the default perspective. See
“Specifying the default perspective” on page 54 for an instruction to change the
default perspective.

The J2EE perspective contains the following views that you would typically use
when you develop resources for enterprise application, EJB, Web, and
application client, or connector projects or modules:
򐂰 J2EE Navigator view—This view provides a project and Java-centric view of
your J2EE and other projects in the workspace. It will show the project
resources and not the individual model objects as in the J2EE Hierarchy view.
For Java projects, the source folders will show the packaged based grouping

56 WebSphere Studio Application Developer Version 5 Programming Guide


of the files much like the Java Packages view. Note that the four J2EE
module types (EJB, application client, Web, and connector) are also Java
projects.

Figure 3-7 J2EE perspective

򐂰 J2EE Hierarchy view—Provides a hierarchical view of the content models


for J2EE resources found in the J2EE projects. This view provides you with
an easy way to view deployment descriptor trees of your J2EE applications
and modules, and to quickly navigate to editors for component objects.
Additionally, it provides links to EJB to RDB mapping, and for configuring
applications to run on a J2EE application server.
򐂰 Outline view—Shows the outline of the file that you are editing. The Outline
view changes as you change open files in different editors or select different
editor tabs.
򐂰 Tasks view—Lists the to-do items that you have entered, plus any
automatically logged problems, warnings, or other information associated
with the selected project. The former is true if you have this option enabled.

Chapter 3. Perspectives, views, and editors 57


You can double-click an item to address the specific problem in the
appropriate resource.
򐂰 Properties view—Provides a tabular view of the properties and associated
values of objects in files you have open in an editor. For example, you can
specify converters in the Properties view of the Mapping editor.
򐂰 Status bar—Provides a description of the location of selected objects in the
J2EE Hierarchy and J2EE Navigator views in the left side. When file and
deployment descriptors are open, it shows the read-only state of the files and
the line and column numbers when applicable. Sometimes when long
operations run, a status monitor will appear in the status bar, along with a
button with a stop sign icon. Clicking the stop sign will stop the operation
when the operation can be cancelled.

Resource perspective
The Resource perspective is a very simple perspective (Figure 3-8).

Figure 3-8 Resource perspective

By default it shows these elements:

58 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Navigator view—This view provides a hierarchical view of all the resources
in the Workbench. By using this view you can open files for editing, or select
resources for operations such as exporting.
򐂰 Outline view—This view displays an outline structure of the file that is
currently open in the editor area, and lists structural elements. The contents
of the outline view are editor-specific.
򐂰 Editor pane—Depending on the type of file you are editing, the appropriate
editor is displayed in the editor area. For example, if you are editing a .java
file, the Java editor displays in the editor area.

Web perspective
Web developers can use the Web perspective to build and edit Web resources,
such as servlets, JSPs, HTML pages, Style sheets and images, as well as the
deployment descriptor file, web.xml (Figure 3-9).

Figure 3-9 Web perspective

Chapter 3. Perspectives, views, and editors 59


The Web perspective contains a number of views, such as:
򐂰 J2EE Navigator view—The same view is included in the J2EE perspective.
򐂰 Page Designer—Page Designer allows you to work with HTML files, JSP
files, and embedded JavaScript. Within the Page Designer, you can move
among three pages that provide different ways for you to work with the file
that you are editing. You can switch pages by clicking the tabs at the bottom
of the editor pane. These pages work in conjunction with the Workbench
Outline and Properties views, tool bar buttons, menu bar options, and context
menus.
– Design—The Design page of Page Designer is the WYSIWYG mode for
editing HTML and JSP files. As you edit in the Design page, your work
reflects the layout and style of the Web pages you build without the added
complexity of source tagging syntax, navigation, and debugging. Although
many tasks can also be performed in the same way in the Source page,
the Design page provides full access to Page Designer menu options,
context menu actions, view-specific GUI options (such as those in the
Styles view), and drag and drop behavior.
– Source—The Source page enables you to view and work with a file's
source code directly. The Outline and Properties views both have features
that supplement the Source page.
– Preview—Shows how the current page is likely to look when viewed in a
Web browser. JSPs shown in this view will contain only static HTML
output.
򐂰 Gallery view—Contains a variety of catalogs of reusable files that can be
applied to Web pages. The file types available include images, wallpaper,
Web art, sound files, and style sheet files.
򐂰 Library view—Allows you to catalog and organize reusable programming
objects, such as HTML tagging, JavaScript, and JSP code, along with files
and custom JSP tags. The view can be extended based on additional objects
that you define and include.
򐂰 Outline view—Shows the outline of the file that you are currently editing. For
example, for an HTML file, the Outline view shows the tag structure and
hierarchy within the HTML file. The context menu for any selected tag
enables you to remove the tag, add an attribute to the tag (if any exist or have
not already been specified), add a child tag (if any exist), and add a sibling tag
before or after the tag.
򐂰 Web Structure view—Provides you with a way to navigate through the
various referenced parts of a Web application from a starting point such as a
Web page (JSP or HTML file), an Action mapping, or a global forward. Parts
of a Web application can be JSP files, links, Action mappings, form beans,
and so forth.

60 WebSphere Studio Application Developer Version 5 Programming Guide


The view also give you a general idea of how the different parts of a Web
application are linked together and how different parts reference each other.
The view provides additional information about a part to facilitate Web
application development. Among the information displayed are errors that
may cause a Web application to run incorrectly and data parameters that a
part requires.
򐂰 Attributes view—Provides tabbed pages that allow you to update attributes
for tags selected in files open in the active Web editor. Changes to attribute
value text fields are reflected in the edited file immediately when cursor focus
is changed, or when you press the Enter key. In addition, changes to any of
the controls in the Attributes view are immediately reflected in the edited file.
򐂰 Links view—Shows the resources that the selected file in the J2EE
Navigator view links to or uses. It also shows the files that link to the file
selected in the J2EE Navigator view or are open in Page Designer.
򐂰 Thumbnail view—Shows thumbnails of the images in the selected project,
folder, or file. This view is especially valuable when used in conjunction with
the Gallery view to add images from the artwork libraries supplied by
WebSphere Studio to your page designs. You can drag and drop from this
view into the J2EE Navigator view or the Design or Source page of Page
Designer.
򐂰 Styles view—Provides guided editing for cascading style sheets and
individual style definitions for HTML elements.
򐂰 Colors view—Allows you to apply colors from a palette (or custom colors) to
selected objects in the editing area.
򐂰 Servers view—Lists servers defined for the project and their status.

Java perspective
The Java perspective (Figure 3-10) supports developers who create, edit and
build Java code.

The Java perspective consists of an editor area and displays by default the
following views:
򐂰 Package Explorer view—This is displayed by default in the Java perspective
and shows the Java element hierarchy of all the Java projects in your
Workbench. It provides you with a Java-specific view of the resources shown
in the Navigator. The element hierarchy is derived from the project's build
classpath. For each project, its source folders and referenced libraries are
shown in the tree view. From here you can open and browse the contents of
both internal and external JAR files.

Chapter 3. Perspectives, views, and editors 61


Java Editor

Fields/Methods

Packages/Classes

Tasks

Figure 3-10 Java perspective

򐂰 Hierarchy view—Can be opened for a selected type to show its super


classes and subclasses. It offers three different ways to look at a class
hierarchy:
– The Type Hierarchy displays the type hierarchy of the selected type, that
is, its position in the hierarchy, along with all its Superclass and
subclasses
– The Supertype Hierarchy displays the supertype hierarchy of the selected
type
– The Subtype Hierarchy displays the subtype hierarchy of the selected type
More information about the Hierarchy view is provided in “Java Type Hierarchy
perspective” on page 64.
򐂰 Outline view—Shows the elements (imports, class, fields, and methods),
that exist in the source file that is currently open in the editor. Clicking an item
in the outline will position you in the editor view at the line where that structure
element is defined.

62 WebSphere Studio Application Developer Version 5 Programming Guide


See Chapter 5, “Developing Java applications” on page 93 for more information
about how to work with the Java perspective.

Tip: To get a larger Java editor view, you can move the Outline view and
place it tabbed next to the Package Explorer and Hierarchy view.

Java Browsing perspective


The Java Browsing perspective also addresses Java developers, but it provides
different views (Figure 3-11).

Java Editor

Figure 3-11 Java Browsing perspective

The Java Browsing perspective also displays an editor area, but unlike the Java
perspective, it displays by default the following views: Projects, Packages,
Types, Members, and an editor pane.

Chapter 3. Perspectives, views, and editors 63


Java Type Hierarchy perspective
This perspective also addresses Java developers and allows them to explore a
type hierarchy. It can be opened on types, compilation units, packages, projects
or source folders and consists of the Hierarchy view and an editor (Figure 3-12).

Java Editor

Figure 3-12 Java Type Hierarchy perspective

By default this perspective displays the Hierarchy view and the Editor pane. The
Hierarchy view does not display a hierarchy until you select a type (Figure 3-13).

Figure 3-13 Hierarchy view - initial

64 WebSphere Studio Application Developer Version 5 Programming Guide


To open a type in the Hierarchy view, open the context menu from a type in the
Package Explorer, the Editor, the Navigator or the Outline view and select Open
Type Hierarchy.

Once you have selected a type and opened it to the type hierarchy, the type
hierarchy is displayed in the Hierarchy view. Figure 3-14 shows the Hierarchy
view of the Java Swing class JList.

Figure 3-14 Hierarchy view

Icons are provided at the top of the Hierarchy view to display the type hierarchy
, the supertype hierarchy (bottom-up) , or the subtype hierarchy
(top-down) . The supertype hierarchy also shows interfaces that are
implemented for each class in the hierarchy.

Chapter 3. Perspectives, views, and editors 65


Server perspective
The Server perspective (Figure 3-15) is used to manage the server test
environments you use when testing, debugging, and profiling your applications.

Figure 3-15 Server perspective

The perspective has the following views:


򐂰 Server Configuration view—Shows the servers and server configurations
created. By clicking the down arrow and selecting Standard or Advanced the
view can be slightly customized.
򐂰 Servers view—Provides another view of the servers and also displays the
console which shows the stdout output from each server.

Servers can be controlled (start, stop, restart) either using the Server
Configuration view or the Servers view. Select the server and choose the
appropriate action from its context menu. If a server configuration is opened (by
double-clicking it) it opens up in the upper right pane and allows for editing of its
properties.

66 WebSphere Studio Application Developer Version 5 Programming Guide


XML perspective
The XML perspective (Figure 3-16) contains several editors and views that can
help a developer in building XML files, XML schemas, DTDs, style sheets, and
integrating between data extracted from relational databases and XML.

Figure 3-16 XML perspective

The XML perspective contains four sections:


򐂰 Outline view—Shows the Outline view for the active editor; in this case the
XML editor is active.
򐂰 Navigator view—Displays the folders, and files of the project.
򐂰 Tasks view—Shows the problems and errors to be fixed.
򐂰 Editor pane—Active editors.

Chapter 3. Perspectives, views, and editors 67


XSL Debug perspective
The XSL Debug perspective is used when you transform XML files. This
perspective and its capabilities are described in the section “Debugging XSL” on
page 369.

Data perspective
The Data perspective lets you access relational databases tools and you can
create and manipulate the data definitions for your project. This perspective also
lets you browse or import database schemas in the DB Servers view, create and
work with database schemas in the Data Definition view, and change database
schemas in the table editor. You can also export data definitions to another
database installed either locally or remotely. The Data perspective is shown in
Figure 3-17.

Figure 3-17 Data perspective

68 WebSphere Studio Application Developer Version 5 Programming Guide


These views characterize the Data perspective:
򐂰 Data Definition view—This view of lets you work directly with data
definitions, defining relational data objects. It can hold local copies of existing
data definitions imported from the DB Servers view, designs created by
running DDL scripts, or new designs that you have created directly in the
Workbench. Using the Data Definition view, you can also rename logical
objects.
򐂰 DB Servers view—Using this view, you can:
– Create a new database connection.
– Connect to existing databases and view their designs.
– Reconnect to a database if your database connection was disconnected.
– Disconnect from a database connection if you are connected.
– Import the designs to another folder in the Data Definition view, where you
can extend or modify the designs.
– Refresh the database objects defined to a database connection.
– Delete a database connection.

Debug perspective
Application Developer provides a Debug perspective that supports testing and
debugging of your applications.

The Debug perspective, shown in Figure 3-18, contains five panes:


򐂰 Top left—Shows Debug and Servers views.
򐂰 Top right—Shows Breakpoints, Expressions, Variables and Display views.
򐂰 Middle left—Shows the Source, the Design view, or the Web browser. In the
Source view, the line with the current error or breakpoint is displayed (where
the process stopped).
򐂰 Middle right—Shows the Outline view of the currently displayed source.
򐂰 Bottom—Shows the Console and the Tasks view.

Chapter 3. Perspectives, views, and editors 69


Figure 3-18 Debug perspective

򐂰 Debug view—Displays the stack frame for the suspended threads for each
target you are debugging. Each thread in your program appears as a node in
the tree. If the thread is suspended, its stack frames are shown as child
elements.
If the resource containing a selected thread is not open and/or active, the file
opens in the editor and becomes active, focusing on the source with which
the thread is associated.
The Debug view enables you to perform various start, step, and terminate
debug actions as well as enable or disable step-by-step debugging
򐂰 Variables view—Displays information about the variables in the
currently-selected stack frame.
򐂰 Breakpoints view—Lists all the breakpoints you have set in the Workbench
projects. You can double-click a breakpoint to display its location in the editor.
In this view, you can also enable or disable breakpoints, delete them, or add

70 WebSphere Studio Application Developer Version 5 Programming Guide


new ones. This view also lists Java exception breakpoints, which suspend
execution at the point where the exception is thrown. You can add or remove
exceptions.
򐂰 Expressions view—Data can be inspected in the Expressions view. You can
inspect data from a scrapbook page, a stack frame of a suspended thread,
and other places. The Expressions view opens automatically when the
Inspect command is activated.
򐂰 Display view—Shows the result of evaluating an expression in the context of
the current stack frame. You can evaluate and display a selection either from
the editor or directly from the Display view.

More information about the Debug perspective can be found in “Testing and
debugging” on page 553.

Profiling perspective
Profiling is controlled from the Profiling perspective (Figure 3-19). To open the
perspective, select Window -> Open Perspective -> Other -> Profiling.

Figure 3-19 Profiling perspective

Chapter 3. Perspectives, views, and editors 71


The Profiling perspective contains all the views used in a profiling session. Once
you open the Profiling perspective, the Profiling Monitor view is visible on the top,
left side of the Workbench.

The Profiling Monitor view displays profiling objects such as project folders,
monitors, hosts, processes, and agents that get created during a profiling
session.

On the right of the Workbench, the Profiling perspective offers the following
views, which display data that is collected from a profiling session:
򐂰 Statistical profiling views:
– Package Statistics view
– Class Method Statistics view
– Method Statistics view
– Class Instance Statistics view
– Instance Statistics view
򐂰 Graphical profiling views:
– Execution Flow view
– Object References view
– Method Execution view
– Method Invocation view
– Heap view

More details about these views can be found in “Performance analysis” on


page 666.

Component Test perspective


The Component Test perspective (Figure 3-20) provides a framework for defining
and executing test cases.
򐂰 Definition view—Used to define test cases. This is also where you define the
hosts on which the test cases will run. Once you define the test case element
in the Definition pane, its contents appear in the Outline pane.
򐂰 Outline view—Displays the contents of a test case currently being edited.
Here you add elements to the test case's main block, and once your definition
is complete you prepare it to run and create a test case instance.
򐂰 Execution view—Once you prepare a test case definition to run, a test case
instance is generated in the Execution pane. You can then review the
instance and edit any associated generated code before running the test
case.

72 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 3-20 Component Test perspective

More information about Component Testing is located in “Component testing” on


page 588.

CVS Repository Exploring perspective


The CVS Repository Exploring perspective (Figure 3-21) lets you connect to
CVS repositories. It allows you to add and synchronize projects with the
workspace and to inspect the revision history of resources:
򐂰 CVS Repositories view—Shows the CVS repository locations that you have
added to your Workbench. Expanding a location reveals the main trunk
(HEAD), project versions and branches in that repository. You can further
expand the project versions and branches to reveal the folders and files
contained within them.
The context menu for this view also allows you to specify new repository
locations. Use the CVS Repositories view to checkout resources from the
repository to the Workbench, configure the branches and versions shown by
the view, view resource history, and compare resource versions.

Chapter 3. Perspectives, views, and editors 73


Figure 3-21 CVS Repository Exploring perspective

Files that exist in the repositories can be viewed by double-clicking them in a


branch or version. This opens the version of the file specified in the file editor,
located at the top right of the workspace.
򐂰 CVS Resource History view—Displays more detailed history of each file.
This view provides a list of all the revisions of a resource in the repository.
From this view you can compare two revisions, replace (get sticky), or revert
the corresponding workspace file to the revision (get contents), or open an
editor on a revision.

More details about using the CVS Repository Exploring perspective can be found
in Chapter 22, “Using Concurrent Versions System” on page 701.

74 WebSphere Studio Application Developer Version 5 Programming Guide


Install/Update perspective
The Install/Update perspective (Figure 3-22) allows you to check to see whether
there are updates for a product's existing features. Working with this perspective
usually requires access to the Internet.

Figure 3-22 Install/Update perspective

The Install/Update perspective contains these views:


򐂰 Install Configuration view—This view allows you to manage your
workspace configuration. The Current Configuration folder shows which local
installation locations are part of the workspace configuration, and which
features are installed in those locations. The Configuration History folder
shows a history of changes made to your workspace configuration. The
Saved Configurations folder show any configurations that were preserved.
򐂰 Feature Updates view—This view allows you to locate and install new
features and feature updates. The view contains three standard folders. The
Sites to Visit folder contains update sites pre-configured by the product you
are using. The Available Updates is a built-in search results folder used for
searching update sites. The My Computer folder is a file explorer that can be
used to navigate to updates located in the file system.
򐂰 Preview view—This view displays detailed information about the current
active selection. Its content changes according to your selection.

Chapter 3. Perspectives, views, and editors 75


For information about how to work with the Update Manager consult Appendix A,
“Product installation” on page 785.

Plug-in Development perspective


You can develop your own Application Developer tools by using the Plug-in
Development Environment (PDE). The PDE provides a set of platform extension
contributions (views, editors, perspectives, etc.) that collectively streamline the
process of developing plug-ins inside the Workbench.

In this book we do not describe how to develop plug-ins for Application


Developer. Figure 3-23 shows the Plug-in Development perspective.

Figure 3-23 Plug-in Development perspective

To learn more about plug-in development, refer to The Java Developer’s Guide
to Eclipse (see “Other publications” on page 818).

76 WebSphere Studio Application Developer Version 5 Programming Guide


Summary
In this chapter we described the perspectives and views that you use with
Application Developer to perform your tasks.

Chapter 3. Perspectives, views, and editors 77


78 WebSphere Studio Application Developer Version 5 Programming Guide
4

Chapter 4. Projects
This chapter introduces the project types and some of the main terms used in
Application Developer.
򐂰 J2EE architecture:
– EAR files
– WAR files
– JAR files
򐂰 Projects and folders
򐂰 Project types:
– Simple project
– Java project
– Web project
– Enterprise Application project
– EJB project
– Application Client project
– Server project
򐂰 Creating a new project

© Copyright IBM Corp. 2003. All rights reserved. 79


J2EE architecture
The Java 2 Platform, Enterprise Edition (J2EE) is a robust suite of middle-ware
application services for server side application development. J2EE is an
extension of the Java 2 Platform, Standard Edition (J2SE).

J2EE makes all Java enterprise APIs and functionality available and accessible
in a well integrated fashion. This helps in simplifying complex problems in the
development, deployment, and management of multi-tier, server-centric
enterprise solutions.

Figure 4-1 shows an overall view comprising the different J2EE technologies.

Applet WebSphere
Container HTTP
SSL
Applet
Web Container EJB Container

JSP Servlet EJB

Java
RMI-IIOP

Java

RMI-IIOP
J2SE
JDBC

JDBC
JNDI

JNDI
Mail
JMS

Mail
JMS
JTA

JTA
JAF JAF

Application HTTP J2SE J2SE


Client SSL
Container

Application
Client
RMI-IIOP

Database
JDBC
JNDI
JMS

J2SE

Figure 4-1 J2EE architecture diagram

Web containers and EJB containers


Containers are basically run-time environments that provide components with
specific services. For example, Web containers provide run-time support to
clients by processing requests through invoking JSPs and servlets and returning
results from the components to the client. Similarly, EJB containers provide

80 WebSphere Studio Application Developer Version 5 Programming Guide


automated support for transaction and state management of EJB components,
as well as look up and security services.

For additional information regarding the J2EE architecture and its technologies,
consult the J2EE specification on Sun’s Web Site:
http://java.sun.com/j2ee

EAR files
Enterprise archive (EAR) files represent a J2EE application that can be deployed
in a WebSphere application server. EAR files are standard Java archive files and
have the file extension .ear. EAR files also contain a deployment descriptor (an
XML file) that describes the contents of the application and contains instructions
for the entire application, such as security settings to be used in the run-time
environment.

An EAR file has the following modules (zero, one, or more of each type):
򐂰 Web modules
򐂰 EJB modules
򐂰 Application client modules
򐂰 Utility JAR files required by other modules

WAR files
Web archive (WAR) files contain all the components of a Web application. These
components are usually:
򐂰 HTML files
򐂰 CSS files
򐂰 JSP files
򐂰 Servlets
򐂰 Compiled Java files
򐂰 Images

JAR files
The Java archive (JAR) file format allows you to store multiple files into a single
archive file. Typically, a JAR file contains the class files and additional resources
associated with applets and applications.

EJB modules and utility modules are packaged as JAR files.

Chapter 4. Projects 81
Projects and folders
Application Developer organizes all resources into projects.

A project in Application Developer is the top-level construct for organizing the


different resources. It contains files as well as folders. In the Workbench you can
create different kinds of projects, and they will have a different structure.

Unless not specified differently, projects are created in the workspace directory
of Application Developer’s installation folder. Also, the metadata is stored in the
workspace directory. The .metadata directory of a workspace directory stores
important information about the workspace structure, such as a project’s
reference or a resource’s properties.

A project is either open or closed. When a project is closed, it cannot be changed


in the Workbench and it cannot be referenced from other projects. The resources
of a closed project do not appear in the Workbench, but they do reside in the
local file system.

Tip: Closed projects require less memory. Because they are not examined
during builds, closing a project can improve the build time.

Application Developer’s project types


Application Developer provides different project types for different tasks.

Simple project
A Simple project in Application Developer does not have any default folders and
does not have an associated builder. The files stored inside the project are not
compiled when you select to rebuild all projects in the Workbench.

We will use a simple project in Chapter 6, “Developing database applications” on


page 139.

Java project
A Java project contains Java packages and Java code as .java files and .class
files. Java projects have an associated Java builder that incrementally compiles
Java source files as they are changed. Java projects can be exported as JAR
files or into a directory structure.

82 WebSphere Studio Application Developer Version 5 Programming Guide


Java projects are used for stand-alone applications or to build utility JAR files for
an enterprise application. A detailed example of how to create a new Java
project is provided in “Creating and working with a Java project” on page 94.

Enterprise Application project


Enterprise Application projects contain references to the resources needed for
enterprise applications and can contain a combination of Web modules, EJB
modules, application client modules, and JAR files.

An Enterprise Application project is deployed in the form of an EAR file. In


Application Developer, the modules in an Enterprise Application project are
mapped to other J2EE projects. The mapping information is stored in metadata
files within the Enterprise Application project. The metadata files are used for
exporting the project to an EAR file, and for running the project on the server.

Application Developer mirrors the layout of a J2EE enterprise application


modules with matching project types. For each type of module, a project type
tailored for that purpose is provided (Figure 4-2).

DD = Deployment Descriptor
Application J2EE
Developer EAR Application Application
Project EAR file
DD

application.xml
EJB
Project
Web
EJB Project Web Client
Module Module Module
Client
JAR file WAR file JAR file
Project

Enterprise EJB HTML, Web Client Client


DD Servlet JSP DD Class
Bean GIF, etc. DD

ejb-jar.xml web.xml

Figure 4-2 Application Developer projects for J2EE

We will create an Enterprise Application project together with a Web project in


Chapter 7, “Developing Web applications” on page 179.

Chapter 4. Projects 83
Web project
A Web project contains resources needed for Web applications, such as source
files and metadata, that correspond to the hierarchy of files necessary to deploy
a Web page or Web application. There are two types of Web projects:
򐂰 Static Web project
򐂰 J2EE Web project

A static Web project contains only static content such as HTML pages or images,
and any associated metadata. In addition to static content, J2EE Web projects
can contain additional kinds of resources for Web applications, including servlets,
JSP files, and Java files. J2EE Web projects incur more system overhead
because of additional validation and Java compilation that is automatically
performed by the Workbench. A Web project is deployed as a WAR file.

A step-by-step description of how to create a new Web project is provided in


“Creating a Web project” on page 185. Also, some detailed information regarding
the structure of a Web project is given in “Web project directory structure” on
page 190.

Struts project
With Application Developer Version 5, a Web project with Struts support can be
created. Such a project is tailored to provide an organization suitable for Struts
development, including the Struts runtime, configuration file, a Web diagram
editor, and wizards to create Struts components.

Refer to Chapter 10, “Developing Struts applications” on page 293 for details
about Struts and the support in Application Developer.

EJB project
Enterprise JavaBeans (EJB) projects contain the resources for EJB applications.
The EJB project contains the metadata files (such as the deployment descriptor,
IBM extensions, and RDB mappings) for the EJB application, Java source files,
compiled code for the enterprise beans, and stubs for the beans. An EJB project
is deployed as an EJB JAR file.

EJB projects allow you to organize your enterprise beans logically. As you
develop EJB applications in the Workbench, your source and output files are
kept in the ejbModule folder of the EJB project. As you make changes and
generate deployment code, the Java classes are compiled into the ejbModule
folder. You cannot use the EJB project as the source folder; doing so will cause
errors.

84 WebSphere Studio Application Developer Version 5 Programming Guide


Application Client project
Application Client projects contain the resources needed for application client
modules. An application client module is used to contain a full-function client
Java application (non Web-based) that connects to and uses the J2EE resources
defined in your server.

When you place the client code in an application client module instead of a
simple JAR file, the application client benefits from the server's resources (it does
not need to re-specify the class path to J2EE and server JAR files), as well as
benefiting from easier JNDI lookup (the server fills in the initial context and other
parameters). The application client project allows you to work as if you are
creating a standalone Java application in a Java project.

An application client project enables you to do the following things:


򐂰 Develop the Java classes that implement the client EJB module
򐂰 Set the application client deployment descriptor
򐂰 Test the application client

When creating a new Application Client project, you can choose between these
two project types:
򐂰 J2EE 1.2 Application Client project
򐂰 J2EE 1.3 Application Client project

Application client projects allow you to organize your client applications logically.
As you develop client applications in the Workbench, your source files will be
kept in the appClientModule folder of the application client project and the binary
files will be kept in the bin folder.

Refer to “Building an application client module” on page 614 for an example.

Server project
A Server project stores information about test and deployment servers and their
configurations. To test an EJB or Web project, you have to define a server with a
server configuration to publish and run the code. Servers identify where you can
test your projects, and server configurations contain setup information.

See the section “Creating a Server project” on page 519 in Chapter 15, “Servers
and server configurations” on page 513 for a detailed instruction of how to create
a Server project and a server.

Chapter 4. Projects 85
Creating a new project
You normally start developing a new application by creating one or more projects.
The Workbench provides wizards to create each specific type of project.

As we work with a number of projects in this book, we provide more detailed


information regarding the creation of projects in the appropriate chapters. For
now we only want to demonstrate how to launch the new project wizard by
selecting File -> New -> Project from the menu bar. The New Project wizard is
shown in Figure 4-3.

Figure 4-3 New Project wizard

In this example we select the Enterprise Application Project, which is categorized


as a J2EE project. Depending on what project you choose in the New Project
dialog, Application Developer shows a tailored dialog after clicking Next.

In general (it differs, depending on what type of project is created), when you
create a new project, you have to specify the following:
򐂰 Name—Project name (we will use ItsoProGuideXxxxx).
򐂰 Location—By default projects are store in the workspace directory, but
another location may be specified.
򐂰 Organization—Directories for source and compiled files (unless this is
dictated by J2EE standards).
򐂰 Dependencies—Within an enterprise application you have dependencies
between modules, for example a Web module requires an EJB module and a
utility JAr file.

86 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Build path—Projects, folders, and JAR files that have to be in the build path.
For some project types this can only be changed after the project has been
created.

After creation of a project, the appropriate perspective opens and displays a view
of the project.

Project properties
To make changes to the definition of a project, select the project and Properties
from the context menu. Figure 4-4 shows the properties dialog for a Web project.

Figure 4-4 Project properties

In the properties dialog you may want to change:


򐂰 Java Build Path—Project dependencies and JAR files
򐂰 Server Preference—Which test server to start when testing the project
򐂰 Validation—What validation tools should run after making changes
򐂰 Web—J2EE level, context root, and tag libraries

Chapter 4. Projects 87
Using templates to create application projects
Application Developer provides an Application Template Wizard that creates
projects containing complete model applications based on application templates.

An application template is the skeleton of an application. It includes the entire


application and may be either fully configured or may have certain parts that
remain to be specified. The Application Template Wizard guides you through a
step-by-step process where you can easily specify the parameters required by
the template to generate the desired application. This enables users with minimal
or no programming skills to quickly build a fully operational application based on
simple wizard guided settings.

The Application Template Wizard currently includes a small set of pre-defined


templates. Each available template stores a description of an application along
with customized settings that enable wizard-driven specification of parameters
and automatic code generation that will produce a complete operational
application.

Running the Application Template Wizard


To generate a template-based application, select File -> New -> Other -> Web ->
Template Application. The Application Template Wizard (or Template Application
Wizard) opens as shown in Figure 4-5:
򐂰 There are three sets of templates to choose from:
– Solution Templates—provides four template applications (see
Figure 4-5)
– IT Templates—provides two template applications: List - Details, Login
– Tutorial—provides one template application: Shopping Cart
򐂰 To create an application, select a template and progress through the dialog.
򐂰 Depending on the template, you have to configure the application in a
variable number of steps, providing information for properties, data sources,
titles, and Web page content. A sample dialog for the Self Service Insurance
template is shown in Figure 4-6.
򐂰 In the Application Developer Help you can find a tutorial for the Shopping Cart
template.
򐂰 A future update to Application Developer will deliver a Template Builder that
enables users to create there own templates.

We did not use the Application Template Wizard in this document.

88 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 4-5 Template wizard: template selection

Configure each step in


the list while progressing
through the wizard.

Figure 4-6 Template wizard: example

Chapter 4. Projects 89
Summary
In this chapter we described the type of projects provided by Application
Developer for the development of J2EE applications.

We also touched briefly on the Application Template Wizard.

90 WebSphere Studio Application Developer Version 5 Programming Guide


Part 2

Part 2 Developing
applications
Part 2 describes how to develop applications. These chapters are provided:
򐂰 Developing Java applications
򐂰 Developing database applications
򐂰 Developing Web applications
򐂰 Developing Web applications with database access
򐂰 Developing applications with stored procedures
򐂰 Developing XML applications
򐂰 Developing EJBs
򐂰 Developing Web services
򐂰 Developing Struts applications
򐂰 Developing GUI applications

Note: See Appendix C, “Additional material” on page 809 for instructions on


how to download the sample code and set up the database that is used in our
examples. In addition, see “Installing DB2 UDB” on page 786 for instructions
on how to enable JDBC 2.0.

© Copyright IBM Corp. 2003. All rights reserved. 91


92 WebSphere Studio Application Developer Version 5 Programming Guide
5

Chapter 5. Developing Java


applications
This chapter provides an introduction in the Java development capabilities of the
Application Developer. The chapter is divided into four major sections:
򐂰 Creating and working with a Java project—This section demonstrates how to
create and work with a Java project. A simple Java class that reads a DB2
database table to retrieve information about customers is used.
򐂰 Preparing a utility project—This section shows how to prepare a utility project
that is available to multiple modules of an enterprise application.
򐂰 Programming assists—This section describes the main Java programming
assist features and capabilities of Application Developer.
򐂰 Javadoc—This section explains how to generate Javadoc for a project or a
set of packages.

The sample Java code used in this chapter is provided in the directory:
\sg246957\sampcode\dev-java

© Copyright IBM Corp. 2003. All rights reserved. 93


Creating and working with a Java project
Before we demonstrate Application Developer’s programming assists, we show
how to create and work with a Java project. You can use Application Developer
to develop the Java packages for your application specific business logic and for
common code that will be used by several projects. These packages can be
exported as JAR files and included in the build path for other types of projects, or
in the application path of the application servers.

Existing Java code can also be imported and integrated into new applications.

Application Developer 5 also introduces the Visual Editor for Java, which allows
you to design applications containing a graphical user interface (GUI). See
Chapter 14, “Developing GUI applications” on page 469 for a detailed description
of the Visual Editor.

Application Developer provides features to perform the following development


tasks:
򐂰 Creating a Java project
򐂰 Creating Java packages
򐂰 Running your programs
򐂰 Exporting code and running outside Application Developer
򐂰 Locating compile errors in your code
򐂰 Debugging your code

Creating a Java project


Java projects contain the resources needed for Java applications, including Java
files and class files. Java projects are used to create Java packages. When you
create a new Java project, the environment is set up for Java development.

To create a new Java project, select File -> New -> Project. This displays the New
Project dialog (Figure 5-1).

94 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-1 New Project dialog

Select Java and Java Project from this dialog and click Next to start the Java
project wizard (Figure 5-2).

Figure 5-2 New Java project: project name and directory

On the first page you name the Java project and specify the directory, where the
project files should be stored. In this example the project is named
ItsoProGuideJava. By default, the project files will be stored in a directory
created under the Application Developer workspace directory. You can change
the project directory by removing the Use default check box and specifying
another directory.

Chapter 5. Developing Java applications 95


If you click Finish, the project is configured with default options that can be
configured in the preferences (select Window -> Preferences and then select
Java -> New Project. to set up defaults for a new Java project).

We click Next to bring up the second dialog of the wizard, where we define the
Java build settings for the new project (Figure 5-3).

Figure 5-3 New Java project: source settings

On the Source tab you decide whether it is appropriate to store source code
directly in the project folder, or if you want to use separate source folders. For our
sample project, the simple model is used. If you want to use the complex model
instead, you can create the required folders by clicking Create New Folder and
adding them to the list.

Here you can also select the target folder for the generated class files. By default
the class files are placed in the same folder as the source folder, but you can edit
the Build output folder field to define a different target folder.

Note: In the Package Explorer view you cannot see the generated .class
files. If you open the Navigator view (Window -> Show View -> Navigator) you
can see source and class files.

96 WebSphere Studio Application Developer Version 5 Programming Guide


On the Projects tab you can specify any other projects in your workspace that
should be in the Java build path for the new project (Figure 5-4). You might have
some common code in a project that already exists and you want to reuse it in
the new project.

Figure 5-4 New Java project: required projects

On the Libraries tab, you can add other code libraries that have to be included in
the build path of your project (Figure 5-5). By default, the library list contains an
entry representing the Java runtime library.

You can also add:


򐂰 Workbench-managed (internal) JAR files
򐂰 File system (external) JAR files
򐂰 Folders containing class files

You can also add Java classpath variables which have been defined in the
Classpath Variable preferences page. Consult the section “Java classpath
variables” on page 33 for more information about the Classpath Variable
preferences page.

The Add Variable button allows you to add classpath variables to the build path.
Classpath variables are symbolic pointers to JAR files with the benefit of
avoiding local file system paths in a classpath.

Chapter 5. Developing Java applications 97


This is a good idea when projects are shared in a team. Variables can be created
and edited in the Classpath Variable preference page. If you want to open the
Classpath Variable preferences page, click Window -> Preferences -> Java ->
Classpath Variables.

Figure 5-5 New Java project: libraries settings

On the last tab, Order and Export, you can specify the order in which you want
items in the build path to be searched. Using the Up and Down buttons allow you
to arrange the order of the classpath entries in the list (Figure 5-6).

The checked list entries are marked as exported. Exported entries are visible to
projects that require the project. Use the Select All and Deselect All buttons to
change the checked state of all entries. The source folder itself is always
exported, and cannot be deselected.

Clicking Finish creates the new project.

98 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-6 New Java project: order and export settings

Creating Java packages


Once the Java project has been created, you can add Java packages to it. Select
the project in the Package Explorer view and New -> Package from the context
menu. In the dialog window, you enter the fully qualified name of the package.
The package where our sample Java application code resides is named
itso.java (Figure 5-7).

Figure 5-7 Create Java package dialog

Chapter 5. Developing Java applications 99


Creating Java classes
After you have created the new package, you can add classes to it. The sample
code is in a new class called CustomerListing. To create a new class, select the
package that has been created in the previous step and select New -> Class from
the context menu. In the Name field of the new Java class dialog, you have to
enter the name of the new class, CustomerListing (Figure 5-8).

You can also set the modifiers, the name of the superclass, add interfaces which
should be implemented, and create method stubs for the new class.

Figure 5-8 Create Java Class dialog

After all settings have been made, you click Finish to create the class. The Java
editor opens with the new class and its selected method stubs (Figure 5-9).

100 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-9 Java source editor with new class

Tip: Notice the Javadoc comment that is generated for a new class. You can
tailor the comment by selecting Window -> Preferences -> Java -> Templates
and editing the typecomment entry.

CustomerListing sample
Complete the CustomerListing class with the sample code from:
\SG246957\sampcode\dev-java\CustomerListing.java

We do not explain in detail the code for the CustomerListing class. The basic
functions of the sample code are:
򐂰 Connect to the DB2 database.
򐂰 Select all customers from the CUSTOMER table.
򐂰 Display the first name, the last name and the user ID of the customers.

Chapter 6, “Developing database applications” on page 139 describes database


access using JDBC. For now we just use this class to experiment with editing,
running, and debugging a Java class.

Figure 5-10 shows the complete code of the sample CustomerListing class.

Note. We also provide a companion program, CustomerListingNet, which uses


the DB2 JDBC net driver to connect to the database:
Class.forName("COM.ibm.db2.net.DB2Driver");
con = DriverManager.getConnection("jdbc:db2://localhost:6789/EJBBANK");

Chapter 5. Developing Java applications 101


package itso.java;
import java.sql.*;

public class CustomerListing {


static String dbtab = "CUSTOMER";

public static void main(String[] args) {


System.out.println("Customer Listing for " + dbtab);
Connection con = null;
con = connect();
Statement stmt = null;
ResultSet rs = null;
String select = "SELECT * FROM ITSO." + dbtab;
try {
stmt = con.createStatement();
rs = stmt.executeQuery(select);
while (rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String userID = rs.getString("userID");
System.out.println(firstName + " " + lastName + " " + userID);
}
System.out.println("End of Listing");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {}
}
}

protected static Connection connect() {


Connection con = null;
try {
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
con = DriverManager.getConnection("jdbc:db2:EJBBANK");
} catch (Exception e) {
System.err.println("Exception: " + e.getMessage());
}
return con;
}
}

Figure 5-10 Sample class code CustomerListing

102 WebSphere Studio Application Developer Version 5 Programming Guide


Running your programs
After the code has been completed and is free of compile errors, it can be
executed using the Workbench Java Application Launcher. To launch the
program, you click the Run icon from the toolbar.

If you launch the program the first time, the Launch Configuration dialog opens
(Figure 5-11). Here you can select the type of configuration you would like to
create to run the program.

Select Java Application from the list and click New. A new launch configuration
with the appropriate settings for the selected class is created. You can also
specify arguments, JRE, and classpath settings for your launch configuration.
Clicking Run invokes the main method of the class.

Figure 5-11 Launch Configurations dialog

Tip: By defining launch configurations for a program you can create multiple
configurations with different arguments and settings (such as the JRE).

You can also use the drop-down arrow of the Run icon. Clicking this drop-down
arrow the first time allows you either to open the configuration launcher or select
the type of application you would like to run, directly.

You can add other launch configurations for any program. Each configuration is
displayed when clicking the drop-down arrow of the Run icon.

Chapter 5. Developing Java applications 103


Executing the CustomerListing class should result in an error. The Console view
will display the following error message:
Customer Listing for CUSTOMER
Exception: COM.ibm.db2.jdbc.app.DB2Driver
Exception: null

The exception information indicates that there was a problem locating a class
required to run the program. To correct the error you have to add the JAR file with
the DB2 JDBC driver code to the classpath.

Adding a JAR file to the classpath


We have to update the Java build path that was previously defined. Select the
ItsoProGuideJava project and Properties from the context menu. Then you
select the Java Build Path entry and the Libraries tab (Figure 5-12).

Figure 5-12 Java Build Path settings for the ItsoProGuideJava project

There are two ways you can specify access to the required classes:
򐂰 Select Add External JARs and locate the db2java.zip file in the file system.
򐂰 Select Add Variable to add a variable that refers to the db2java.zip file.

It is recommended to use the second option because you are not directly
referencing a physical path that could be different for another developer within a
team.

104 WebSphere Studio Application Developer Version 5 Programming Guide


For this sample it is assumed that a variable DB2JAVA has been defined. If DB2 is
installed on your system, Application Developer predefines this variable.

To add this variable to the Java build path for the project, select Add Variable to
display the New Variable Classpath Entry dialog (Figure 5-13).

Figure 5-13 Adding a variable to the classpath

Select the DB2JAVA variable and close the dialog with OK.

If the DB2JAVA variable is not available in the dialog, you have to create a new
variable. Click the New button to display the New Variable Entry dialog
(Figure 5-14). Enter DB2JAVA in the name field and select the file db2java.zip
from the file system by clicking the File button and confirm the dialog with OK.

DB2JAVA
c:\sqllib\java\db2java.zip

Figure 5-14 New Variable Entry dialog

The sample code can now be executed again and the list of customers in the
database table should be displayed in the Console view.

Note: The EJBBANK database must be defined for this example. See “Installing
the EJBBANK database” on page 811 for instructions.

Chapter 5. Developing Java applications 105


Exporting code and running outside Application Developer
If you would like to run this sample application outside of Application Developer
you can export the class file to the file system and run it from there:
򐂰 Select File -> Export. The Export dialog is displayed (Figure 5-15).

Figure 5-15 Export dialog

򐂰 This dialog allows you to select the destination of the export. In this example
we will do a simple export to the file system. If the code would have been in
several class files, or if there would have been other resources required to run
the program, you could have chosen to export the sample project as a JAR
file instead.
When you have made your selection—in this case select File system—click
Next to specify the resources to export (Figure 5-16).

106 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-16 Export to File System dialog

򐂰 Expand the project which is shown in the left pane and select the
CustomerListing.class file in the right pane. You can specify the directory
where you would like to export the file. In this example we use C:\ as the path
and check the Create directory structure for files check box. This option
creates the directory path ItsoProGuideJava\itso\java for the file.
򐂰 To run the application, open a command prompt window, switch to the
ItsoProGuideJava directory and enter the command:
java -cp ".;c:\sqllib\java\db2java.zip" itso.java.CustomerListing
The db2java.zip file is already added to the classpath after DB2 has been
installed. Therefore the following command should also execute the sample
application:
java itso.java.CustomerListing
򐂰 After running this program, the customer list is displayed in the command
window.

Chapter 5. Developing Java applications 107


Note: The command may be different on your system, depending on where
DB2 has been installed.

You also need to ensure that the file java.exe is accessible in the path. In the
Application Developer installation folder you will find a copy of java.exe
located in the <wsadhome>\eclipse\jre\bin directory.

Locating compile errors in your code


All compile errors in your Java code are shown in the Tasks view. An example of
such an entry in the CustomerListings.java file is displayed in Figure 5-17. The
entry in the Tasks view is marked with this symbol . Double-clicking the entry
in the task list will navigate to the line in the source editor, where the error was
detected.

The line where the error occurs is also indicated by a yellow light bulb. If you
move the mouse over the light bulb, the error message is shown.

Figure 5-17 Identifying errors in Java code

To more easily find the errors in the file you are working in, you can filter the
Tasks view to only show errors related to the current resource. To do this, click
the Filter icon in the Tasks view and select the entry On selected resource
only (or On any resource in same project) in the Filter Tasks dialog (Figure 5-18).

108 WebSphere Studio Application Developer Version 5 Programming Guide


Typical setting:
resources in
the same
project

Figure 5-18 Filter Tasks dialog

Debugging your code


How to debug Java applications in Application Developer is described in detail in
Chapter 16, “Testing and debugging” on page 553. In this section we will only
take a quick look at how to debug the simple Java application we have just
created.

Setting a breakpoint in a method causes the Debug perspective to open. A


breakpoint is a temporary marker in your code to tell the debugger to suspend
executing your program at a given point.

To set a breakpoint in the code, double-click in the grey area left of the statement
in the Java editor where you want to set the breakpoint. You can also open the
context menu and select Add Breakpoint (Figure 5-19).

Chapter 5. Developing Java applications 109


If you want to see all breakpoints that are currently set, select Window -> Show
View -> Other and select the Breakpoints view located in the Debug tree.

Figure 5-19 Setting a breakpoint

To debug the CustomerListing class, you can start the program in debug mode
by clicking the Debug icon in the toolbar .

This opens the Debug perspective and run the program until the first breakpoint
has been reached. Within the Debug perspective you can view, inspect, and
modify variables, and can trace your code (Figure 5-20).

Step through
the code

Watch the variables

Breakpoint

Figure 5-20 Debug perspective

110 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Step through the code line by line using the icon in the toolbar of the
Debug view. Other icons let you step into methods, or step to the return of a
method.
򐂰 Watch the variable values in the Variables view.
򐂰 Run the program to the end using the icon.
򐂰 Close the Debug perspective and any open editors.

Preparing a utility project


Utility projects are Java projects containing code that should be available to
multiple modules of an enterprise application.

J2EE 1.3 provides support for utility JAR files at the enterprise application level.
Such JAR files are then made available to Web and EJB modules as JAR file
dependencies.

Banking model
Later in this book, when we implement an enterprise application with a Web
module in Chapter 7, “Developing Web applications” on page 179, we will use a
banking model that we define in the Java project. Figure 5-21 shows the types
used in the banking model.

Front-end Façade Business


Model
Banking
Bank
Test

Servlet 1:m 1:m

Customer Account
m:m

1:m
JSP

TransRecord

Figure 5-21 Banking model

Chapter 5. Developing Java applications 111


Customer A customer of the bank.
Account A bank account. A customer may have multiple bank accounts
and an account may be owned by multiple customers.
TransRecord A transaction record that is generated for each banking
transaction, such as a deposit, withdrawal, or transfer of money
between two accounts. A bank account may have many
transaction records.
Bank The mediator. Mediators act as coordinators, encapsulating the
other objects and how they interact. The bank class holds the
customer, account, and transaction record objects, and
methods to work with them.
In Chapter 12, “Developing EJB applications” on page 373 we
replace the Bank class with a EJB session bean that provides
the same functions. The session bean interacts with entity
beans that map to relational tables.
BankingTest The facade. The intent of facades is to provide a simple and
unified interface to the otherwise complex model that lies
behind it. By doing so, we reduce the dependencies between
the model classes and its clients. Less dependencies mean
more freedom to adapt to new requirements.
The BankingTest facade is for testing purposes only. We will
implement the real facade in the front-end modules, for
example, in Web applications.

Note: Both mediator and facade are documented design patterns. Refer to
Design Patterns: Elements of Reusable Object-Oriented Software.

Design considerations
This design with separation of front-end and backend enables us to implement
multiple front-ends and multiple business models that work with each other.
򐂰 In Chapter 7, “Developing Web applications” on page 179, we implement a
front-end Web application using basic servlets and JSPs.
򐂰 In Chapter 10, “Developing Struts applications” on page 293, we implement a
front-end Web application using the Struts framework.
򐂰 In Chapter 12, “Developing EJB applications” on page 373, we implement the
business model as enterprise beans (EJBs). With a small change to the
facade bean we can then run both Web applications against the EJB business
model.

112 WebSphere Studio Application Developer Version 5 Programming Guide


Implementation
We use an implementation in regular JavaBeans with data in memory for the
model. Additional services like persistence, distribution, security, or transaction
management were not considered. We wanted to keep the model layer as simple
as possible, not to add to the complexity natural to this kind of application.

However, we can redesign the model with the use of an underlying database at
any time.

Packages and classes


The model is implemented in these packages and classes:
itso.bank.model Model classes: Bank, Customer, Account, TransRecord
Customer: id, title, firstname, lastname
Account: id, balance, type
TransRecord: timeStamp, transType, transAmt
itso.bank.facade The facade for banking operations is the BankingTest
class. This is the initial implementation of the facade.
itso.bank.exception Application exceptions: AccountDoesNotExistException,
CustomerDoesNotExistException, ZeroAmountException,
InvalidAmountException, BankException,
InsufficientFundsException
itso.bank.util Converter of amounts between numeric and character
representations: AmountConverter
itso.bank.main Test program: BankMain

The Bank class initializes the data in memory. Instances of customers and
accounts are kept as java.util.Map. The customer-account relationship is held
as a java.util.Vector for each customer within a java.util.Map. The
transaction records of an account are held as a java.util.TreeSet for each
Account within a java.util.Map.

All amounts are kept as java.math.BigDecimal, which provide accurate


calculations of amounts.

Business logic
All classes provide getter and setter methods for the attributes. To work with the
model the following business logic methods are provided:
򐂰 The Customer class provides no special methods.
򐂰 The Account class provides deposit and withdraw methods to perform
banking transactions.

Chapter 5. Developing Java applications 113


򐂰 The TransRecord class provides no special methods.
򐂰 The Bank class provides:
– Customer getCustomer(customerID)—retrieve customer information
– Account getAccount(accountID)—retrieve account information
– Account[] get Accounts(customerID)—retrieve the accounts of one
customer as an array
– TransRecord[] getTransactions(accountID)—retrieve the transactions
records of one account as an array
– BigDecimal deposit(accountID, amount)
– BigDecimal withdraw(accountID, amount)
– BigDecimal ransfer(accountID1, accountID2, amount)
򐂰 The BankingTest facade class provides the same methods as the Bank class
and forwards the execution to the Bank class.

Importing the implementation


The banking model is provided in a JAR file that you can import into the
ItsoProGuideJava project, which becomes our utility project:
򐂰 Select the ItsoProGuideJava project and Import (context).
򐂰 Select ZIP file and click Next.
򐂰 Click Browse and locate the file:
\sg246957\sampcode\dev-java\BankingModel.jar
򐂰 Select Overwrite existing resources without warning.
򐂰 Click Finish.

After importing the code you find the five packages in the ItsoProGuideJava
project.

We will use the ItsoProGuideJava project as a utility project in Chapter 7,


“Developing Web applications” on page 179.

Testing the model


To test the model, select the ItsoProGuideJava project and Run -> Run As ->
Java Application. When prompted, select the BankMain class and click OK.

Alternatively, you can run the BankMain program using the instruction in “Running
your programs” on page 103.

The program executes a few of the business methods and displays the output in
the Console view.

114 WebSphere Studio Application Developer Version 5 Programming Guide


Programming assists
Application Developer contains a number of Java programming assist features.
These features are designed to make life easier for both experienced and novice
Java programmers by simplifying or automating many common tasks.

The following topics are covered:


򐂰 Pluggable JDK
򐂰 Java Scrapbook
򐂰 Code assist
򐂰 Navigating through your code
򐂰 Import generation
򐂰 Tasks view
򐂰 Refactoring
򐂰 Code generation actions
򐂰 Smart compilation
򐂰 Java search and working sets
򐂰 Bookmarks

Pluggable JDK
To provide support for different JDK levels and run-time environments, new JREs
can be added to the Workbench. For each project you can then select which
particular JRE you would like to use. By default the current version of Application
Developer supports the IBM JDK 1.3.1. The corresponding JRE will be used for
all projects unless it has been specified differently.

See “Installed JREs” on page 39 of Chapter 2, “Setting up your Workbench and


workspace preferences” on page 21 for more information regarding the JRE
environment of Application Developer and how to add a new JRE.

Java Scrapbook
Snippets of Java code can be entered in a Scrapbook window and evaluated by
simply selecting the code and running it. This feature can be used to quickly test
code without having to modify any actual Java source file.

These scrapbook pages can be added to any project. The extension of a


scrapbook page is jpage, to distinguish them from normal Java source files.

Tip: Content assist (such as code assist) is also available on scrapbook


pages.

Chapter 5. Developing Java applications 115


To create a scrapbook page, select a folder (itso.java) and New -> Scrapbook
Page (context). Make sure the correct folder is selected and enter a file name
(JavaTest) for the new page (Figure 5-22).

Figure 5-22 Create Java Scrapbook Page dialog

Click Finish to create the scrapbook page. After the page has been created and
opened in the source editor, you can start entering code snippets in it.

To test a scrapbook page, we use code similar to the BankingTest class from the
banking model (Figure 5-23). The code is available in:
sg246957\sampcode\dev-java\JavaTest.jpage

Tip: All class names in a scrapbook page must be fully qualified or you have to
set import statements:
򐂰 Select Set Imports from the context menu anywhere in the scrapbook.
򐂰 For our example, select the itso.bank.model, itso.bank.util, and
java.util packages.

After you have added the code, you can run one of the snippets by selecting the
code and Run Snippet (context) or click the Run the Selected Code icon in
the toolbar. The result are displayed in the Console view.

116 WebSphere Studio Application Developer Version 5 Programming Guide


// ------------------------------------- snippet 1
Bank bank = Bank.getInstance();
for (int i=101; i<107; i++) {
String id = String.valueOf(i);
Customer customer = bank.getCustomer(id);
System.out.println("Customer: " + id + " " + customer.getLastName());
Account[] accounts = bank.getAccounts(id);
for (int j=0; j<accounts.length; j++) {
Account account = accounts[j];
System.out.println(" - Account: " + account.getId() + " "
+ AmountConverter.fromDecimal(account.getBalance()));
}
}

// ------------------------------------- snippet 2
Bank bank2 = Bank.getInstance();
itso.bank.facade.BankingTest banking = new itso.bank.facade.BankingTest();
String acct1 = "101-1001";
String acct2 = "101-1002";
System.out.println("Transfer 33 from " + acct1 + " to " + acct2);
banking.transfer(acct1, acct2, new java.math.BigDecimal("33"));
System.out.println("Account: " + acct1 + " "
+ AmountConverter.fromDecimal(banking.getAccount(acct1).getBalance()));
TransRecord[] tx = banking.getTransactions(acct1);
for (int j=0; j<tx.length; j++) {
TransRecord tr = tx[j];
System.out.println(" - Tx: " + tr.getTimeStamp() + " " +
tr.getTransType() + " "+
AmountConverter.fromDecimal(tr.getTransAmt()));
}

Figure 5-23 Scrapbook code sample

Note: You cannot run code in a scrapbook page until you have at least one
statement selected.

You can also select Display from (context) to display the result expression or
Inspect to bring up the Expressions view, which allows you to inspect the result
like a variable in the debugger (see Chapter 16, “Testing and debugging” on
page 553 for more information about debugging and inspecting).

Change one of the account numbers for the transfer in snippet 2 to an invalid
account and run the code again. The debugger opens when the exception is
thrown.

Chapter 5. Developing Java applications 117


Code assist
When writing Java code, you can use the code assist feature of the Application
Developer to display classes, methods, fields and variables that are valid to use
in the current context. In the example in Figure 5-24, you want to use the method
from the SQL Connection class to create a new SQL statement, but you cannot
remember the exact name and parameters. To see all valid methods, position the
cursor at the point where you want to insert the method call and press
Ctrl-Space.

A window is displayed and lists all methods and fields available for this object. In
addition, an infopop window is displayed, which shows the Javadoc associated
with the selected item. To insert a call to the method createStatement, simply
double-click the method’s name or press Enter on your keyboard.

Figure 5-24 Code assist feature

The Java editor also supports syntax highlighting and hover help for the Java
code, which displays the Javadoc associated with the selected code.

Application Developer also provides templates, which helps the user to add
occurring source code patterns. For more information regarding templates see
“Templates” on page 43.

118 WebSphere Studio Application Developer Version 5 Programming Guide


Navigating through your code
By default, the Java perspective contains an Outline view on the right hand side
of the Java source editor (Figure 5-25). The Outline view displays an outline of a
structured file that is currently open in the editor area, and lists structural
elements. The contents of the Outline view are editor-specific. For a Java source
file (our example), the structural elements are classes, fields, and methods.

By selecting elements in the Outline view, you can navigate to the corresponding
point in your code. This allows you to easily find methods and field definitions
without scrolling the editor window.

Figure 5-25 Using the Outline view for navigation

Tip: If you have a source file with many fields and methods, you can use the
Show Source of Selected Element Only icon from the toolbar to limit the
edit view to the element that is currently selected in the Outline view.

The Package Explorer view, which is available by default in the Java perspective,
can also be used for navigation (Figure 5-26).

The Package Explorer view provides you with a Java-specific view of the
resources shown in the Navigator. The element hierarchy is derived from the
project's build paths.

Chapter 5. Developing Java applications 119


Figure 5-26 Package Explorer view

Import generation
The Application Developer Java Editor simplifies the task of finding the correct
import statements to use in your Java code.

Simply select the type name in the code and select Add Import from the context
menu. If the type name is unambiguous, the import will be pasted at the correct
place in the code. If the type exists in more than one package, a window with all
the types is displayed and you can choose the correct type for the import
statement.

Figure 5-27 shows an example where the selected type (Statement) exists in
several packages. Once you have determined that the java.sql package is what
you want, double-click the entry in the list and the import statement is generated
in the code.

120 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-27 Import generation

You can also add the required import statements for the whole compilation unit.
Open the context menu somewhere in the Java source editor and select Source
-> Organize Imports. The code in the compilation unit is analyzed and the
appropriate import statements are added.

You can control the order in which the imports are added and when package level
imports should be used through the Preferences dialog. See “Organize imports”
on page 42 for details about this feature.

Tasks view
The Tasks view displays the following information:
򐂰 System generated tasks errors
򐂰 User-defined tasks that you add manually

System generated tasks are typically created by the various builders. System
generated tasks can be errors, warnings, or information associated with a
resource. For example, if you save a Java source file that contains syntax errors,
the errors will automatically be logged in this view.

Chapter 5. Developing Java applications 121


User-defined tasks are global and not related to a particular resource or folder.
Tasks in this context are similar to an item in a to-do list. Any user task can be
inserted into the Tasks view and tracked for completion.

Figure 5-28 shows an example of the Tasks view with one user-defined task and
five system generated tasks (a broken link warning in an HTML file and four
compile errors in a Java file).

Figure 5-28 Tasks view

Also, the Tasks view can be filtered to show only specific types of tasks. For
example, you may want to see only error or tasks related to a specific resource.
For more information on this issue, refer to “Locating compile errors in your code”
on page 108.

A typical filter in a Java project would be to display the tasks that apply to any
resource in same project (see Figure 5-18 on page 109).

Refactoring
When developing Java applications, it is often necessary to perform tasks such
as renaming classes, moving classes between packages, and breaking out code
into separate methods. The term refactoring is sometimes used to describe
these types of changes. In traditional programming environments such tasks are
both time consuming and error prone, because it is up to the programmer to find
and update each and every reference throughout the project code. Application
Developer provides functions to automate this process.

The Java development tools (JDT) of Application Developer provides assistance


for managing refactoring. In the Refactoring wizard you can select:
򐂰 Refactoring with preview—Click Next in the dialog to bring up a second
dialog panel where you are notified of potential problems and are given a
detailed preview of what the refactoring action will do.
򐂰 Refactoring without preview—Click Finish in the dialog and have the
refactoring performed. If a stop problem is detected, refactoring is halted and
a list of problems is displayed.

122 WebSphere Studio Application Developer Version 5 Programming Guide


Table 5-1 shows the refactoring actions available in Application Developer.

Table 5-1 Refactoring actions


Name Function

Rename Starts the Rename refactoring wizard. Renames the selected


element and (if enabled) corrects all references to the elements
(also in other files). Is available on methods, fields, local variables,
method parameters, types, compilation units, packages, source
folders, projects and on a text selection resolving to one of these
element types.

Move Starts the Move refactoring wizard. Moves the selected elements
and (if enabled) corrects all references to the elements (also in
other files). Can be applied on one or more static methods, static
fields, types, compilation units, packages, source folders and
projects and on a text selection resolving to one of these element
types.

Pull Up Starts the Pull Up refactoring wizard. Moves a field or method to its
super class. Can be applied on one or more methods and fields
from the same type or on a text selection resolving to a field or
method.

Modify Starts the Modify Parameters refactoring wizard. Changes


Parameters parameter names and parameter order and updates all references
to the corresponding method. Can be applied on methods with
parameters or on text selection resolving to a method with
parameters.

Extract Method Starts the Extract Method refactoring wizard. Creates a new
method containing the statements or expressions currently
selected and replaces the selection with a reference to the new
method.

Extract Variable Starts the Extract Variable refactoring wizard. Creates a new
variable assigned to the expression currently selected and replaces
the selection with a reference to the new variable.

Inline Local Starts the Inline Local Variable refactoring wizard. Replaces the
Variable references to the selected local variable with the variable's initializer
expression and removes the variable.

Self Encapsulate Starts the Self Encapsulate Field refactoring wizard. Replaces all
Field references to a field with getter and setter methods. Is applicable to
a selected field or a text selection resolving to a field.

Undo Does an Undo of the last refactoring.

Redo Does a Redo of the last undone refactoring.

Chapter 5. Developing Java applications 123


Refactoring preferences
In the Refactoring preferences page, located in Window -> Preferences -> Java
-> Refactoring, you can select the default level for problems to be displayed when
you are carrying out a refactoring without a preview (Figure 5-29).

Figure 5-29 Refactoring preferences

The set of radio buttons is used to indicate what type of error reporting you want
to see in the refactoring dialog. These options are listed in order of severity. By
default Application Developer will display any error that would occur if the
refactoring is performed.

If you check the option Save all modified resources automatically prior to
refactoring, any outstanding changes will be saved without displaying a prompt.

Refactoring example
The following example of a refactoring operation assumes that you want to
rename a class in your Java program. To initiate the renaming, simply select the
class and select Refactor -> Rename in the context menu. The Refactoring
wizard is displayed, where you rename the class and select the appropriate
refactoring settings (Figure 5-30).

124 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-30 Refactoring wizard

Enter the new name for the class and click Next. If there are any files with
unsaved changes in the Workbench and you have not indicated in the
preferences that the save should be done automatically, you are prompted to
save these files before continuing the refactoring operation.

If problems more severe than the default level set in the refactoring preferences
are anticipated, then the problems page is displayed (Figure 5-31). If the
problems are severe, the Next and Finish buttons are disabled and the
refactoring must be aborted until the problems have been corrected. If the
buttons are enabled, you can select whether to accept the problems and
continue, or to cancel the refactoring operation.

Figure 5-31 Refactoring problems

Selecting Next at this point displays a window showing what actions will be
performed during the refactoring (Figure 5-32).

Chapter 5. Developing Java applications 125


Figure 5-32 Refactoring preview

After reviewing the changes that will be applied, you can again select whether to
Finish or to Cancel the refactoring operation. Clicking Finish will perform the
renaming operation of the class. If there are any problems detected, they will be
displayed after the operation has been completed. The type of problem shown
depends on the settings in the Refactoring preferences dialog (Figure 5-29 on
page 124).

Application Developer provides one level of an undo operation for refactoring


commands. If you want to undo the renaming changes at this point, select
Refactor -> Undo from the menu bar.

Code generation actions


Application Developer’s Java editor allows you to generate default Java code. It
can generate getters and setters, override methods, or add constructors from the
superclass.

126 WebSphere Studio Application Developer Version 5 Programming Guide


Generate getters and setters
When working with the Java editor you can generate accessors (getters and
setters) for the fields of a type inside a compilation unit. There are several ways
to generate getters and setters for a field:
򐂰 Select Source -> Generate Getter and Setter from the context menu in the
Java editor.
򐂰 Select Source -> Generate Getter and Setter from the context menu of the
field in the Outline view.
򐂰 Select Source -> Generate Getter and Setter from the menu bar.

A dialog opens to let you select which methods you want to create. Select the
methods and click OK (Figure 5-33).

Figure 5-33 Generate Getter and Setter dialog

Override methods
The override methods feature helps you to override methods from the
superclass. Select Source -> Override Methods from the menu or Override
Methods in the context menu of a selected type or on a text selection in a type.

The Override Methods dialog (Figure 5-34) displays all methods that can be
overridden from superclasses or implemented from interfaces. Abstract methods
or not yet implemented methods are selected by default.

When clicking OK, method stubs for all selected methods are created.

Chapter 5. Developing Java applications 127


Figure 5-34 Override methods dialog

Add constructors from superclass


This feature allows you to automatically add constructors as defined in the
superclass for the currently selected type. Open the context menu in the Java
editor and select Source -> Add Constructors from Superclass.

Smart compilation
The Java Builder in the Workbench incrementally compiles the Java code as it is
changed, unless you disable the automatic build feature. For more information
consult the section “Automatic builds” on page 27.

Java search and working sets


In addition to the normal text search functionality, Application Developer provides
a special Java element search feature. Using the Java Search dialog, you can
search for types, methods, packages, constructors and fields within the
workspace. The search results can be limited to show only declarations,
references, implementors or read or write access if you are searching for a
specific field.

You can also specify the scope of the search. You can either search the
workspace, choose only the selected resources or create a working set, which
can be used for future searches as well.

128 WebSphere Studio Application Developer Version 5 Programming Guide


Working sets are used, because users often find it necessary to filter views such
as the navigator view in order to reduce clutter. Working sets can be used to filter
resources by only including specified resources. They are selected and defined
using the view's filter selection dialog.

Simply click the Search icon to open the search dialog. Figure 5-35
demonstrates how to search for the field dbtab within a working set.

Figure 5-35 Java search dialog

Type in the search string, specify that you would like to search for a field, and
select Working Set as the scope of this search.

Click Choose to display a new dialog, where you can select an existing working
set or create a new one (Figure 5-36).
򐂰 Click New to create a new working set. Select a Resource working set or a
Java working set and click Next.
򐂰 The last page of the wizard is displayed. You have to name your new working
set and specify the working set content.
򐂰 Click Finish to create the working set.

Chapter 5. Developing Java applications 129


Select the
projects or
folders of the
working set

Figure 5-36 Creating a working set

By confirming this dialog with OK, the new set will be used in our Java search.

Figure 5-37 shows the Java search dialog with the new working set. Click Search
to start the search operation.

130 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 5-37 Java search dialog with Working Set

The search results are displayed in the Search view (Figure 5-38).
Double-clicking the result entry in the Search view opens the source file where
the field has been found and the first match is highlighted. The yellow arrows on
the left hand side indicate the lines where a match has been found.

Figure 5-38 Java search results

Chapter 5. Developing Java applications 131


Bookmarks
Bookmarks are a simple way to navigate to resources that you frequently use.
The Bookmarks view displays all bookmarks in the Workbench. To show the
Bookmarks view choose Window -> Show View -> Other and select Bookmarks
from the Basic section.

To set a bookmark in your code, right-click in the gray sidebar left of your code in
the Java editor and select Add Bookmark (Figure 5-39).

Figure 5-39 Adding a bookmark

A dialog is displayed where you have to enter a name for the new bookmark
(Figure 5-40).

Figure 5-40 Naming a bookmark

132 WebSphere Studio Application Developer Version 5 Programming Guide


The newly created bookmark is indicated by a symbol in the marker bar and also
appears in the Bookmarks view. Double-clicking the bookmark entry in the
Bookmarks view opens the file and navigates to the line where the bookmark has
been created.

Tip: You can bookmark individual files in the Workbench to open them quickly
from the Bookmark’s view later. In the Navigator view, right-click the file that
you want to add to you list of bookmarks and select Add Bookmark from the
file’s pop-up menu.

You can remove a bookmark by using the bookmark’s context menu in the
Bookmarks view and select Delete.

Note: Bookmarks are not specific to Java code. They can be used in any file
to provide a quick way of navigating to a specific location.

Javadoc
Javadoc is a tool in the Java JDK to generate documentation about Java
packages, classes, and methods. The Javadoc documentation is based on
comments entered for each class and method, and the packaging of classes into
packages.

Preferences
The location of the javadoc.exe must be specified in the Javadoc preferences.
Refer to “Javadoc documentation” on page 40 for instructions.

Generating Javadoc
Application Developer provides a wizard to generate Javadoc for selected
packages or projects.

In this section we generate Javadoc for the ItsoProGuideJava project:


򐂰 Select the ItsoProGuideJava project and Export (context).
򐂰 Select Javadoc and click Next.
򐂰 Select the projects (or expand and select packages), member visibility, and
the output location. The default location is in the workspace (Figure 5-41).
Click Next.

Chapter 5. Developing Java applications 133


Figure 5-41 Javadoc generation options (1)

򐂰 On the next page you can specify detailed options about the doclet
generation, including a title (Figure 5-42). Click Next.

Figure 5-42 Javadoc generation options (2)

134 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 On the final page, select the options for generating an Ant script and opening
a browser (Figure 5-43). Click Finish.

Figure 5-43 Javadoc generation options (3)

򐂰 Watch the generation of Javadoc in the Console view:


Loading source files for package itso.bank.facade...
......
Constructing Javadoc information...
Building tree for all the packages and classes...
Generating E:\WSAD5sg246957\ItsoProGuideJava\doc\itso\bank\facade\class-use
\BankingTest.html...
......
Building index for all the packages and classes...
Generating E:\WSAD5sg246957\ItsoProGuideJava\doc\overview-tree.html...
......
Building index for all classes...
Generating E:\WSAD5sg246957\ItsoProGuideJava\doc\allclasses-frame.html...
Generating E:\WSAD5sg246957\ItsoProGuideJava\doc\index.html...
Generating E:\WSAD5sg246957\ItsoProGuideJava\doc\packages.html...
......
򐂰 A browser opens with the generated Javadoc and you can explore the
documentation of the packages and classes (Figure 5-44).

Chapter 5. Developing Java applications 135


Figure 5-44 Generated Javadoc in a browser

Note that our source classes do not have many comments for good Javadoc!
򐂰 To see the generated files in the Workbench, select the ItsoProGuideJava
project and Refresh (context).
򐂰 In general you would not generate Javadoc into the Workbench but rather into
a documentation location. Either move the data to another location or delete
the doc folder from the project.

Using Ant to generate Javadoc


The javadoc wizard generated an Ant build script (javadoc.xml) in the
ItsoProGuideJava project. This build script that can be used to regenerate the
documentation (Figure 5-45).

136 WebSphere Studio Application Developer Version 5 Programming Guide


<?xml version="1.0" encoding="UTF-8"?>
<project default="javadoc" name="ItsoProGuideJava">
<target name="javadoc">
<javadoc access="public" author="true"
classpath="E:\WSAD5sg246957\ItsoProGuideJava;
D:\SQLLIB\java\db2java.zip"
destdir="E:\WSAD5sg246957\ItsoProGuideJava\doc"
doctitle="ItsoProGuide Javadoc" nodeprecated="false"
nodeprecatedlist="false" noindex="false" nonavbar="false"
notree="false"
packagenames="itso.bank.facade,itso.bank.exception,
itso.bank.main,itso.bank.model,itso.bank.util,itso.java"
sourcepath="E:\WSAD5sg246957\ItsoProGuideJava"
splitindex="true" use="true" version="true"/>
</target>
</project>

Figure 5-45 Javadoc Ant build script

To regenerate the Javadoc, select the javadoc.xml file and Run Ant (context) and
click Finish in the pop-up dialog.

See Chapter 19, “Building applications with Ant” on page 633 for detailed
information about Ant.

Summary
In this chapter we described how to create a new Java project and how to work
with the programming assists of Application Developer by creating a simple Java
class.

While you are working with larger projects you will experience the benefits of the
programming assists and the Java development tools.

We also demonstrated how to prepare and implement a utility project and how to
generate Javadoc.

Chapter 5. Developing Java applications 137


138 WebSphere Studio Application Developer Version 5 Programming Guide
6

Chapter 6. Developing database


applications
In this chapter we explain how to connect to a database from a Java application.
Concepts such as JDBC and data sources are covered.

We then go into detail about the wizards included in Application Developer to


work with databases. This includes tools to build your own databases and SQL
statements, as well as the wizards to access a database from Java applications.

This chapter covers the following topics:


򐂰 JDBC overview
򐂰 Data source versus direct connection
򐂰 Application Developer database operations
򐂰 XMI and DDL
򐂰 Data perspective
򐂰 Using the DB Servers view
򐂰 Creating database objects
򐂰 Using the SQL Statement Wizard
򐂰 Using SQL Query Builder
򐂰 Accessing databases from a Java application

© Copyright IBM Corp. 2003. All rights reserved. 139


JDBC overview
Java Database Connectivity (JDBC), like Open Database Connectivity (ODBC),
is based on the X/Open SQL call-level interface specifications, but unlike ODBC,
JDBC does not rely on various C features that do not fit well with the Java
language. Using JDBC, you can make dynamic calls to databases from your Java
applications or Java applets.

JCBC is vendor neutral and provides access to a wide range of relational


databases, as well as to other tabular sources of data. It can even be used to get
data from flat files or spreadsheets. This portability and versatility are the main
attractions of using JDBC for database access in application programs. JDBC is
especially suited for use in Web applications. Using the JDBC API you can
connect to databases using standard network connections. Any modern Web
browser is Java enabled, so you do not have to worry about whether the client
can handle the application or not.

Figure 6-1 shows the basic components of JDBC access. The JDBC API sends
the SQL commands from the application through a connection to the vendor
specific driver that provides access to the database. Connections can be
established through a driver manager (JDBC 1.0) or a data source (JDBC 2.0).

Java Application

getConnection getConnection

JDBC Driver Connection Data Source


Manager

Vendor supplied
JDBC Driver

Database

Figure 6-1 JDBC overview

140 WebSphere Studio Application Developer Version 5 Programming Guide


Data source versus direct connection
In JDBC 1.0 the only way of establishing a database connection was by using the
DriverManager interface. This was expensive in terms of performance because a
connection was created each time you had to access the database from your
program, thereby incurring a substantial processing overhead. In the JDBC 2.0
Standard Extension API an alternative way of handling database connections
was introduced.

By using data source objects you have access to a pool of connections to a data
source. Using connection pooling gives you the following advantages:
򐂰 It improves performance. Creating connections is expensive; a data source
object creates a pool of connections as soon as it is instantiated.
򐂰 It simplifies resource allocation. Resources are only allocated from the data
source objects, and not at arbitrary places in the code.

Data source objects work as follows:


򐂰 When a servlet or other client wants to use a connection, it looks up a data
source object by name from a Java Naming and Directory Interface (JNDI)
server.
򐂰 The servlet or client asks the data source object for a connection.
򐂰 If the data source object has no more connections, it may ask the database
manager for more connections (as long as it has not exceeded the maximum
number of connections).
򐂰 When the client has finished with the connection, it releases it.
򐂰 The data source object then returns the connection to the available pool.

Important: Because of the advantages of connection pooling, using data


source objects is the preferred method of handling database connections in
Web applications. The WebSphere Application Server has full support for
connection pooling and for registering data sources through JNDI.

If you use the Create database Web pages wizard, described in detail in
“Accessing databases from a Web application” on page 248, you have the option
of generating code to use either a driver manager connection or a data source
connection.

Chapter 6. Developing database applications 141


Application Developer database operations
Application Developer provides a number of features that make it easier to work
with relational databases in your projects.
򐂰 Ability to import and use existing database models.
򐂰 Ability to create your own database objects and generate DDL for the target
database.
򐂰 Ability to generate XML schemas from database models.
򐂰 Ability to interactively build and execute SQL queries from an imported
database model or through an active connection, using SQL Wizard and SQL
Query Builder.
򐂰 Ability to generate Web pages and supporting Java classes based on existing
or new SQL queries.
򐂰 Ability to access database API from JavaServer Pages, using either
JavaBeans or JSP tags.

These features will be discussed in more detail later in this chapter.

XMI and DDL


XML Metadata Interchange (XMI) is an Object Management Group (OMG)
standard format for exchanging metadata information. Application Developer
uses the XMI format to store all local descriptors of databases, tables, and
schemas. The content of the XMI files can be viewed and edited using tailored
editors. When you import an existing database model, it can be stored in XMI
format.

Data definition language (DDL) is a format used by relational database systems


to store information about how to create of database objects. Application
Developer allows you to generate DDL from an XMI file and vice versa.

Data perspective
The Data perspective is used to work with databases, tables, and SQL
statements. See “Data perspective” on page 68 for an introduction.

There are three main views in the Data Perspective:


򐂰 DB Servers view
򐂰 Data Definition view
򐂰 Navigator view

142 WebSphere Studio Application Developer Version 5 Programming Guide


DB Servers view
The DB Servers view shows active connections to databases and allows you to
create new connections. In Figure 6-2 you can see an active connection to the
EJBBank DB2 database. We will create this connection in “Creating a database
connection” on page 145.

Figure 6-2 DB Servers view

The DB Servers view is independent of any projects. It displays active


connections to databases. When you stop Application Developer, the
connections become inactive and no databases and tables are displayed.

An inactive connection can be activated by selecting the connection and


Reconnect from the context menu.

Data Definition view


The Data Definition view (Figure 6-3) shows the database models that currently
exist in Application Developer. These are either imported through the DB Servers
view or created within the Workbench. In this example we imported the data
model from the DB Servers view.

Chapter 6. Developing database applications 143


Database models are stored within an Application Developer project. This can be
any type of project; for example, a simple project, a Web project with database
access, or an EJB project with entity beans.

The Data Definition view is a hierarchical view of the database objects and does
not display how these definitions are stored in actual files.

Figure 6-3 Data Definition view

Navigator view
In the Navigator view (Figure 6-4) you can see the local descriptor files (.xmi
files) that represent the database objects. Each of the files has an editor
associated with it. Double-clicking the file brings up the appropriate editor for the
type of object that is described, which could be either a database, a schema, or a
table.

144 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 6-4 Navigator view

Using the DB Servers view


You can use the DB Servers view to connect to existing databases and view their
objects. The objects can be imported into Application Developer and used in your
applications.

The DB Servers view allows you to filter the designs that are returned to only
show a subset of schemas or tables. You can also use the DB Servers view to
generate DDL files and XML schemas.

Important: The DB Servers view is read-only. Before you can edit any
database objects, you have to import them into an Application Developer
project.

Creating a database connection

Note: The examples in this section assume that you have created and
populated the DB2 tables as described in “Installing the EJBBANK database”
on page 811.

To view the definition of an existing database, you first have to create a JDBC
connection to the database. To create a new connection, first make sure you are
in the DB Servers view. Then right-click anywhere in the view and select New
Connection to display the Database Connection wizard (Figure 6-5).

Chapter 6. Developing database applications 145


Figure 6-5 Creating a JDBC connection

You have to provide a unique name for the connection (Con1 in our example), a
user ID and password if required, and the type of database you are connecting
to. Also, you must specify which JDBC driver should be used. There are two
predefined JDBC drivers for DB2:
򐂰 IBM DB2 APP DRIVER (COM.ibm.db2.jdbc.app.DB2Driver) for connections
to local databases or remote databases defined locally with the DB2 Client
Configuration Assistant.
򐂰 IBM DB2 NET DRIVER (COM.ibm.db2.jdbc.net.DB2Driver) for connections
to remote DB2 databases.

See “DB2 JDBC drivers” on page 175 for more details on DB2 JDBC drivers.

146 WebSphere Studio Application Developer Version 5 Programming Guide


If you do not want to use one of the predefined drivers, you can select Other
Driver from the JDBC driver drop-down, and fill in the JDBC driver class field with
the driver name.

Note: Application Developer now contains support for additional database


systems, such as Cloudscape™, Oracle, Microsoft® SQL Server, Informix,
Sybase, InstantDB, and MySQL.

If you want to limit the schemas, tables, stored procedures or user-defined


functions returned, click the Filters button (Figure 6-5 on page 146), and the
Connection Filters dialog, shown in Figure 6-6, is displayed.

Figure 6-6 Creating a JDBC connection: filter

The dialog has four pages to define filters for schemas, tables, stored
procedures, and user-defined functions. By default, one schema filter is
predefined (SCHEMA NOT LIKE SYS%) by the selection Exclude system schemas.

For our example we are limiting the selection to tables with names starting with
CU. To create the filter, select the Table tab and click Add Filter, and the Add
Filter dialog shown in Figure 6-7 opens.

Chapter 6. Developing database applications 147


Figure 6-7 Adding a new filter

Enter CU% in the entry field and click OK. You can modify the filter by clicking any
cell in the table and changing the value. Click OK to close the filter dialog.

After clicking Finish in the connection window, the connection is created and a
new database entry is added to the DB Servers view. You can expand the new
node to see the schemas and tables that are now available for use (Figure 6-8).

Figure 6-8 DB Servers view of EJBBANK database with table filter applied

Next we create another connection without filters. We will use this connection in
the next section to import database objects into our workspace.

Right-click inside the DB Servers view, and select New Connection from the
context menu. The new connection wizard opens, already containing the default
values for connection name (Con2) and database name (EJBBANK). By default, no
filters are entered. All you have to do is click Finish to create this connection.

Figure 6-9 shows the DB Servers view, which now contains the new connection
Con2. This new connection has no table filters, so it shows all the tables in the
EJBBANK database.

148 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 6-9 Updated DB Servers view with two connections

Importing database objects


In the DB Servers view you can browse the tables and columns, but before you
can actually use them in your application, you have to import them into a folder in
a project.

Simple project
We use a simple project to store the database definitions. A simple project is a
generic project that contains files and folders. To create the project select File ->
New -> Project. Then select Simple and Project from the New Project dialog and
click Next. Enter ItsoProGuideDatabase as the project name, and click Finish.

The Resource perspective opens. However, we will continue to work in the Data
perspective, so we close the Resource perspective.

Import database
We now import the EJBBANK database into the new project:
򐂰 In the Data perspective, DB Servers view, select the connection Con2 Import
to Folder (context).
򐂰 In the Import dialog (Figure 6-10) click Browse to locate the
ItsoProGuideDatabase project, then click Finish.

Chapter 6. Developing database applications 149


Figure 6-10 Import database objects

In the Data Definition view (Figure 6-11) expand the EJBBANK node. The same
database objects are shown, but you can now open editors on them to view and
modify their definitions.

In the Navigator view you will notice that a number of XMI files have been created
for the database objects. (XMI is an open information interchange model that
allows developers who work with object technology to exchange programming
data over the Internet in a standardized way.)

Figure 6-11 Imported database objects in Data Definition and Navigator views

If you double-click one of these files, the appropriate object editor opens. If you
want to see the XMI source, you can right-click any of the files and select Open
With -> Text Editor.

150 WebSphere Studio Application Developer Version 5 Programming Guide


Generate DDL and XML schema files
Application Developer allows you to generate DDL files and XML Schemas for
database objects. To generate a DDL file, select the database object in the Data
Definition or DB Servers view and Generate DDL (context) to open the Generate
SQL DDL wizard, shown in Figure 6-12. You can generate DDL for the database,
for a schema, or for individual tables.

Figure 6-12 Generate DDL for a database object

Enter the name of the folder where you want the generated .sql file to be stored,
select options for the generation and whether you want to open the SQL editor on
the generated file. If you elect not to open the editor, you will have to switch to the
Navigator view to see the generated file. The generated DDL file is shown in
Example 6-1.

Example 6-1 Generated EJBBANK.sql file (extract)


-- Generated by Relational Schema Center on Mon Mar 17 01:07:11 PST 2003

CREATE SCHEMA ITSO;

CREATE TABLE ITSO.ACCOUNT


(ACCID CHARACTER(8) NOT NULL,
BALANCE DECIMAL(8, 2) NOT NULL,
INTEREST INTEGER NOT NULL,
ACCTYPE VARCHAR(8) NOT NULL,
DISCRIMINATOR CHARACTER(1) NOT NULL,
OVERDRAFT DECIMAL(8, 2) NOT NULL,

Chapter 6. Developing database applications 151


MINAMOUNT DECIMAL(8, 2) NOT NULL);

ALTER TABLE ITSO.ACCOUNT


ADD CONSTRAINT SQL030221140126480 PRIMARY KEY (ACCID);

CREATE TABLE ITSO.CUSTACCT


(CUSTOMERID INTEGER NOT NULL,
ACCID CHARACTER(8) NOT NULL);

ALTER TABLE ITSO.CUSTACCT


ADD CONSTRAINT SQL030221140126190 PRIMARY KEY (CUSTOMERID, ACCID);

CREATE TABLE ITSO.CUSTOMER


(CUSTOMERID INTEGER NOT NULL,
TITLE CHARACTER(3) NOT NULL,
FIRSTNAME VARCHAR(30) NOT NULL,
LASTNAME VARCHAR(30) NOT NULL,
USERID CHARACTER(8),
PASSWORD CHARACTER(8),
ADDRESS BLOB(2000));

ALTER TABLE ITSO.CUSTOMER


ADD CONSTRAINT SQL030221140125890 PRIMARY KEY (CUSTOMERID);
......

ALTER TABLE ITSO.CUSTACCT


ADD CONSTRAINT "CAtoAccount" FOREIGN KEY (ACCID)
REFERENCES ITSO.ACCOUNT(ACCID)
ON DELETE RESTRICT
ON UPDATE NO ACTION;

ALTER TABLE ITSO.CUSTACCT


ADD CONSTRAINT "CAtoCustomer" FOREIGN KEY (CUSTOMERID)
REFERENCES ITSO.CUSTOMER(CUSTOMERID)
ON DELETE RESTRICT
ON UPDATE NO ACTION;
......

XML schemas can be generated for tables. To generate an XML schema for a
table, you must already have imported it into a folder and be in the Data
Definition view.

Select the CUSTOMER table and Generate XML Schema from the context menu,
and the Create XML Schema dialog opens (Figure 6-13).

152 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 6-13 Create XML schema for database table

Click Finish and the schema file (with extension .xsd) is created and opened in
the XML schema editor. The content of the customer XSD file (visible in the
Source tab of the editor) is shown in Example 6-2.

Example 6-2 Generated XML schema


<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.ibm.com/EJBBANK/ITSO"
xmlns:EJBBANKITSO="http://www.ibm.com/EJBBANK/ITSO">

<element name="CUSTOMER_TABLE">
<complexType>
<sequence>
<element ref="EJBBANKITSO:CUSTOMER" minOccurs="0"
maxOccurs="unbounded"/>
</sequence>
</complexType>
<key name="CUSTOMER_PRIMARYKEY">
<selector xpath="EJBBANKITSO:CUSTOMER"/>
<field xpath="CUSTOMERID"/>
</key>
</element>

<element name="CUSTOMER">
<complexType>
<sequence>
<element name="CUSTOMERID" type="integer"/>
<element name="TITLE">

Chapter 6. Developing database applications 153


<simpleType>
<restriction base="string">
<length value="3"/>
</restriction>
</simpleType>
</element>
<element name="FIRSTNAME">
<simpleType>
<restriction base="string">
<length value="30"/>
</restriction>
</simpleType>
</element>
<element name="LASTNAME">
<simpleType>
<restriction base="string">
<length value="30"/>
</restriction>
</simpleType>
</element>
<element name="USERID">
<simpleType>
<restriction base="string">
<length value="8"/>
</restriction>
</simpleType>
</element>
<element name="PASSWORD">
<simpleType>
<restriction base="string">
<length value="8"/>
</restriction>
</simpleType>
</element>
<element name="ADDRESS">
<simpleType>
<restriction base="base64Binary">
<length value="2000"/>
</restriction>
</simpleType>
</element>
</sequence>
</complexType>
</element>
</schema>

Notice the Graph page of the XML schema editor (Figure 6-14). Expand the
boxes by clicking the + icon.

154 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 6-14 XML schema editor: graph

Study the Outline view as well. It shows the structure of the XML schema file.

If you want, you can make changes to the XML file and generate a new DDL file
by selecting Generate -> DDL (context).

Creating database objects


Application Developer provides support for creating new databases, new
schemas, and new tables.

Create database
To create a new database you have to have a project. If you have not already
done so, you should now create a new simple project called
ItsoProGuideDatabase.

To create database objects you have to switch to the Data perspective and open
the Data Definition view.

Chapter 6. Developing database applications 155


To create a database select the ItsoProGuideDatabase project and New -> New
database definition. The Database creation dialog is displayed (Figure 6-15).

Figure 6-15 Database definition dialog

Here you specify the name of the new database and the vendor type. When you
later generate the database DDL it will conform to the database type that you
select. Click Finish to create the new database definition.

Important: Database definitions created within Application Developer are not


automatically created in the database system. You have to export the DDL and
use the appropriate database tool to create the objects, or you can submit the
DDL from Application Developer (see “Define the database schema in a
database system” on page 163).

Database schemas are a way of providing a logical classification of objects in the


database. Some of the objects that a schema may contain include tables, views,
aliases, indexes, triggers, and structured types. The support for schemas varies
between database types; some require them, and some have no support for
them. The schema options available to you depend on the database type that
you chose when the database was created. If the database type does not
support schemas at all, this option will not be available, and the tables and other
objects will be created directly under the database node.

156 WebSphere Studio Application Developer Version 5 Programming Guide


Create schema
To add a schema to the database, select the database created in the previous
step and New -> New schema definition. The Schema Definition dialog is
displayed (Figure 6-16).

Figure 6-16 Schema definition dialog

Select a name (ITSO) for the schema and click Finish to create it.

Expand the new schema in the Data Definition view and you will see the types of
objects that can be added to it.
򐂰 Tables
򐂰 Views
򐂰 Aliases
򐂰 Indexes
򐂰 Triggers
򐂰 Structured types
򐂰 Stored procedures
򐂰 User-defined functions

Note: In the current release of Application Developer, tables, views, stored


procedures, and user-defined functions can be created. The other types of
objects are not supported.

Create table
We will now look at how to create a new table in the schema. Application
Developer provides a wizard for defining table columns as well as primary and
foreign keys. To create a table, select the schema created in the previous step

Chapter 6. Developing database applications 157


and New -> New table definition. The Create table wizard is displayed
(Figure 6-17).

Figure 6-17 Table definition wizard: table name

Here you give the table a name and an optional comment. On the next page you
define the columns of the table (Figure 6-18).

Figure 6-18 Table definition wizard: columns

158 WebSphere Studio Application Developer Version 5 Programming Guide


Click Add Another to add a column to the table and define the column properties.
The exact properties available depend on the database type. For more
information about the properties available, you can consult the documentation
provided by the database vendor.

In our case, in addition to the CUSTOMERID field, we add FIRSTNAME and LASTNAME.
These two additional fields are of type CHARACTER with string length 30 and For bit
data not checked (Figure 6-17).

Figure 6-19 Table definition wizard: columns

The next page of the wizard lets you define the primary key of the table
(Figure 6-20).

Chapter 6. Developing database applications 159


Figure 6-20 Table definition wizard: primary key

You select the items you want from the Source Columns and add them to the
primary key by clicking >.

On the final page of the wizard you can define any foreign key constraints that
you want to apply. In our case, we do not have another table defined, so we do
not add a foreign key (Figure 6-21).

Figure 6-21 Table definition wizard: foreign keys

160 WebSphere Studio Application Developer Version 5 Programming Guide


Clicking Finish creates the table and keys as defined.

If you want, you can generate the DDL for the table you have just created. To do
so, select the table in the Data Definition view and Generate DDL and the
Generate SQL DDL dialog opens (Figure 6-22).

Figure 6-22 Generate DDL dialog

The options available are to create the DDL with or without the schema name,
whether to place delimiters around identifiers or not, whether or not to generate
DROP statements, and whether to open an editor on the generated file. The
generated DDL file is shown in Figure 6-23.

-- Generated by Relational Schema Center on Mon Mar 17 01:56:34 PST 2003

CREATE TABLE ITSO.CUSTOMER


(CUSTOMERID INTEGER NOT NULL,
FIRSTNAME CHARACTER(30) NOT NULL,
LASTNAME CHARACTER(30) NOT NULL);

ALTER TABLE ITSO.CUSTOMER


ADD CONSTRAINT C4956569 PRIMARY KEY (CUSTOMERID);

COMMENT ON TABLE ITSO.CUSTOMER IS 'Table containing customer details';

Figure 6-23 Generated DDL file for the customer table

Chapter 6. Developing database applications 161


You can use the generated DDL to create the table in the database system with
the help of the appropriate tool provided by the database vendor.

You can also execute the DDL on a database server. See “Define the database
schema in a database system” on page 163.

Create table with foreign key


Now we will create a second table with a foreign key. Use the same wizard as
above to create a CUSTADDRESS table with the following columns:
򐂰 ADDRESSID—as an INTEGER and also a key column
򐂰 CITY—as a CHARACTER 50
򐂰 COUNTRY—as a CHARACTER 50
򐂰 CUSTOMERID—as an INTEGER

On the foreign keys page of the wizard (Figure 6-24), click Add Another to add a
foreign key.

Figure 6-24 Defining a foreign key

162 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Select ITSO.CUSTOMER as the target table, then select CUSTOMERID in the
Source Columns list and click >. This defines the primary key of the
ITSO.CUSTOMER table to be the foreign key in the CUSTADDRESS table.
򐂰 Define constraints for referential integrity as RESTRICT for delete and NO
ACTION for update.
򐂰 Click Finish and the new table CUSTADDRESS, complete with foreign key has
been generated in our model. You can again generate DDL to produce the
DDL file for this table (Figure 6-25).

-- Generated by Relational Schema Center on Mon Mar 17 02:09:21 PST 2003

CREATE TABLE ITSO.CUSTADDRESS


(ADDRESSID INTEGER NOT NULL,
CITY CHARACTER(50) NOT NULL,
COUNTRY CHARACTER(50) NOT NULL,
CUSTOMERID INTEGER NOT NULL);

ALTER TABLE ITSO.CUSTADDRESS


ADD CONSTRAINT C0107854 PRIMARY KEY (ADDRESSID);

ALTER TABLE ITSO.CUSTADDRESS


ADD CONSTRAINT C4412200 FOREIGN KEY (CUSTOMERID)
REFERENCES ITSO.CUSTOMER(CUSTOMERID)
ON DELETE RESTRICT
ON UPDATE NO ACTION;

Figure 6-25 DDL for address table

Define the database schema in a database system


To define the ITSOTEST database with its schema and tables in a DB2 system,
generate the DDL for the database.

Select the ITSOTEST object and Generate DDL (context). Note that the generated
file (ITSOTEST.sql) does not contain the DDL for the database object itself, only
the schema and the tables are defined.

Create the database


Create the database, for example, in a DB2 Command Window with the
command:
db2 create database ITSOTEST

Chapter 6. Developing database applications 163


Create the schema and tables
Select the ITSOTEST.sql file and Run on Database Server. The Run Script dialog
opens (Figure 6-26). Select the statements that you want to execute.

Figure 6-26 Run DDL script

Click Next. On the next page, set the commit option, for example, Commit
changes only upon success (Figure 6-27).

Figure 6-27 Commit options for DDL script

Click Next. On the connection page, create a connection to the ITSOTEST


database. The dialog is the same as Figure 6-5 on page 146.

164 WebSphere Studio Application Developer Version 5 Programming Guide


Click Finish and the DDL statements are executed against the database. Using a
DB2 Command Window you can verify that the objects are created:
db2 connect to itsotest
db2 select * from itso.customer
db2 select * from itso.custaddress

This completes our look at creating database objects.

Creating SQL statements


There are two alternative ways of creating an SQL statement in Application
Developer:
򐂰 SQL Statement Wizard—The SQL Statement Wizard is a guided dialog
through a number of panels, with an SQL statement as the result.
򐂰 SQL Query Builder—The SQL Query Builder is an editor for an advanced
user.

Both tools can be used to build an SQL statement. After using the SQL
Statement Wizard, you can use the SQL Query Builder to updates the SQL
statement.

For our example we are developing a SELECT statement against the sample
EJBBANK database. We would like to see a list of all credit transactions where the
last name of the customer contains the letter “o”. We like to see the transaction
ID, account ID, and the first and last name of the customer, as well as the
transaction amount.

Basically we construct this SQL statement:


SELECT t.TRANSID, c.FIRSTNAME, c.LASTNAME, t.ACCID, t.TRANSAMT
FROM CUSTOMER c, CUSTACCT a, TRANSRECORD t
WHERE c.CUSTOMERID = a.CUSTOMERID
AND a.ACCID = t.ACCID
AND t.TRANSTYPE = 'C'
AND c.LASTNAME LIKE :lastname

Using the SQL Statement Wizard


In this section we create an SQL statement using the wizard.

To create some order in the project, select the ItsoProGuideDatabase project and
New -> Folder (Navigator view, context). Enter sql as the folder name.

Chapter 6. Developing database applications 165


Select the ItsoProGuideDatabase project and File -> New -> Other. Select Data
and SQL Statement in the New dialog and click Next to open the SQL Statement
Wizard (Figure 6-28).

Figure 6-28 SQL Statement Wizard: specify statement information

On the first page, you select the type of statement you want to create and say
that you want to use the wizard: Be guided through creating an SQL statement.

There are two ways to specify the database model. You can either use an
existing one or import a new one. In this case we already have the database
model imported into the Workbench, so we select Use existing database model.
Click the Browse button to locate the EJBBANK model in the Workbench and enter
the name of the SQL statement.

Selecting tables and columns


On the second page of the SQL Statement Wizard you build your SQL statement
by selecting tables, columns and adding joins and conditions. First we identify the
tables that should be included in the query (Figure 6-29).

166 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 6-29 SQL Statement Wizard: add tables

You select the tables in the left pane and use the > button to include them. For
our example we have the CUSTACCT, CUSTOMER, and TRANSRECORD tables. On the
Columns tab you select the columns from these tables that should be included in
the query (Figure 6-30).

Figure 6-30 SQL Statement Wizard: add columns

Chapter 6. Developing database applications 167


Select FIRSTNAME and LASTNAME from the CUSTOMER table and TRANSID, ACCID and
TRANSAMT from the TRANSRECORD table and move them across to the right pane.
Order the output columns using the Move Up and Move Down buttons.

Defining a table join


Next you have to specify the join columns between the three tables on the Join
tab. This is done by selecting the column from one table and dragging it to the
corresponding column of the other table. In our case we link
CUSTOMER.CUSTOMERID to CUSTACCT.CUSTOMERID and CUSTACCT.ACCID to
TRANSRECORD.ACCID. When the joins are complete, connection symbols are
displayed (Figure 6-31).

Figure 6-31 SQL Statement Wizard: add joins

Tip: You can rearrange the tables by dragging them on the pane. You can
enlarge a table by dragging the sides. You can also select the columns in this
dialog step, or make changes to the selection from the previous step.

Defining the conditions for the WHERE clause


The Conditions tab is used to define the restrictions on the SELECT statement.
Each condition is added to the WHERE clause (Figure 6-32).

Select the Column, Operator, Value, And/Or, using the drop-down menu (visible
after you click in the field). Enter the value by typing in the field.

168 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 6-32 SQL Statement Wizard: add conditions

Using a variable
In a real-life situation you might not want to hardcode that the last name contains
the letter o, but instead leave it as a host variable. Therefore, do not enter '%o%'
in the Value column, rather enter a variable as :lastname. This is especially
useful later in “Accessing databases from a Web application” on page 248.

Tip: If you have to enter more than one condition, you must put in the AND or
the OR element before the next row in the table becomes editable.

On the next two tabs you can enter information regarding grouping (GROUP BY)
and sorting of rows (ORDER BY).

Once you have finished building the statement you can click Next to see the
generated SQL statement (Figure 6-33).

If you want, you can edit the statement directly. When you are finished editing,
you can click Parse to validate that the SQL statement is correct.

Chapter 6. Developing database applications 169


Figure 6-33 SQL Statement Wizard: generated SQL statement

Executing an SQL statement


To test the SQL statement, you click Execute and then Execute again in the next
window. You are prompted for the host variable. Enter '%o%' and click Finish. The
statement is executed and the results are displayed (Figure 6-34).

Host variable prompt

Figure 6-34 SQL Statement Wizard: test SQL statement

170 WebSphere Studio Application Developer Version 5 Programming Guide


Select Close to close the Execute SQL Statement window, then select Finish to
save the SQL Statement.

The SQL statement is opened in the SQL Query Builder editor. Close the editor.
The SQL statement appears as EJBBANK_CreditListing.sqx in the Navigator
view, and as CreditListing in the Data Definition view (under EJBBANK ->
Statements).

Using SQL Query Builder


The other way of creating SQL statements in Application Developer is to use the
SQL Query Builder. This tool supports all the options of the SQL Statement
Wizard, with the addition of WITH and FULLSELECT. In this section we will describe
how to use the SQL Query Builder to build a similar SELECT statement as we did
using the SQL Wizard.

We develop a SELECT statement against the EJBBANK database. We would like to


select credit or debit transactions where the customer’s last name is a variable.
This time we want to display most of the columns of the CUSTOMER and
TRANSRECORD tables.

To start the SQL Query Builder, expand the database folder in the Data Definition
view. Select the Statements folder and New -> Select Statement. A dialog to
enter the name of the statement is displayed. Enter ListCredits and click OK.
The SQL Query Builder editor is displayed (Figure 6-35).

Figure 6-35 SQL Query Builder: create SELECT statement

Chapter 6. Developing database applications 171


To define your query, go through the following steps:
򐂰 First we must add the tables that are involved in the query. In our example
these are CUSTOMER, CUSTACCT, and TRANSRECORD. To add them, simply drag
them from the Navigator or Data Definition view and drop them in the middle
pane of the SQL Query Builder screen. The result is shown in Figure 6-36.
As you can see, the tables have been added to the SELECT statement in the
top pane.

join
join

Figure 6-36 SQL Query Builder: adding tables

򐂰 Next, select the columns from each table. To select a column, check the box
next to its name. For the CUSTOMER table, select all columns except ADDRESS.
For the TRANSRECORD table, select all columns. Do not select any columns of
the CUSTACCT table (they are duplicates anyway). As you select the columns,
the SELECT statement is updated in the top pane and the columns are added
in the bottom pane.
򐂰 Next, join the tables together. To join the tables, select the CUSTOMERID
column in the CUSTOMER table and drag it across to the corresponding column
in the CUSTACCT table. Next, select the ACCID column in the CUSTACCT table and
drag it across to the corresponding column in the TRANSRECORD table. A link

172 WebSphere Studio Application Developer Version 5 Programming Guide


symbol is shown between the tables, and the SELECT statement is updated
with the corresponding WHERE clauses.
򐂰 Finally, we want to add the two conditions (TRANSTYPE = :type and LASTNAME
LIKE :lastname). Use the Conditions tab in the bottom pane to add the
conditions using the drop-down menus, or type them directly into the SQL
statement and the Conditions tab is updated (Figure 6-37).

Join

Conditions

Figure 6-37 SQL Query Builder: adding conditions

Save the statement. You are prompted for the host variables; just click Cancel to
dismiss the dialog.

Chapter 6. Developing database applications 173


To test the statement, select it in the Statements folder and Execute (context) or
select SQL -> Execute in the menu bar.

Enter 'C' as the value for the :type and '%o%' as the value for the :lastname
variables in the Host Variable Values window and click Finish to execute the
query. The matching rows from the database are shown in the DB Output view
(Figure 6-38).

Figure 6-38 SQL Query Builder: testing the SQL statement

Later on we will look at how you can use Application Developer to generate Web
pages and Java classes to quickly and easily build an application based on an
SQL statement that uses host variables.

We will use this SQL statement in “Accessing databases from a Web application”
on page 248.

Accessing databases from a Java application


We have already seen an example of how to access a relational database using
JDBC from a Java application. In Chapter 5, “Developing Java applications” on
page 93 we created a simple application (CustomerListing, Figure 5-10 on
page 102) that accesses a DB2 table to return a list of customers. We now take a
closer look at database access.

Access using the DriverManager


We use the driver manager class to manage the connection to the database.
First we have to establish a connection to the database as shown in Figure 6-39.
򐂰 The first thing that has to be done is to load the JDBC driver. The
Class.forName() call does this. The driver name is dependent on which
database you are connecting to.

Note: You do not have to create an instance of the driver or register it. This is
done automatically for you by the DriverManager class.

174 WebSphere Studio Application Developer Version 5 Programming Guide


protected static Connection connect() {
Connection con = null;
try {
Class.forName("COM.ibm.db2.jdbc.app.DB2Driver");
con = DriverManager.getConnection("jdbc:db2:EJBBANK");
} catch(Exception e) {...}
return con;
}

Figure 6-39 Establish a connection to the database

򐂰 After loading the driver, you have to establish a connection. The class that
handles this is called DriverManager.
The URL string that is passed in to the getConnection method is again
dependent on which database system you are using. In the example above,
we are connecting to a DB2 database called EJBBANK. In this example we are
not passing a user ID and password, but if that was required, they would be
the second and third parameters of the getConnection call.

DB2 JDBC drivers


DB2 supplies two JDBC drivers:
򐂰 COM.ibm.db2.jdbc.app.DB2Driver—This is a JDBC type 2 driver that uses
a DB2 client installed on the machine where the application runs. You would
use this driver when accessing a local database or a remote database
through a local DB2 client. The database URL has the format:
jdbc:db2:databasename
򐂰 COM.ibm.db2.jdbc.net.DB2Driver—This is a JDBC type 3 driver. It is a Java
driver that is designed to enable Java applets access to DB2 data sources.
Using this driver your application will talk to another machine where the DB2
client is installed. The database URL has the format:
jdbc:db2://hostname:port/databasename
The standard port of the DB2 JDBC Applet Server service is 6789. This DB2
service must be started in your machine.
To connect to a database you have to supply user ID and password:
con = DriverManager.getConnection("jdbc:db2://localhost:6789/EJBBANK",
"db2admin","db2admin");

In our examples we use the DB2 app driver because we are talking to a local
database. If you are trying to connect to another database system, you should
consult the documentation to determine what driver name and URL to use.

Chapter 6. Developing database applications 175


The classes required when connecting to a DB2 database from Java are found in
.\sqllib\java\db2java.zip. You would make this available in Application
Developer by creating a classpath variable for it and adding that to the project
build path, as explained in “Running your programs” on page 103.

Executing SQL statements


You are now ready to perform operations on the database. How to execute a
simple select statement is shown in Figure 6-40.

stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM ITSO.CUSTOMER");

Figure 6-40 Executing a simple select statement

You create a statement using the connection obtained from the DriverManager
and then you execute the query passing the select statement. The result set from
the query is returned in a ResultSet variable.

Next, you have to process the result set from the query. The ResultSet class
provides a number of get methods for various data types as shown in
Figure 6-41.

while (rs.next()) {
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String userID = rs.getString("userID");
System.out.println(firstName + " " + lastName + " " + userID);
}

Figure 6-41 Processing the result set from the query

Finally, JDBC objects must be closed to release the resources (Figure 6-42). The
best place is a finally clause that is executed even in case of exceptions.

} finally {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (con != null) con.close();
} catch (SQLException e) {}
}

Figure 6-42 Releasing JDBC resources

176 WebSphere Studio Application Developer Version 5 Programming Guide


Access using a data source
JDBC access using a data source is not well suited for stand-alone applications.
It is, however, the preferred way to access databases from Web applications
where multiple clients use the same servlet for database access.

Figure 6-43 shows the basic code sequence to get a connection through a data
source.

try {
javax.naming.InitialContext ctx = new javax.naming.InitialContext();
javax.sql.DataSource ds = (javax.sql.DataSource)
ctx.lookup("jdbc/ejbbank");
con = ds.getConnection();
} catch (javax.naming.NamingException e) {
System.err.println("Naming-Exception: " + e.getMessage());
} catch (java.sql.SQLException e) {
System.err.println("SQL-Exception: " + e.getMessage());
}

Figure 6-43 Getting a connection through a data source

The data source is retrieved using a the lookup method of the InitialContext.
The data source must be registered in the JNDI server. In our example we use a
JNDI name of jdbc/ejbbank, which points to the EJBBANK database.

Once a connection is obtained, the rest of the code is the same.

Retrieving the data source is expensive. Good coding practice for Web
applications is to retrieve the data source only once in the init method of a
servlet, and to get and release a connection in the doGet or doPost method for
each client request.

We explore database access in Web applications in Chapter 8, “Developing Web


applications with database access” on page 247.

J2EE client application


In “Building an application client module” on page 614 we implement a modified
version of the CustomerList program. The CustomerListDS program uses a data
source and runs as a J2EE client application accessing the EJBBANK database,
which is defined in a WebSphere server through a data source.

Chapter 6. Developing database applications 177


Summary
We have introduced you to JDBC and data sources, and have seen how to create
and connect to databases using Application Developer.

In particular we covered the Data perspective and the generation of SQL


statements.

178 WebSphere Studio Application Developer Version 5 Programming Guide


7

Chapter 7. Developing Web


applications
In this chapter we develop a Web application as part of an enterprise application.
We develop static and dynamic content in the form of an HTML page, a servlet,
and a JSP.

We use the Page Designer, CSS Designer, and wizards to create servlets and
JSPs. To experiment with the new J2EE 1.3 functions, we develop both a sample
filter and a listener.

Finally, we use the wizard to create a simple Web application from a JavaBean.

© Copyright IBM Corp. 2003. All rights reserved. 179


Introduction
This chapter guides you through the Application Developer’s features designed to
assist you in the creation of Web applications.

We will start off by introducing you to the sample application that will be used
throughout this chapter, and in later chapters as well. We will then proceed to
create a new Web project to hold our example application. Once the project is in
place, we are able to add both static and dynamic content to it, and to use tools
and wizards, such as Page Designer, CSS Designer, and creating Web pages
from a JavaBean.

Even though this chapter does not assume that you are always in the Web
perspective of Application Developer, you may find it easier to perform the tasks
described here using the Web perspective.

Sample application: RedBank


In this section we describe the architecture for our sample banking application:
RedBank.

Note that the intent of this chapter is to introduce you to the Application
Developer’s tools that make the development of Web applications possible.
Together we will work only on a single HTML page, a single servlet, and a single
JSP page. The rest of the application has already been developed and is made
available to you so that you can explore it if you would like to.

The RedBank application was designed using the MVC architecture pattern,
which we will cover in more detail in Chapter 10, “Developing Struts applications”
on page 293.

Because the same example is used throughout the book, you will have the
opportunity to see how little it changes in the face of varying design constraints
and evolving techniques. This is in fact the most important characteristic of the
MVC pattern.

We are now going to introduce you to how the application implements each of the
MVC layers, so that you feel more comfortable with its design.

Model
The RedBank application’s business model (Figure 7-1) is described in “Banking
model” on page 111, and the code is imported into the ItsoProGuideJava project.

180 WebSphere Studio Application Developer Version 5 Programming Guide


Banking Bank Customer

Account TransRecord

Figure 7-1 Banking model revisited

Controller
The control layer was implemented using two different strategies: one
straightforward; and the other a little bit more complex, but more realistic. We did
so to keep the discussion in the book simple, but still have a nice example.

The application has a total of four servlets:


򐂰 ListAccounts—get the list of accounts for one customer.
򐂰 AccountDetails—display the account balance and the selection of
operations: list transactions, deposit, withdraw, and transfer.
򐂰 InvalidateSession—invalidate the session data.
򐂰 PerformTransaction—perform the selected operation by calling the
appropriate control action: ListTransactions, Deposit, Withdraw, or
Transfer.

Three of the servlets, including the ListAccounts servlet that you will implement,
fall into the first category. They work as sole controllers, without any external
collaboration. It is easier to implement and understand them this way.

The last of the four servlets, PerformTransaction, falls into the second category.
It acts as a front controller, simply receiving the HTTP request and passing it to
the appropriate control action object. These objects are responsible for carrying
out the control of the application. For a more thorough explanation of this
strategy, and the motivation behind it, please read Chapter 10, “Developing
Struts applications” on page 293.

Note: Action objects, or commands, are part of the command design pattern.
For more information, refer to Design Patterns: Elements of Reusable
Object-Oriented Software.

Chapter 7. Developing Web applications 181


View
The RedBank application’s view layer is comprised of an HTML file and four JSP
files. The application home page is the index.html file (Figure 7-2).

Figure 7-2 RedBank home page (index.html)

The home page allows you to type the customer ID to access the customer
services. There is no dynamic content in this page, so we use plain HTML. Note
that security issues (logon and password) are not covered in this book.

The second Web page (Figure 7-3) displays the customer’s accounts for
selection.

Figure 7-3 RedBank account listing (listAccounts.jsp)

The customer’s name and the available accounts are processed dynamically, as
they depend on the given customer ID, so we implemented this page as a JSP.

182 WebSphere Studio Application Developer Version 5 Programming Guide


After selecting an account, the user can view the logged transactions or perform
banking transactions, such as deposit, withdraw, and transfer (Figure 7-4).

Figure 7-4 RedBank account maintenance (accountDetails.jsp)

The maintenance screen also shows the current account number and balance,
both dynamic values. A simple JavaScript code controls whether the amount and
destination account fields are available or not, depending on the option selected.

If the user chooses to list the logged transactions, the Web page shown in
Figure 7-5 is displayed.

Figure 7-5 RedBank transaction log (listTransactions.jsp)

Chapter 7. Developing Web applications 183


This is a mostly dynamic page. The user may check the transaction number,
date, type, and amount. The color of the table rows alternate for readability
reasons.

Finally, if anything goes wrong in the regular flow of events, the exception page is
shown to inform the user (Figure 7-6).

Figure 7-6 RedBank exception page (showException.jsp)

The only dynamic content in this page is the message displayed to the user. In
the example shown in Figure 7-6, we entered an invalid customer ID.

Facade
We will use a copy of the facade in the Web application. It is better to have the
facade in the Web application to be able to access a different model that is
implemented in another project (for example as EJBs).

Application flow
The flow of the application is shown in Figure 7-7:
򐂰 The view layer is comprised of one HTML file (index.html) and four JSPs.
You will implement the index.html and the listAccounts.jsp.
򐂰 The control layer is comprised of four servlets and four action classes. The
PerformTransaction servlet passes control to one of the action classes.
You will implement the ListAccounts servlet.
򐂰 The model layer is comprised of the facade and four model classes. All
interactions from the servlets and actions classes go through the facade, the
Banking class.
The model is available in the ItsoProGuideJava project, which will be a utility
project in the enterprise application.

184 WebSphere Studio Application Developer Version 5 Programming Guide


index listAccounts accountDetails listTransactions VIEW

showException

ListAccounts AccountDetails PerformTransation CONTROL

Invalidate
Session ListTransactions Deposit Withdraw Transfer

Facade Banking

MODEL
Bank - Customer - Account - TransRecord

Figure 7-7 Banking application flow

Creating a Web project


In Application Developer, you create and maintain Web resources in Web
projects. They provide a development environment that enables you to perform
activities such as link-checking, building, testing, and publishing. Within a Web
project, Web resources can be treated as a portable, cohesive unit.

Web projects can be static or dynamic. Static Web projects are comprised solely
of static resources, which can be served by a traditional HTTP server (HTML
files, images, and so forth), and are useful for when you do not have to program
any business logic. J2EE Web projects, on the other hand, may deliver dynamic
content as well, which gives them the ability to define Web applications.

A Web application contains components that work together to realize some


business requirements. It might be self-contained, or access external data and
functions, as it is usually the case. It is comprised of one or more related servlets,
JavaServer Pages, and regular static content, and managed as a unit.
Throughout this chapter, we will create both static and dynamic content. Thus,
we need a J2EE Web project to support our tasks.

Chapter 7. Developing Web applications 185


Project name and features
To create a new Web project, select File -> New -> Web Project. The dialog in
Figure 7-8 is displayed.

Figure 7-8 Create a Web project wizard: name and features

Most of the time you will just have to set the project’s name and type. In our case,
we are creating a new J2EE Web project named ItsoProGuideBasicWeb.
Advanced users may also want to change the other options on the window:
򐂰 Use default—Deselect the check box to change the project file location.
򐂰 Web project features—Select one or more of the various options to add
additional features to your Web project. When you select a feature, a detailed
description is provided for you. For now, we will just use a default CSS file.
Later on you will be introduced to more advanced features.

186 WebSphere Studio Application Developer Version 5 Programming Guide


Enterprise application features
Click Next to move to the wizard’s second page (Figure 7-9).

Figure 7-9 Create a Web project wizard: enterprise application

J2EE Web modules, such as the project we are creating, run exclusively within
enterprise applications. For this reason, you have to either select an existing
enterprise application project, or let the wizard create a new one for you.

Type ItsoProGuide in the New project name field. Optionally you can set the
advanced options on this page, which are:
򐂰 Context root—The context root defines the Web application. The context root
is the root part of the URI under which all the application resources are going
to be placed, and by which they will be later referenced. It is also the top level
directory for your Web application when it is deployed to an application server.
Context roots are case-sensitive, so are all the Java URLs. Many developers
like to make their context root all lowercase in order to facilitate the manual
entering of URLs. The context root you select must be unique among all Web
modules within the same application server cell. Application Developer’s
default is to use the project’s name as the context root.
򐂰 J2EE level—You usually want to select the greatest J2EE level that your
target application server allows. For WebSphere Application Server Version 5,

Chapter 7. Developing Web applications 187


that would be J2EE 1.3. Selecting any of the two allowed levels will show you
details on the supported APIs.

Click Finish and the enterprise application and the Web project are created.

Adding the banking model as a utility JAR


The Web application requires the banking model that is in the ItsoProGuideJava
project. To add the ItsoProGuideJava project as a utility JAR file:
򐂰 Expand the ItsoProGuide enterprise application project and open the EAR
Deployment Descriptor (double-click).
򐂰 On the Module page (Figure 7-10), click Add under Project Utility JARs.
򐂰 Select the ItsoProGuideJava project and click Finish. The utility JAR file is
added.
򐂰 Save the deployment descriptor and close the editor.

Figure 7-10 Adding a utility JAR to an enterprise application

188 WebSphere Studio Application Developer Version 5 Programming Guide


Module dependencies
To make the utility JAR available to the Web application we have to specify a
module dependency:
򐂰 Open the Web project properties (select the ItsoProGuideBasicWeb project
and Properties from the context menu).
򐂰 Select the Java JAR Dependencies page and then select the
ItsoProGuideJava.jar file (Figure 7-11).
򐂰 Click OK.

Figure 7-11 Project properties: Java JAR dependencies

Project properties
The project properties dialog can be used at any time to change dependencies or
to change the context root, J2EE level, and other features.

For example, to change the context root, open the properties and select the Web
page (Figure 7-12).

Chapter 7. Developing Web applications 189


Figure 7-12 Project properties: context root

Web project directory structure


The Web project uses the directory structure shown in Figure 7-13.

Figure 7-13 Web Project in the J2EE navigator

190 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Java Source—This folder contains the project’s Java source code for regular
classes, JavaBeans, and servlets. When resources are added to a Web
project, they are automatically compiled and the generated files are added to
the Web Content\WEB-INF\classes folder. By default, the contents of the
source directory are not packaged in exported WAR files. If you want them to
be, you have to select the appropriate option when exporting the WAR file.
򐂰 Web Content—This folder holds the contents of the WAR file that will be
deployed to the server. It contains all the Web resources, including compiled
Java classes and servlets, HTML files, JSPs, and graphics needed for the
application.

Important: Any files not under Web Content are considered design time
resources (for example .java and .sql files) and will not be deployed when
the project is published. Make sure that you place everything that should
be published under the Web Content folder.

– Web Content\META-INF
This folder holds the MANIFEST.MF file, which describes the Web module’s
external dependencies.
– Web Content\theme
Contains cascading style sheets and other style-related objects.
– Web Content\WEB-INF
This directory holds the supporting Web resources for the Web module,
including the Web deployment descriptor (web.xml), IBM WebSphere
extensions’ descriptors (ibm-web-bnd.xmi and ibm-web-ext.xmi), and the
classes and lib directories.
– Web Content\WEB-INF\classes
Contains the project’s Java compiled code for regular classes, JavaBeans,
and servlets. These are the Java classes that will be published to the
application server and loaded in run-time. The class files are automatically
placed in this directory when the source files from the Java Source
directory are compiled. Any files placed manually in this directory will be
deleted by the Java compiler when it runs.
– Web Content\WEB-INF\lib
Contains utility JAR files that your Web module references. Any classes
contained in these JAR files will be available to your Web module.

Chapter 7. Developing Web applications 191


Importing existing resources
In most cases you do not have to start a Web project from scratch; rather you
import existing external resources into your Workspace.

Application Developer lets you import resources from a wide selection of


sources, such as:
򐂰 EAR, WAR, JAR, ZIP, and RAR files
򐂰 Existing projects in the workspace
򐂰 Existing WebSphere Studio V4 ClearCase projects
򐂰 Folder and files from the file system
򐂰 FTP and HTTP sites

As mentioned earlier, you will only develop a small part of our sample application.
The rest of the resources have been made available for you and have to be
imported now.
򐂰 Select File -> Import to open the import wizard. Select WAR file and click Next
to proceed to the second page (Figure 7-14).

Figure 7-14 Importing resources from a WAR file

192 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Select the WAR file by clicking Browse and navigating to
\sg246957\sampcode\dev-web\initial\ItsoProGuideBasicWeb.war.
򐂰 Because we have already created our Web project, select Existing and click
Browse. A small dialog pops-up and lets you select the
ItsoProGuideBasicWeb project. Click OK to continue.

Note: As you can see, you could have created the enterprise application
project, the Web project, and imported the resources in just one step using
this wizard.

򐂰 The Context Root and Enterprise application project fields are automatically
filled in for you. Select Overwrite existing resources without warning and click
Finish to import the resources.

What did we import? We imported the facade (itso.bank.facade.Banking,


which is a copy of the BankingTest class used in “Banking model” on
page 111, the control layer (itso.basicweb.control), three JSPs, an image,
and a CSS style sheet. We will develop the missing pieces of the application.

Creating static Web resources


Now that you have imported the initial set of resources for our sample
application, it is time that you learn how to develop your own. We will start by
creating a static web resource: an HTML page.

Page Designer
Page Designer is the main Application Developer tool used by Web designers to
create HTML pages. It is a WYSIWYG editor that generates the underlying
HTML code and frees the Web designer to concentrate on the visual aspect of
the page rather than on the details of HTML syntax. Page Designer currently
supports the HTML 4.01 specification.

The Page Designer shows three views of an HTML page: design, source, and
preview.
򐂰 In the Design view the work is done visually.
򐂰 In the Source view you manually edit the HTML code. You can use the content
assist feature, the same as for editing Java files. Pressing Ctrl-Space will
bring up a pick list of context-appropriate selections to choose from.
򐂰 The Preview view shows what the page will look like to the user, and thus is
read-only.

Chapter 7. Developing Web applications 193


Changes in the Design and Source views will automatically update each other,
as well as the preview view. You can also preview your page using an external
Web browser by selecting Tools -> Launch External Web Browser -> Default Web
Browser.

Syntax validation
When you save an HTML page, it will not be automatically validated for syntax
compliance by default. To manually validate the syntax of an HTML page, select
Tools -> Validate HTML Syntax .

Alternatively, you can choose to have Application Developer automatically do this


for you, a setting that can be platform-wide (Window -> Preferences ->
Validation) or project-wide (Properties -> Validation, on the Web project's context
menu).

To demonstrate the basic capabilities of Page Designer, we will walk you through
the building of a simple HTML page. In the next section, we discuss in more
detail how to use servlets and JSPs to provide dynamic content on our
application.

Create a simple HTML page


To add a new HTML page to a Web project, select the Web Content folder in your
Web project and New -> HTML/XHTML File from its context menu. This displays
the dialog shown in Figure 7-15, through which you give the page a name and a
location.

Figure 7-15 Create a new HTML/XHTML file wizard (page 1)

194 WebSphere Studio Application Developer Version 5 Programming Guide


Because we had the Web Content folder selected, the wizard automatically fills in
the folder field. You can change it by typing in a new value, or clicking Browse.

The other important information that you have to provide on this page is the file
name, in this case index. You may or may not type the file’s extension. If you do
not, the .html extension is added for you by the wizard.

The other field lets you specify the document’s markup language. In our case, it
should just be the default value of HTML, but other options would be HTML
Frameset, XHTML, or XHTML Frameset.

The Extensible HyperText Markup Language (XHTML) is a class of languages


and modules that reproduce the HTML language in valid XML syntax. It is useful
when you need to process HTML with XML-based user agents, which require
syntactically accurate documents.

Finally, there is the model field, but it is not used in the creation of HTML files.
Click Next to advance to the next page on the wizard (Figure 7-16).

Figure 7-16 Create a new HTML/XHTML file wizard (page 2)

Chapter 7. Developing Web applications 195


The wizard’s second page allows you to change the document’s character
encoding, which defaults to the Workbench’s default setting.

It also permits that you change the content and document types. Your options
depend very much on the markup language that you chose on the previous page.
If you chose HTML, for instance, then the content type is limited to text/html and
the document type should be one of the following:
򐂰 HTML 4.01 Strict—This is a downsized version of HTML 4.01. It allows for the
writing of more portable documents, because it emphasizes structure over
presentation. Deprecated elements and attributes, frames, and link targets
are not allowed in HTML 4.01 Strict. This document type depends very much
on style sheets for presentation.
򐂰 HTML 4.01 Transitional—Includes all elements and attributes of HTML 4.01
strict, plus presentational attributes, deprecated elements, and link targets. It
is a more common document type because it shows nice in browsers that
have limited or no support for style sheets.
򐂰 HTML 4.0 Frameset—This is a variant of HTML 4.01 Transitional, used for
documents that contain frames.

Finally, you can associate style sheets with the new document. By default, the file
Master.css is assigned, but you can add and remove files as you see fit. Click
Finish to complete the wizard.

Using the Page Designer


The Page Designer is opened on the new HTML page and you can now start
adding your page elements. In this example we will add the following elements:
the page title, meta tags to prevent Web clients from caching the page, a table,
an image, a static text, a form, a text field, and a submit button. Make sure you
are in the Design view to perform the tasks described below.

Start by deleting the default text paragraph that the wizard generated. To do that,
simply select the whole paragraph (or click Ctrl-A) and then click the Delete
button.

We will now set the page title and add the meta tags that will tell the Web client
not to cache the page. Most of the times static pages can and should be cached
to improve on performance. However, our static page is referenced not only
directly (by its file name) but also by a servlet (InvalidateSession). We do not
want the Web client to use the cached page when the servlet is called. We
instead want the servlet to receive the request again.

Select Page Properties on the document’s context menu. The dialog in


Figure 7-17 is displayed.

196 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-17 HTML page properties

򐂰 Type the page title (RedBank) on the Page Information tab.


򐂰 Switch to the Meta Info tab and enter the last six attributes shown in
Figure 7-17 (the first three should be there already). Click Add for each new
line, select NAME or HTTP-EQUIV from the drop-down menu, and enter the
item and content values.
򐂰 Click OK to close the dialog. If you switch over to the source tab you will
notice that the HTML code has been updated. The following content has been
added to the head of the document:
<TITLE>RedBank</TITLE>
<META name="Cache-Control" content="no-cache">
<META name="Pragma" content="no-cache">
<META name="Expires" content="-1">
<META content="no-cache" http-equiv="Cache-Control">
<META content="no-cache" http-equiv="Pragma">
<META content="-1" http-equiv="Expires">

Tip: You may alternatively copy and paste the text above directly to the HTML
source through the Source view.

Chapter 7. Developing Web applications 197


Our next step is to insert a simple table to hold our logo. Position the cursor on
the top of the page and then select Table -> Table. Our table will have just one
row and two columns, as shown on Figure 7-18. After setting the correct values,
click OK.

Figure 7-18 Insert a table dialog

The new table is inserted, and the first cell selected. Both cells should be of the
same size and very small, because they are still empty.

We do not want the table to have visible borders. Select the table (or any of its
cells) and Attributes (context) or select Window -> Show View -> Attributes. Set
the border attribute to 0 (Figure 7-19).

Figure 7-19 Table attributes

Now let’s fill the table with content. Select the left cell and type RedBank. We want
this text to be formatted as a heading 1. To accomplish this, select it and then
click Format -> Paragraph -> Heading 1. We also want the first three characters
(Red) to be in red. Select them and then click Format -> Font. Type red on the
color field and click OK.

198 WebSphere Studio Application Developer Version 5 Programming Guide


Alternatively, you can use the colors view to carry out the same task. With the
text still selected, select Window -> Show View -> Colors to display the colors
view. Select the color red from the palette (#FF0000). Finally, make sure the target
attribute is set to Text Color and then click the larger red box.

The second table cell should contain an image: itso.gif. It was imported along
with the rest of the resources and can be found in the Web Content\images folder.
Open the thumbnail view by selecting Window -> Show View -> Thumbnail and
then select the images folder in the J2EE Navigator view. You should now see the
thumbnail of the imported image, as shown in Figure 7-20. Simply drag and drop
it into the second table cell. Alternatively you can also expand the images folder
and drag/drop the itso.gif file into the second table cell.

Figure 7-20 Thumbnail view

Our next task is to place a second heading on the page, right after the table that
we have just created. Type the text Welcome to the ITSO Bank and format the
text as a heading 2.

After the heading comes a form, where the user can enter information that will be
sent back to the server. Click Insert -> Form and Input Fields -> Form. The form
should have a descriptive text that reads Please, enter your customer ID in the
field below:, a text field named customerNumber (Insert -> Form and Input Fields
-> Text Field) and a Submit button (Insert -> Form and Input Fields -> Submit
Button, set the label to Submit). The elements should be separated by a blank
line. The resulting form should look like Figure 7-21.

Figure 7-21 Example HTML form

Chapter 7. Developing Web applications 199


Finally, we will create an HTML link to another Web site. Insert the text For more
information on ITSO and RedBooks, please visit our Internet site at the very end
of the document. Highlight the text Internet site and select Insert -> Link. On the
URL field, enter http://www.redbooks.ibm.com.

The edited page in the Design view is shown in Figure 7-22.

Figure 7-22 Example HTML page

To save the page and validate your changes, select File -> Save index.html, or
alternatively press Ctrl-S. You may now close the editor window.

Using the CSS Designer


Cascading style sheets (CSS) allow authors and readers to attach multiple
presentation styles (such as fonts, colors, and spacing) to an HTML document.
By applying the same set of styles to all the presentation files of a Web
application, you can give it a much more homogeneous and coherent look, just
like a standard set of widgets would do to a GUI application.

Application Developer supports the following World Wide Web Consortium


(W3C) cascading style sheet standards:
򐂰 CSS1 (cascading style sheet level 1)
򐂰 CSS2 (cascading style sheet level 2)
򐂰 CSS Mobile Profile 1.0

In addition, the WAP Forum standard WCSS 1.0 (WAP CSS 1.0) is also
supported.

200 WebSphere Studio Application Developer Version 5 Programming Guide


As was mentioned earlier, you can have Application Developer create a default
CSS for you when you create a project. You can still create as many CSS files as
you like, but for now the default one will do. We just have to make some
modifications to it.

Application Developer provides a special editor to modify CSS files: the CSS
Designer. CSS Designer shows the source of a CSS file, and enables you to edit
styles with the help of syntax highlighting, content assist, and preview function.
The modifications made in CSS Designer are immediately applied to the design
page of Page Designer if the HTML file has a link to the CSS file.

To access the CSS Designer, double-click the existing style sheet in your Web
project (Web Content\theme\Master.css). This will bring up the style sheet editor,
comprised of source and preview panes, and the styles view (Figure 7-23).

Source Pane Preview Pane

Styles View

Figure 7-23 CSS Designer: style sheet editor

Chapter 7. Developing Web applications 201


If you are familiar with CSS file syntax, you can use the source pane to edit the
file directly. Just like when editing HTML files, you can use the content assist
feature to help you select values. If you press Ctrl-Space, a pick list of choices
appropriate to where the cursor is currently positioned will be displayed.

If you prefer, you can instead use the CSS Designer dialogs to edit or add styles
(accessible through the styles view, or through the style menu). These dialogs
are context sensitive and will open up on the style that is currently selected in the
editor.

Finally, the preview pane shows you how the styles will look like when applied to
an HTML file. By default, a sample HTML file is used, but you can choose to
preview the style changes with any file on your Web project.

For our example, we will change the appearance of two HTML elements: H1 and
H2. The first one will be edited directly through the source pane. Find the H1
style definition and manually change the color attribute to black. After edited, the
style source should look like the following:
H1
{
COLOR: black;
FONT-FAMILY: 'Times New Roman';
TEXT-TRANSFORM: capitalize
}

The second style will be changed via the editor's dialog. Double-click the H2 style
in the styles view to bring up the style properties dialog (Figure 7-24).

Figure 7-24 Style properties editor

202 WebSphere Studio Application Developer Version 5 Programming Guide


Change the following attributes: font color to white; background-color to #6098C8;
and padding in all directions to 2px. The items marked with an asterisk are the
items that have been changed. After the changes have been applied, the H2
style source should look as follows:
H2
{
COLOR: white;
FONT-FAMILY: 'Times New Roman';
TEXT-TRANSFORM: capitalize;
background-color: #6098C8;
padding: 2px;
}

Save your changes and close the style editor. Open up the index.html file and
verify its new look (Figure 7-25).

Figure 7-25 Example HTML page with CSS applied

Creating dynamic Web resources


There are many ways to create dynamic Web applications. The most
time-consuming method is to build the pages manually, by writing the code
line-by-line in a text editor. An easier and more productive way is to use the
Application Developer wizards in conjunction with content-specific editors, such
as the HTML and CSS editors, which we have already used.

The Web development wizards help you quickly create forms, HTML pages,
JavaServer Pages (JSPs), and Java servlets, even if you are not an expert
programmer. These files can be used as is, or modified to fit your specific needs.

Chapter 7. Developing Web applications 203


Application Developer wizards not only support you in creating servlets, JSPs,
and JavaBeans, but they also compile the Java code and store the class files in
the correct folders for publishing to your application servers. In addition, as the
wizards generate project resources, the deployment descriptor file, web.xml, is
updated with the appropriate configuration information for the servlets that are
created. You can test the resulting project resources within the Application
Developer using the WebSphere Test Environment, or any other configured
server that supports the chosen J2EE specification level.

Working with servlets


Servlets are flexible and scalable server-side Java components based on the
Sun Microsystems Java Servlet API, as defined in the Sun Microsystems Java
Servlet Specification. For J2EE 1.3, the supported API is Servlet 2.3.

Servlets generate dynamic content by responding to Web client requests. When


an HTTP request is received by the application server, the server determines
which servlet is responsible for answering that request (based on the requested
URI) and forwards the request to that servlet. The servlet then performs its logic
and builds the response HTML that is returned back to the Web client.

Application Developer provides the necessary features to make servlets easy to


develop and integrate into your Web application. Without leaving your
Workbench, you can develop, debug, and deploy them. You can set breakpoints
within servlets, and step through the code. You can make changes that are
dynamically folded into the running servlet on a running server, without having to
restart the server each time.

Adding a servlet to your Web project


Application Developer provides a servlet wizard to assist you in adding servlets
to your Web applications.

To start it, select File -> New -> Other. Select Web -> Servlet and click Next.
Alternatively, you can switch to the J2EE Navigator view, select the Java Source
folder in your Web project folder, and select New -> Servlet from its context
menu. The wizard starts with the dialog shown in Figure 7-26.

204 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-26 New servlet wizard (page 1)

The wizard’s first page will require you to fill out the following information:
Folder The source folder of your Web project. In our case, it is
\ItsoProGuideBasicWeb\Java Source.
Java package The package in which the servlet class will be created. For our
example, it should be itso.basicweb.control.
Class Name The servlet’s class name. We will implement the ListAccounts
servlet.
Superclass Usually, and this is true to our example, you will select the
javax.servlet.http.HttpServlet as your servlet’s superclass.
Application Developer requires you to select a class that
implements the javax.servlet.Servlet interface.

Chapter 7. Developing Web applications 205


Modifiers These are the usual Java class modifiers. We will go with
public. Servlets can also be abstract or final, but not both.
Options The only option that you have here is to have your servlet
implement the SingleThreadModel interface. This option should
only be selected for servlets that must have read/write state
accessed during their service methods. The need to implement
the SingleThreadModel interface probably indicates a poor
design.
Interfaces Which additional interfaces your servlet needs to implement.
Model No models are available for simple servlets.

Click Next to proceed to the wizard’s second page, shown in Figure 7-27.

Figure 7-27 New servlet wizard (page 2)

This page lets you select the appropriate method stubs to be created in the
servlet code. These are the servlet’s life-cycle methods, along with its service
methods specific to the HTTP protocol (the methods that start with “do”).

206 WebSphere Studio Application Developer Version 5 Programming Guide


For our example, we need both doGet and doPost selected. Both are read
methods. Usually, HTTP gets are used with direct links, when no information
needs to be sent to the server. HTTP posts are typically used when information in
a form has to be sent to the server.

Only one instance of a servlet is created in the application server. If you want to
perform any initialization when the servlet instance is created, select the init
method to be created. This method is invoked after the servlet instance has been
created and you can perform the initialization tasks.

Another check box lets you select whether or not you want to generate stubs for
the inherited abstract methods. You should select it if your servlet is concrete.

Because constructors are not inherited in Java, you may also want to generate
constructors that call their counterpart in the superclass.

Finally, the wizard lets you choose whether or not to add the new servlet to the
Web deployment descriptor. If you choose to do so, and we do for our sample
application, you can also define initialization parameters and their values, and the
URLs mapped to the servlet. We will stick to the default URL mapping suggested
by the wizard, which equals the servlet name.

You can now click Finish to complete the process. The servlet is generated and
added to the project. In the J2EE Hierarchy view you can see the servlet and its
mapping in the Web module. In the J2EE Navigator view you can see the servlet
file ListAccounts.java inside the itso.basicweb.control package. An editor is
opened, where you can view and edit the generated servlet source code.

Editing the servlet


Application Developer generates a skeleton servlet for you. Your task is now to
add code to the servlet in order to implement the required behavior for your
needs. The code is provided in:
\sg246957\sampcode\dev-web\servlet

Start by adding these import statements to the statements generated for you:
import javax.servlet.http.HttpSession;
import itso.bank.model.Customer;
import itso.bank.model.Account;
import itso.bank.facade.Banking;

Next, change the doGet and doPost methods’ body to look like this:
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
performTask(req, resp);
}

Chapter 7. Developing Web applications 207


public void doPost(HttpServletReq request, HttpServletResponse resp)
throws ServletException, IOException {
performTask(req, resp);
}

As you can see, both methods call a third method, called performTask. Because
both doGet and doPost are read methods, and the Java API for handling the
request parameters is the same no matter the request type, this works fine.

Finally, you need to code the performTask method (see Example 7-1).

Example 7-1 Servlet performTask method


public void performTask(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
// Parameters
// Get input parameter and keep it on the HTTP session
String customerNumber = req.getParameter("customerNumber");
HttpSession session = req.getSession();

if (customerNumber == null)
customerNumber =
(String) session.getAttribute("customerNumber");
else
session.setAttribute("customerNumber", customerNumber);

// Control logic - Create the new banking facade


Banking banking = new Banking();

// Retrieve customer and related accounts


Customer customer = banking.getCustomer(customerNumber);
Account[] accounts = banking.getAccounts(customerNumber);

// Response - Set the request attributes for future rendering


req.setAttribute("customer", customer);
req.setAttribute("accounts", accounts);

// Call the presentation renderer


getServletContext().getRequestDispatcher("listAccounts.jsp")
.forward(req, resp);
} catch (Exception e) {
req.setAttribute("message", e.getMessage());
req.setAttribute("forward", "index.html");
getServletContext().getRequestDispatcher("showException.jsp")
.forward(req, resp);
}
}

208 WebSphere Studio Application Developer Version 5 Programming Guide


The performTask method is divided into three main sections:
򐂰 The first section deals with the HTTP parameters. This servlet expects to
either receive a parameter called customerNumber (underlined) or none at all.
If the parameter is passed, we store it in the HTTP session for future use. If it
is not passed, we look for it in the HTTP session, because it might have been
stored there earlier. The parameter name equals the text field name in the
index.html page.
򐂰 The second section deals with the control logic. We create a new Banking
facade and use it to get the customer object and the array of accounts for that
customer.
򐂰 Finally, the third and last section sees that the presentation renderer
(listAccounts.jsp) gets the parameters it requires to perform its job
(customer and accounts, both underlined). The parameters are passed in the
request context, because they are no longer needed once this request is
answered.

We could have written the presentation code in the servlet if we wanted to do so.
Instead, we chose to use JSPs, which were specially designed for that purpose.
Servlets do not make very good Web presentation renderers, because writing
HTML code in Java is cumbersome.

Save your changes and close the source editor.

Linking an HTML page to a servlet


Before we write our JSP code, we complete the index.html file by linking it to the
ListAccounts servlet that we have just created. Open the index.html file and
switch to the Design view. Select the form element and open its properties view
by selecting Properties on the form’s context menu.

The form’s action should be the ListAccounts servlet. But you do not have to
type that in yourself. Instead, click ... -> Servlet and select the ListAccounts
servlet from the pop-up list. Remove the Web application context root:
From: /ItsoProGuideBasicWeb/ListAccounts <=== absolute URL
To: ListAccounts <=== relative URL

Finally, make sure that the Post method is selected. The Attributes view is shown
in Figure 7-28.

Chapter 7. Developing Web applications 209


select servlet

Figure 7-28 Form element attributes

You could have added the link to the servlet in the Source view as the action
attribute of the form:
<FORM action="ListAccounts" method="post">

Save the page and close the editor.

Links view
Select index.html file and the Links view. You should see the files (CSS file and
image) and links (servlet, URL) that are used by the HTML file (Figure 7-29).

servlet

Figure 7-29 Links view

Working with JSPs


Now that we have managed to build our first static page and our first servlet
controller, it is time to complete the cycle by writing our first JSP page:
listAccounts.jsp. This page is responsible for presenting the list of accounts
belonging to the given user.

210 WebSphere Studio Application Developer Version 5 Programming Guide


When an application server such as WebSphere Application Server processes a
request that involves a JSP file, it performs the following actions:
򐂰 Compiles the JSP file into executable Java code, if needed.
If a previously compiled JSP class file can be found, and the source file is
older than the compiled file, the application server does not have to recompile
the JSP file.
򐂰 Instantiates the JSP servlet, if needed.
Because JSPs are just like any other servlet, there will probably be just one
instance of each type in memory at the same time (unless they implement the
javax.servlet.SingleThreadModel interface). So, if the JSP has already
been processed in a previous request, chances are that resulting servlet
object is still in memory and can be reused.
򐂰 Sends the request to the JSP servlet for processing.
򐂰 The JSP servlet renders the HTML result which is sent back to the Web client
for output.

JSP files are edited in Page Designer, the very same editor you used to edit the
HTML page. When working with a JSP page, though, Page Designer has
additional elements (JSP tags) that can be used, such as JavaBean references,
expressions, and scriptlets containing Java code.

Creating a JSP
To create a JSP file, select the Web Content folder and select New -> JSP File
to open the new JSP file wizard (Figure 7-30).
򐂰 Because you had the Web Content folder selected when you started the
wizard, the folder field comes filled in for you. Type the file name
(listAccounts.jsp) into the appropriate field. You do not have to type the file
extension, as it will be automatically added for you.
򐂰 We will be using HTML as the markup language, so leave it as is. The options
are the same as when you created a new HTML page.
򐂰 If you select the Create as JSP Fragment check box, this file will be created
as a fragment that can be added to another JSP file. Other JSP files can
include JSP fragments using a JSP include directive. Creating a fragment
causes the resulting file to end in a .jspf or .jsf extension. You will not be
prompted for DOCTYPE information, because a fragment cannot stand alone
as a Web page, and it would invalidate any JSP file that included it.
򐂰 We want the wizard to generate code without using any special models, so let
the model field be set to none. Your other option would be to generate a
Struts JSP page, but that will be left for Chapter 10, “Developing Struts
applications” on page 293.

Chapter 7. Developing Web applications 211


Figure 7-30 New JSP file wizard (page 1)

Click Next to continue to the second page (Figure 7-31).

Figure 7-31 New JSP file wizard (page 2)

212 WebSphere Studio Application Developer Version 5 Programming Guide


The wizard’s second page lets you add tag libraries from a variety of sources. We
do not have any tag libraries on our example, but the steps to add a tag library
would be:
򐂰 Click Add Tag Library to locate a tag library directive (TLD) file or a JAR file
that contains a TLD file. TLD URIs can be located in one of the following
places:
– As a taglibname.tld file in the WEB-INF directory (most common).
– Within a JAR file located in the project lib directory that contains
\WEB-INF\taglibname.tld.
– Within a JAR file external to the project.
– In a loose .tld anywhere in the project.
򐂰 Taglib files are referenced in the Web deployment descriptor (web.xml) file on
the References page.
򐂰 In the Select a tag library dialog, either select one of the available tag
libraries, or click Import to locate and add a tag library to the list, and then
select it. The dialog will automatically populate the informational fields that
describe the tag library and its contents. You must specify a Prefix value. Click
OK to add the tag library.
򐂰 As you add tag libraries, the Available Custom Tags list box displays the
declaration of the tag along with the tag library directive. If the selected TLD
file is not registered in the web.xml file, it will be added automatically.

Note: We will work with tag libraries in Chapter 10, “Developing Struts
applications” on page 293.

We will skip working with tag libraries for now, so just click Next to proceed to the
third page (Figure 7-32).

Chapter 7. Developing Web applications 213


Figure 7-32 New JSP file wizard (page 3)

This page lets you supply page directive information for the JSP file:
򐂰 It allows you to choose the scripting language (Java is the preferred language,
but you can also choose Javascript if you would like), set the imported types
and packages, and configure the set of directive attributes.
If you do not select an attribute’s check box, it means that it will be assigned
the default value, which you can tell by checking the disabled radio group.
򐂰 First of all, add the packages java.util and itso.bank.model to the imports
list by clicking Import Package once for each package.
򐂰 Then, because we do not need a session variable in our JSP page, check the
Create Session Variable box and set its value to false.
Note that the default for a session variable in a JSP is true.

Click Next to continue to the next page (Figure 7-33).

214 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-33 New JSP file wizard (page 4)

The wizard’s fourth page lets you supply the JSP encoding, DOCTYPE, and style
sheet information, just like when we created our HTML page.

Leave the options to their default values and click Next to continue to the last
page (Figure 7-34).

Chapter 7. Developing Web applications 215


Figure 7-34 New JSP file wizard (page 5)

This last page lets you select which JSP method stubs you would like the wizard
to generate, and whether or not to add deployment information to the Web
project's deployment descriptor file.
򐂰 Because we do not need to add behavior to the life-cycle methods, leave both
init and destroy unchecked.
򐂰 Finally, if you select the Add to web.xml check box, the JSP file, along with its
display name, and any URL mappings and initialization parameters
associated with the JSP file, will be automatically included in the Web
project’s deployment descriptor file. We do not want to do that because our
JSP’s client is the ListAccounts servlet, and not an external Web client.

Note: The File Name value provided in the first page of the wizard is
automatically mapped to the Servlet Name value on this page, as well the
URL Pattern mappings. These mappings are not updated if you go back and
change the original value in the File Name field.

Click Finish to complete the wizard and create the file. The JSP file is added to
the Web Content folder and opened for editing.

216 WebSphere Studio Application Developer Version 5 Programming Guide


Note the additional JSP menu item that now can be found in Page Designer’s tool
bar. It helps you with many common tasks when editing JSPs, such as:
򐂰 Declaring and accessing JavaBeans and their properties
򐂰 Inserting declarations, expressions, and scriptlets
򐂰 Inserting forwards and includes
򐂰 Using plug-ins
򐂰 Working with custom tags

Editing a JSP file


In Application Developer you can create JSPs from scratch or use the JSP
wizards to generate code skeletons and then edit them to fit your particular
needs. For now, we do not use the more complex wizards, but you will be able to
experience them later in the book.

You can customize the recently created JSP file by adding your own static
content, just like you would to a regular HTML file. Along with that, you can use
the standard JSP declarations, scriptlets, expressions, and tags, or any other
custom tag that you might have retrieved from the Internet or developed yourself.

Switch to the Design view if you are not already at it. Clear the default text
paragraph that the wizard generated, just like you did with the HTML file. Then
set the page title to RedBank: Customer's Accounts.

Also, just like you did before, add the two column table to hold the bank’s logo.
The left column should contain the RedBank string (with the first three characters
in red). The logo image should be placed on the column to the right.

On a paragraph following the table, enter Someone's Accounts (including the


quote). This paragraph should be formatted as heading 2.

Insert an HTML form right after the heading 2. The form’s action should point to
the AccountDetails servlet, and should be an HTTP post. Configure these
attributes just like we did with the index page (“Linking an HTML page to a
servlet” on page 209).

The form should contain the following elements:


򐂰 A text string reading Please, select the account you would like to work with:,
followed by two line breaks.
򐂰 A list box named accountList (Insert -> Form and Input Fields -> List Box,
enter 3 the number of rows) followed by another two line breaks.
򐂰 A Submit button labeled Submit, followed by a white space.
򐂰 A general button labeled Cancel (Insert -> Form and Input Fields -> Reset
Button).

Chapter 7. Developing Web applications 217


Using JavaScript
When the Cancel button is pressed, we want the browser to send an HTTP get
request to the InvalidateSession servlet. To configure this behavior, we need to
write a little script in JavaScript. Select the button and switch to the Source view.
Your cursor should be now right in front of the input tag that defines the cancel
button:
<INPUT type="button" value="Cancel">

Change this tag so that it looks like this:


<INPUT type="button" value="Cancel" onclick="cancel()">

We are telling the browser to call the cancel function (to be defined in a moment)
when the button notifies the click event.

Find the </HEAD> tag and place your cursor right before. Insert a line break so
that the source will look nice, and manually enter the following script:
<SCRIPT language="JavaScript">
function cancel()
{
window.navigate("InvalidateSession");
}
</SCRIPT>
</HEAD>

As it is the case with source code in other languages, you can also use the code
assist feature to suggest options or complete your JavaScript code.

Inserting a link
Finally, we will create the HTML link to the Redbooks Web site. Switch back to
the Design view and type For more information on ITSO and RedBooks, please
visit our Internet site at the very end of the document. Just like you did before,
select the string Internet site and select Insert -> Link. On the URL field, enter
http://www.redbooks.ibm.com.

The resulting page’s Design view should be looking like Figure 7-35.

218 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-35 listAccounts.jsp file with just static contents

Up to this point we have just inserted static content into the JSP page, nothing
different from what you did when you edited the index.html file. Now it is time for
us to insert the dynamic elements into the page.

First, we need to declare the two JavaBean parameters that will be sent by the
controller servlet (ListAccounts), so that we can use them later on the page.
Their IDs are customer and accounts (see Example 7-1 on page 208).

While in the Design view, place you cursor before the table, or press Ctrl-Home.
Select JSP -> Insert Bean. The dialog in Figure 7-36 is displayed.

Figure 7-36 Insert JSP Bean wizard

Chapter 7. Developing Web applications 219


The ID field is the key which uniquely identifies the bean at the specified scope.
The pull-down menu contains recently used IDs. Because you have not used any
IDs so far, simply type customer.

The customer bean will be passed as a parameter to this page in the request
scope and not as a serialized bean from a file. Select Bean for the type and
Request for the scope.

We do not have to specify the bean’s class, because we do not want an object to
be created from scratch if it is not found in the specified scope. Leave the class
field blank and enter itso.bank.model.Customer in the type field. You can click
Browse to find the bean’s type instead of having to type it.

Click OK to complete the wizard. The following code is added to your JSP page,
right below the <BODY> tag:
<jsp:useBean id="customer" type="itso.bank.model.Customer"
scope="request">
</jsp:useBean>

Tip: An alternative way to add a JavaBean to a JSP page is to find it in the


J2EE Navigator view and drag and drop it on the page. The <jsp:usebean> tag
is inserted for you, but you have to add the id and scope attributes and change
the class attribute to type.

Repeat the above process for the accounts bean. The resulting JSP tag should
be:
<jsp:useBean id="accounts" type="itso.bank.model.Account[]"
scope="request"></jsp:useBean>

The <useBean> tag for an array results in a warning. To remove the warning we
can declare the accounts variable directly. Replace the <useBean> tag with this
code:
<% Account[] accounts = (Account[])request.getAttribute("accounts"); %>

Now that both beans have been declared, we can use them to display dynamic
data to the user. We want to substitute the Someone string for the customer’s
name.

Select the string in the heading 2 paragraph and simply delete it. With the cursor
positioned right before the apostrophe, select JSP -> Insert Get Property and the
dialog shown in Figure 7-37 appears.

220 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-37 Insert a JavaBean property

This dialog presents you with the list of all available beans to be used in the point
of insertion. Find the customer bean, expand it by clicking the plus sign, and
select the firstName property. The rest of the fields should automatically be filled
in for you. Click OK to close the dialog.

Now insert a blank space and repeat the above process for the customer’s last
name. The resulting JSP code added should look like this:
<H2><jsp:getProperty name="customer" property="firstName" />
<jsp:getProperty name="customer" property="lastName" />'s Accounts</H2>

Because this JSP displays a list of accounts for a customer (a customer may
have many accounts), it has to loop through the resulting collection of accounts.
To support this without using external taglibs, you have to insert a scriptlet with
Java code.

Note: Ideally, a JSP page would have no Java code at all, just JSP tags. The
intent of this scripting language is to enable Web designers that might not be
proficient in the Java language to write Web presentation to Java applications.
To a certain extent, this can be achieved without any further complications. So
far we have already used JSP tags but have written no Java code whatsoever.
In certain situations, though, as with loops, we cannot skip using Java
scriptlets unless we choose to use external taglibs, like the Java Standard Tag
Library (JSTL).

Chapter 7. Developing Web applications 221


Switch to the Source view and position your cursor within the <SELECT> tag body.
Select JSP -> Insert Scriptlet. Page Designer will insert the starting and ending
scriptlet tag for you. Enter the following code in the scriptlet body:
<SELECT size="3" name="accountList">
<%
for (int i=0; i < accounts.length; i++) {
Account account = accounts[i];
%>
</SELECT>

Note that the Java code has opened a loop block which but not closed it. We will
look into that in a short while. What we essentially did here was to get an iterator
for the accounts collection, previously declared, start a WHILE loop to iterate
through the account objects in that collection, and finally select the current
account object and assign it to the account variable.

We want this current account to show up as an option in the list box. After the
scriptlet but still within the select body, insert the following HTML tag:
<OPTION value="<%=account.getId()%>"><%=account.getId()%></OPTION>

Note that in the middle of the HTML code we put two identical JSP expressions.
These expressions will be substituted by the account ID at runtime, which is
essential what will be displayed to the user.

Finally, complete the loop by inserting another scriptlet with the loop’s closing
curly braces. The final code should look like this:
<SELECT size="2" name="accountList">
<%
for (int i=0; i < accounts.length; i++) {
Account account = accounts[i];
%>
<OPTION value="<%=account.getId()%>"><%=account.getId()%></OPTION>
<% } %>
</SELECT>

This completes the code for the JSP. You can test the visual aspects of it by
selecting the preview view Page Designer. Figure 7-38 shows the finished JSP
design and preview.

222 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-38 JSP design and preview

The JSP tags are shown as icon boxes. Double-click a JSP tag icon and view the
definition in the Attributes view, or view the content in the Source view.

You can see that the JSP tags are not displayed in the preview pane. Neither are
their results, of course. They can only be obtained by a J2EE application server,
at run time.

Make sure you are at either the design or the Source view and save your work.
Close the source editor.

Chapter 7. Developing Web applications 223


Creating a server for testing
To test a Web application we require a server. Because our project is a J2EE 1.3
project we require a WebSphere Version 5 server (or a Tomcat server).

A server can be created automatically or manually:


򐂰 For automatic server creation, select the ItsoProGuideBasicWeb project and
Run on Server (context). The dialog shown in Figure 7-39 is displayed.

Figure 7-39 Server selection dialog

The default selection is correct and clicking OK defines a server project


named Servers, a server named WebSphere v5.0 Test Environment, and
starts the server. The drawback of this method is that we cannot select a
name for the server and we cannot tailor the server before it starts.
Stop the server, delete it from the Server Configuration view and delete the
Servers project. We want to create a server manually.
򐂰 For manual creation of a server, open the Server perspective and select New
-> Server and Server Configuration. In the dialog (Figure 7-40) enter the
name of the server (for example, ItsoServer), set the folder as
ItsoProGuideServers (this creates the ItsoProGuideServers project), and
select WebSphere version 5.0 -> Test Environment.
Click Next and confirm that you want to create the ItsoProGuideServers
project.
Accept the default port of 9080 and click Finish.
Select the ItsoServer in the Server Configuration view and Add ->
ItsoProGuide (context). This adds the EAR project (with the Web module) to
the server.
The ItsoServer server also appears in the Servers view, from where it can be
started and stopped.

224 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-40 Creating a WebSphere test server

Testing the application


Start the ItsoServer server.

While the server is starting, you can check its initialization message log on the
Console view. If the view is not visible, select Window -> Show View -> Console
from the menu bar. You will know that the server is ready when you read the
message “Server server1 open for e-business“.

Select the ItsoProGuideBasicWeb project and Run on Server (context). When you
run a Web project itself, instead of a single HTML file, then the welcome page is
displayed. Welcome pages are defined in the deployment descriptor (web.xml) on
the Pages page. Usually the index.html file is the first in the list.

Chapter 7. Developing Web applications 225


If you are prompted to select a server, select the ItsoServer and also select Set
server as project default (do not prompt). This stores a server as the default in
the properties of the Web project., where it can be changed at any time.

The Web browser window opens and displays the index page (Figure 7-2 on
page 182). In the customer ID field, type any number from 101 to 106 and submit
the form. The resulting page (Figure 7-3 on page 182) should display the
selected customer’s account list.

Working with filters


Servlet filtering is a new addition to the Servlet 2.3 API. It provides a new type of
reusable object called a filter, that can transform requests and responses on the
fly. You can chain filters together so that a group of filters can act on the input and
output of a specified resource or group of resources.

Filters typically include logging filters, image conversion filters, encryption filters,
and MIME type filters. Although filters are not servlets, their life cycle is very
similar.

Filters are handled in the following manner:


򐂰 The Web container determines which filters must be constructed for the Web
application, before a request causes a Web resource to be accessed.
򐂰 The container instantiates and initializes each filter (if this was not previously
done) by calling the filter’s init method.
򐂰 When the container receives a request for a Web resource, it creates a filter
chain containing the filters associated with the resource.
򐂰 The container invokes the chain’s doFilter method, which in turn invokes
each filter’s doFilter method. A filter’s doFilter method typically:
– Pre-processes the request object, or wraps it with a customized
implementation of ServletRequest or HttpServletRequest to modify
request headers or data.
– Pre-processes the response object, or wraps it with a customized
implementation of ServletResponse or HttpServletResponse to modify
response headers or data.
– Typically invokes the next filter on the chain by calling the chain’s doFilter
method, but may alternatively block the chain. After this step, the filter may
examine the response’s headers.
– Does additional post-processing to the request and response objects.

226 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Finally, after all the filters on the chain have been invoked, the filter chain calls
the originally requested resource.
򐂰 Before a filter can be removed from service, the container must call its
destroy method.

Figure 7-41 shows how the chaining of filters work:

Web Container

Filter 1 Filter 2
doFilter doFilter Resource

doFilter Filter Chain

Figure 7-41 Filter chaining

Creating a filter in Application Developer


We implement a simple filter that audits all the banking transactions by writing an
audit trail to a file. This filter in invoked before the PerformTransaction servlet
gets control.

Note: This is a simple example that uses a file for auditing. Such a design
should not be used in a real application.

To create a new filter in Application Developer, open the J2EE Navigator view of
the ItsoProGuideBasicWeb project.

Create a new package (under Java Source) names itso.basicweb.filter.

Select the itso.basicweb.filter package and New -> Filter from the context
menu to start the New Filter wizard (Figure 7-42).

Chapter 7. Developing Web applications 227


Figure 7-42 Creating a new filter (page 1)

Make sure the correct package (itso.basicweb.filter) is selected.

In the Filter Name field, type TransactionAuditingFilter. Our filter will audit
every transaction that is performed with the bank accounts, logging the
transaction type, time stamp, and parameters, as well as the client’s hostname
and IP address.

Click Next to proceed to the second page (Figure 7-43).

The wizard’s second page lets you select method stubs and deployment
descriptor information.

228 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 7-43 Creating a new filter (page 2)

The filter has to be added to the Web deployment descriptor. Configure the
initialization parameter by clicking the respective Add. Enter pathname for the
parameter name and c:/transactionAudit.txt for its value.

Finally, we have to set with which servlets this filter should be associated. Click
the respective Add to open the Choose a Servlet dialog. Select
PerformTransaction and click OK.

Click Finish to complete the wizard. The TransactionAuditingFilter.java file is


opened for editing.

Note: To change the filter’s servlet associations or initialization parameters,


open the Web deployment descriptor on the Filters page.

Chapter 7. Developing Web applications 229


Editing the filter
Switch to the Java editor opened on the TransactionAuditingFilter.java file.
The source code of the sample filter is available in:
\sg246957\sampcode\dev-web\filter\TransactionAuditingFilter.java

Add an import statement and declare the following instance variable:


import java.io.RandomAccessFile;
private RandomAccessFile auditFile;

The auditFile property holds a reference to the audit file. Generate its getter
and setter methods by selecting the field in the Outline view and Generate Getter
and Setter from its context menu. Change the generated method access
modifiers from public to private (Figure 7-44):

private RandomAccessFile getAuditFile() {


return auditFile;
}

private void setAuditFile(RandomAccessFile auditFile) {


this.auditFile = auditFile;
}

Figure 7-44 Getter and setter methods for the auditFile property

The audit file should be opened upon the filter initialization. Edit the init method
as shown in Figure 7-45.

public void init(FilterConfig config) throws ServletException {


String pathname = config.getInitParameter("pathname");
try {
setAuditFile(new RandomAccessFile(pathname, "rw"));
getAuditFile().seek(getAuditFile().length());
} catch (IOException e) {
e.printStackTrace());
}
}

Figure 7-45 TransactionAuditingFilter init method

After opening the file for both read and write access, we move the file pointer to
the end, so that the file can be appended instead of overwritten.

Because we opened the file in the init method, we have to close it in the
destroy method (Figure 7-46).

230 WebSphere Studio Application Developer Version 5 Programming Guide


public void destroy() {
try {
getAuditFile().close();
} catch (IOException e) {
e.printStackTrace();
}
}

Figure 7-46 TransactionAuditingFilter destroy method

Finally, edit the filter’s doFilter method as shown in Figure 7-47.

public void doFilter(ServletRequest request, ServletResponse response,


FilterChain chain) throws ServletException, IOException {
String protocol = req.getProtocol();
String address = req.getRemoteAddr();
String host = req.getRemoteHost();
String transaction = req.getParameter("transaction");
String parameters = "";
java.util.Enumeration parameterNames = req.getParameterNames();
while (parameterNames.hasMoreElements()) {
String name = parameterNames.nextElement().toString();
String value = req.getParameter(name);
parameters += name + "=" + value + ", ";
}
parameters = parameters.substring(0, parameters.length() - 2);
String output = "- " + transaction +
" being performed from " + host + " (" + address +
") using " + protocol + " at " + new java.util.Date() +
" Parameters: " + parameters + "\r\n";

synchronized (getAuditFile()) {
getAuditFile().writeBytes(output);
}
System.out.println(output);

chain.doFilter(request, response);
}

Figure 7-47 TransactionAuditingFilter doFilter method

Save your changes and close the editor. The next time you perform a transaction
with any of the accounts, the audit file c:\transactionAudit.txt is created and
populated. See Figure 7-54 on page 236 for sample output of the filter (and the
listener that we create next).

Chapter 7. Developing Web applications 231


Working with listeners
Life-cycle listeners, now part of the Servlet API, enable you to be notified when
servlet contexts and HTTP sessions are created, destroyed or modified. They
give the application developer greater control over interactions with
ServletContext and HttpSession objects. Servlet context listeners manage
resources at an application level. Session listeners manage resources
associated with a particular client’s HTTP session.

Listeners are available for life-cycle events and for attribute modification events.
The listener developer creates a class that implements the interface
corresponding to the desired listener functionality:
򐂰 javax.servlet.ServletContextListener
Receives javax.servlet.ServletContextEvent events that notify that a
servlet context has just been created or is about to be destroyed.
򐂰 javax.servlet.ServletContextAttributeListener
Receives javax.servlet.ServletContextAttributeEvent events that notify
that an attribute in the servlet context has been added, removed, or modified.
򐂰 javax.servlet.http.HttpSessionListener
Receives javax.servlet.http.HttpSessionEvent events that notify that an
HTTP session object has just been created or is about to be destroyed.
򐂰 javax.servlet.http.HttpSessionAttributeListener
Receives javax.servlet.http.HttpSessionBindingEvent events that notify
that an attribute in an HTTP session has been added, removed, or modified.

Note that the same listener may implement any combination of the above
interfaces. At application startup time, the container uses introspection to create
an instance of the listener class and registers it with the appropriate event
generators.

As an example, we will create a listener that implements both the


HttpSessionListener and HttpSessionAttributeListener interfaces. It will be
called HttpSessionInspector and will print to the standard output detailed HTTP
session event notifications that can be used by the developer to determine:
򐂰 When HTTP sessions are created and destroyed.
򐂰 The size of the HTTP session objects at creation and destruction.
򐂰 When HTTP session attributes are added, removed or modified, and their
sizes.

232 WebSphere Studio Application Developer Version 5 Programming Guide


Creating a listener in Application Developer
To create a listener in Application Developer, open the J2EE Navigator view of
the ItsoProGuideBasicWeb project.

Create a new package (under Java Source) names itso.basicweb.listener.

Select the itso.basicweb.listener package under the Java Source folder and
then select New -> Life-cycle Listener from the context menu to start the New
Life-cycle Listener wizard (Figure 7-48):

Figure 7-48 Creating a new life-cycle listener (page 1)

Make sure the correct package (itso.basicweb.listener) is selected.

In the Listener Name field, type HttpSessionInspector. In the Listener Types


field, select both Http Session Listener and Http Session Attribute Listener. Click
Next to continue to the second page (Figure 7-49):

Chapter 7. Developing Web applications 233


Figure 7-49 Creating a new life-cycle listener (page 2)

All the default values are suitable, just click Finish to complete the wizard. The
listener is created and added to the Web deployment descriptor. A Java editor is
also opened on the listener class Java file.

Editing the listener


Switch to the Java editor that was opened on the HttpSessionInspector.java
file. The source code of the sample listener is available in:
\sg246957\sampcode\dev-web\listener\HttpSessionInspector.java

The first method we will enter calculates an object’s size when serialized. This
method is useful for determining how much space a session or one of its
attributes would take if they would be serialized to a database. Add the size
method as shown in Figure 7-50.

234 WebSphere Studio Application Developer Version 5 Programming Guide


private int size (Object anObject) {
ByteArrayOutputStream array = new ByteArrayOutputStream ();
try {
(new ObjectOutputStream (array)).writeObject(anObject);
return array.size();
} catch (IOException e) {
return -1;
}
}

Figure 7-50 Listener helper method: size

The next helper method that has to be created is called report. It handles the
printing of messages to the standard output (Figure 7-51).

private void report (String reason, HttpSession session, Object value,) {


if (value == null)
System.out.println (reason + ": session #" + session.hashCode() + "
size: " + size(session));
else
System.out.println (reason + ": session #" + session.hashCode() + "
size: " + size(session) + " Attribute size: " + size(value));
}

Figure 7-51 Listener helper method: report

Now enter the life-cycle methods for the HttpSessionListener interface


(Figure 7-52).

public void sessionCreated(HttpSessionEvent arg0) {


report ("Session created", arg0.getSession(), null);
}

public void sessionDestroyed(HttpSessionEvent arg0) {


report ("Session destroyed", arg0.getSession(), null);
}

Figure 7-52 Listener implementation for the HttpSessionListener interface

Finally, enter the methods for the HttpSessionAttributeListener interface


(Figure 7-53).

Chapter 7. Developing Web applications 235


public void attributeRemoved(HttpSessionBindingEvent arg0) {
report ("Attribute " + arg0.getName() + " removed",
arg0.getSession(), arg0.getValue());
}

public void attributeAdded(HttpSessionBindingEvent arg0) {


report ("Attribute " + arg0.getName() + " added",
arg0.getSession(), arg0.getValue());
}

public void attributeReplaced(HttpSessionBindingEvent arg0) {


report ("Attribute " + arg0.getName() + " replaced",
arg0.getSession(), arg0.getValue());
}

Figure 7-53 Listener implementation of the HttpSessionAttributeListener interface

To get rid of all the errors from undefined classes, select Source -> Organize
Imports and the required import statements are added to the code.

Save your changes and close the editor. Run the application to see the results of
your work. The listener’s messages should show up on the Console view.

Figure 7-54 contains an extract from the Console showing the output of both the
filter and the listener.

Session created: session #1152644455 size: 226


Attribute customerNumber added: session #1152644455 size: 249
Attribute size: 10
Attribute accountNumber added: session #1152644455 size: 276
Attribute size: 15
- Deposit being performed from 127.0.0.1 (127.0.0.1) using HTTP/1.1 at
Sun Apr 06 15:23:02 PDT 2003 Parameters: amount=100, transaction=Deposit
- Transfer being performed from 127.0.0.1 (127.0.0.1) using HTTP/1.1 at
Sun Apr 06 15:23:14 PDT 2003 Parameters: destinationAccount=106-6002,
amount=200, transaction=Transfer
Attribute accountNumber replaced: session #1152644455 size: 276
Attribute size: 15
- ListTransactions being performed from 127.0.0.1 (127.0.0.1) using
HTTP/1.1 at Sun Apr 06 15:23:24 PDT 2003 Parameters:
transaction=ListTransactions
Invalidating session
Session destroyed: session #1152644455 size: 276

Figure 7-54 Sample output of filter and listener

236 WebSphere Studio Application Developer Version 5 Programming Guide


Creating Web pages from a JavaBean
Application Developer provides support for generating a working set of pages
and Java classes from a simple JavaBean or a set of JavaBeans. A JavaBean, in
this context, is any Java class that has a public constructor and public getters and
setters for its properties.

Important: The Java classes you select must have zero-argument


constructors, as per the JavaBeans specification, or the resulting generated
code will fail to work correctly.

As we have seen before, JavaBeans usually either implement or represent the


business model tier. The JavaBean wizard will generate the view and control
layers to work with the JavaBeans you select, in accordance to the MVC
architectural pattern.

The JavaBean Web Pages Wizard supports the following activity models:
򐂰 Set bean properties—Create an input form that collects input from users and
stores the resulting data within the properties of a Java bean.
򐂰 Retrieve bean properties—Create a result form that displays a bean's current
property values.
򐂰 Execute a bean's method(s)—Run any number of methods from a bean by
submitting an input form.
򐂰 Execute a bean's method(s) with parameters—Create an input form that
collects data from users, and use this data as input to a bean's methods.
򐂰 Display a method's result—Create a result page that displays the return value
of a method.
򐂰 Combination—Create a set of pages that include any combination of the
above models.

For the sole purpose of demonstrating the wizard, we are going to redo the same
two pages and one servlet we did before (index.html, listAccounts.jsp and
ListAccounts). You will then be able to compare the two approaches.

We create the application in the ItsoProGuideBasicWeb project.

To better organize your code, create a new folder under Web Content named jbwp
(as in JavaBean Web pages).

Chapter 7. Developing Web applications 237


Select the newly created jbwp folder and select File -> New -> Other from the
menu bar. Select the Web -> Java Bean Web Pages option and click Next to
continue. This opens the wizard’s first page, as shown in Figure 7-55.

Figure 7-55 JavaBean Web pages wizard: start

򐂰 The Destination folder field should have come up already filled in, since you
had the folder selected. In the Java package field, type itso.jbwp. We do not
want the code mixed with the old application.
򐂰 The model selection drop-down currently only has one entry: View Bean. This
code generation model uses view helpers, which are Java wrapper classes
that manage all the model interaction.
򐂰 The rest of the dialog is simply informative. Selecting the Files field values
displays a description.

238 WebSphere Studio Application Developer Version 5 Programming Guide


Click Next to proceed to the next page (Figure 7-56).

Figure 7-56 JavaBean Web pages wizard: select bean and methods

򐂰 The second step consists of selecting the JavaBean that will act as the model
for the generated pages, and selecting which of its properties and methods
the pages should be created for.
򐂰 Click Browse to bring up the Choose Java Bean dialog. Type Banking in the
Choose Java Bean field. The dialog presents you with the matching types,
but the list is probably going to be limited to just one occurrence. Select the
appropriate type (Banking) and package (itso.bank.facade) and click OK.
򐂰 The wizard automatically introspects the bean and presents you with the list
of available properties and methods. You do not have to click Introspect
unless you type in the class name directly.
򐂰 Select the getCustomer and getAccounts methods. We only want to retrieve
the customer and its accounts.

Chapter 7. Developing Web applications 239


Click Next to continue to the next page (Figure 7-57).

Figure 7-57 JavaBean Web pages wizard: controller, view beans

򐂰 The third wizard’s page lets you select the style sheets you want associated
with the generated pages. By default, Web Content\theme\Master.css comes
selected, and that is enough for us. You may add, remove, or change the
priority of style sheets by clicking Add, Remove, and the arrow buttons,
respectively.
򐂰 Here you may also select whether or not the wizard should link the given error
page to the generated pages. Note that the wizard will not generate the error
page. It will just declare it in the generated pages’ page directive for you. We
do not need that behavior.
򐂰 The default setting for storing the results is Request, the option that you
should select for this example. Selecting Request means that the method
results will only be available for the duration of the HTTP request. If you want
the results to be preserved for the lifetime of the user session, choose the
Session option. If the results occupy too much memory, this may not be the
best approach.
򐂰 You can then choose how you would like the wizard to generate control layer
code for you. You may want to generate a new controller servlet, to reuse an
existing one, or not to use a controller servlet at all (in which case the wizard
would generate view and control code in the JSPs). Select the Create a new
Front Controller option.

240 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 While you are still on this page, you can choose to have the wizard create a
view bean wrapper for you. This wrapper class allows you to format the result
data for display. If you deselect this option, the wizard accesses data using
the previously chosen bean directly. For our simple example, we do not want
a wrapper.

Click Next to proceed to the fourth page (Figure 7-58).

Figure 7-58 JavaBean Web pages wizard: input page

This page lets you see and configure how the generated input HTML file will look
like:
򐂰 Select the getCustomer method and clear its Label property.
򐂰 Select the customerID item under the getCustomer method and configure its
label to Enter a customer number:
򐂰 Deselect the getAccounts method and customerID under it, we only want one
input field for the customer number.
򐂰 Select the Page tab and set the Page Title field to RedBank.

Chapter 7. Developing Web applications 241


Click Next to proceed to the fifth page (Figure 7-59).

Figure 7-59 JavaBean Web pages wizard: results page

Using this page you can determine and configure how the response JSP will
look:
򐂰 Use the arrows to move getAccounts under getCustomer (if the sequence is
reversed).
򐂰 Select the getCustomer method and clear its Label property.
򐂰 Select the getCustomer result (right under the getCustomer method) and set
its Label property to Customer:.
򐂰 Expand the getCustomer method and select both firstName and lastName
properties. Select each field and change the labels to First name: and Last
name:.
򐂰 Expand the getAccounts method, select it, and clear its label.
򐂰 Select the getAccounts under it and set its label to Accounts: and its layout
style to table (use the drop-down menu).

242 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 The getAccounts result is an array of Account objects. Expand the
getAccounts result.
򐂰 The properties of the Account class are now displayed under getAccounts.
Check the id and balance fields.
򐂰 Select the id and balance fields and change the labels to Account number and
Balance.
򐂰 Configure the page title to RedBank: Customer's Accounts.

Click Next to skip to the wizard’s last page (Figure 7-60).

Figure 7-60 JavaBean Web pages wizard (page 6)

Finally, you have to configure a prefix to be appended before every generated


resource. Simply type ListAccounts and click Finish to complete the wizard.

The following resources were generated:


򐂰 A ListAccountsInputForm.html file in the Web Content\jbwp folder.
򐂰 A ListAccountsResultsForm.jsp file in the Web Content\jbwp folder.
򐂰 A ListAccountsController servlet in the itso.jbwp package. This servlet has
also been registered in the Web module’s deployment descriptor.

Completing the code


Because we only generated one input field for the customer ID, the call to the
getAccounts method has no parameter. We have to add the parameter manually.

Open the ListAccountsResultsForm.jsp file and find the method calls. Change
the getAccounts call:
itso.bank.model.Customer methodResult0 = listAccountsBean.getCustomer
(new java.lang.String(request.getParameter

Chapter 7. Developing Web applications 243


("getCustomer_java_lang_String__customerID")));
itso.bank.model.Account[] methodResult1 = listAccountsBean.getAccounts
(new java.lang.String(request.getParameter
("getCustomer_java_lang_String__customerID")));

Tailoring the generated files


You could make the ListAccountsInputForm.html file look like the original
index.html file.

Rename
Note that if you rename the files, you have to configure the initialization
parameters of the controller servlet (ListAccountsController) in the web.xml
deployment descriptor.

Running the generated application


Select the ListAccountsInputForm.html file and Run on Server (context). The
application is published, the server is started, and the input page is displayed.

Enter a customer number (102) and click Submit. The name of the customer and
the accounts are displayed. A sample run is shown in Figure 7-61.

Figure 7-61 Sample JavaBean application run

244 WebSphere Studio Application Developer Version 5 Programming Guide


Summary
In this chapter we learned about Application Developer’s facilities for creating
static and dynamic Web applications. We created a Web project and imported
existing resources into it. We then created static HTML pages, a cascading style
sheet, servlets, JSPs, filters, and life-cycle listeners to complete the sample
RedBank application, based on the MVC architectural pattern.

We also used the JavaBean Web Pages Wizard to generate a Web application
from a JavaBean.

Chapter 7. Developing Web applications 245


246 WebSphere Studio Application Developer Version 5 Programming Guide
8

Chapter 8. Developing Web


applications with database
access
We have seen how to connect to databases and how to access them from a Java
application. Application Developer contains wizards to allow you to easily access
databases from a Web application. We now examine how to use those wizards,
and how to test the resulting application.

In this chapter, we go over the following topics:


򐂰 Accessing databases from a Web application
򐂰 Defining a data source in the server
򐂰 Testing the database application
򐂰 Accessing a database using DB Beans

© Copyright IBM Corp. 2003. All rights reserved. 247


Accessing databases from a Web application
There are a number of ways that you can access databases from a Web
application. You can write your own Java classes and access the database via
standard JDBC calls. Alternatively, Application Developer supplies a library of
database access beans called DB Beans. These can be used in a JSP through
the <useBean> tag and can also be accessed through a set of JSP tags supplied
in a tag library. An application using DB Beans or tags can be generated for you
by Application Developer using a wizard based on an SQL statement.

Which of these methods you choose depends on the nature of your application
and the complexity of your database access. From the perspective of separating
the layers of your application, using separate JavaBeans for the database access
may be more appropriate because you are not mixing presentation and database
logic in the JSP as you do when using DB Beans or JSP tags.

In the following sections we discuss the wizard that can be used to create a view
bean or a taglib application starting from an SQL statement. We then look a bit
more closely at the DB Beans classes and JSP tags.

Creating a Web project


In this section, we use a new ItsoProGuideDataBaseWeb project:
򐂰 Create a Web project named ItsoProGuideDataBaseWeb by following the
instructions in “Creating a Web project” on page 185.
򐂰 Use the existing ItsoProGuide enterprise application project and the default
context root.
򐂰 On the module dependencies page, select the ItsoProGuideJava.jar file and
click Finish.
򐂰 When prompted to repair the server configuration because a new project was
added to the EAR file, click OK (Figure 8-1).

Figure 8-1 Repair server configuration

248 WebSphere Studio Application Developer Version 5 Programming Guide


Generate Web pages from SQL queries
Application Developer provides a wizard to help you create a set of Web pages
and supporting Java classes starting from an existing or new SQL query. The
wizard generates the required HTML pages, JSPs, and Java classes to quickly
create a working skeleton application without you having to write any code. You
can then expand and modify the generated code to create the finished
application.

To start the wizard, click File -> New -> Other. In the New wizard, select Web in
the left pane and Database Web Pages in the right pane, then click Next.

The first page of the wizard is displayed (Figure 8-2).

Figure 8-2 Create Database Web Pages wizard: select model

The following fields are available on this page:


򐂰 Destination folder—Folder where the generated Web pages are stored.
򐂰 Java package—Package where Java classes are generated.
򐂰 SQL Statement Type—The type of action to perform on the database.

Chapter 8. Developing Web applications with database access 249


򐂰 Model—There are two types of models that you can use:
IBM Database Access Tag Library: Two choices of tag library models are
available: Select Statement and Master Details Pattern.
– The Select Statement generation model creates an input form and a result
table based on the given SQL query
– The Master Details Pattern produces a master results table as well as a
details page that displays more information on a selected row of the
master results table.
Both of these use JSP tag libraries to access the data. JSP tags are
discussed in more detail in “Accessing a database using JSP taglib” on
page 262.
IBM Database Access Java Beans - Master Details Pattern: This model
generates Web pages that access database information using IBM Data
Access Beans to separate the database interaction from the JSP page. For
this example we use this model.

Clicking Next brings up the second wizard page (Figure 8-3).

Figure 8-3 Create Database Web Pages wizard: select SQL statement

You have two choices: use an existing SQL statement, or build a new one:
򐂰 If you already have an existing SQL statement in the statement folder of a
database project, you can select it here and use that to generate the Web
pages.

250 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 If you deselect Use Existing SQL Statement and click Next, you are prompted
to build an SQL statement in the same way as described in “Creating SQL
statements” on page 165.

We select the ListCredits SQL statement that we built in “Using SQL Query
Builder” on page 171 and click Next.

Clicking Next displays the page where you decide how you want to access the
database when the generated application is run (Figure 8-4). You can choose to
use a direct connection or use a data source. For a discussion about these two
different ways of connecting, see “Data source versus direct connection” on
page 141.

Figure 8-4 Create Database Web Pages wizard: connection information

In this case we use the data source connection. We specify the JNDI name of the
data source, which in our case is jdbc/ejbbank.

On the next three wizard pages you can view and change the pages that will be
generated by the wizard.

The first page is the View Bean Data Page, where you can specify the style
sheet, error page, whether to store results in the session or request object, and
whether or not to create a Front Controller, use an existing one, or not use one at
all (Figure 8-5).

Chapter 8. Developing Web applications with database access 251


Figure 8-5 Create Database Web Pages wizard: View Bean Data Page

The Store results option determines where the results from the query should be
stored. You can choose to store them in the session, in which case they will be
available to other pages for the life of the session, or in the request. You should
be aware of potential memory issues if you choose to store a large result set in
the session.

The front controller option decides if a controller servlet is generated or reused.


The controller servlet uses initialization parameters that specify for each action
which JSP to call.

On the following page, you see the HTML input form (Figure 8-6).

252 WebSphere Studio Application Developer Version 5 Programming Guide


Last name

Figure 8-6 Create Database Web Pages wizard: design input form

Here you can make some changes to page and field properties. Notice that the
two input fields are automatically generated. This is where the :type and
:lastname host variable values will come from.

Select each host variable and change the label to the desired text, for example,
Transaction type and Last name.

Once this and the following pages have been generated, you can make further
changes using Page Designer.

The next page shows the master result page. The default is to use a table to
display the result rows from the query (Figure 8-7).

Chapter 8. Developing Web applications with database access 253


Figure 8-7 Create Database Web Pages wizard: design result form

Here you can change the heading of the columns and page properties. If you do
not want to show one or more of the fields retrieved from the query, you can
deselect them in the top left pane. Typically, you would only select a subset of
the fields for the master table.

To change the labels, select the item in the top left pane and make your changes
in the bottom left pane. Typically, you would change the headings of the table to
short descriptive names.

The next page shows the default form for showing details of a selected row in the
details view page (Figure 8-8). You can make the same type of changes here as
on the master table view page to improve the look of the page.

254 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 8-8 Create Database Web Pages wizard: design detail form

Finally, you can specify the default prefix for all generated objects (Figure 8-9).
Clicking Finish generates the Java classes and HTML/JSP pages.

Figure 8-9 Create database Web pages wizard: select prefix

Chapter 8. Developing Web applications with database access 255


Defining a data source in the server
Before we can test the application, we have to set up the data source in the
server. To use a data source, you have to configure the server to recognize it.
For our application, we have to register a data source for the EJBBANK database.

These steps assume that a WebSphere v5.0 Test Environment server has
already been created, as explained in “Creating a server for testing” on
page 224.

Open the Server perspective and edit the server configuration of the ItsoServer:
򐂰 Go to the Data source tab.
򐂰 Under Server Settings, select the Default DB2 JDBC Provider from the JDBC
provider list and click Add next to the data source list. The Create a Data
Source dialog is displayed (Figure 8-10).

Figure 8-10 Create a Data Source dialog

Select DB2 JDBC provider and make sure Version 5.0 data source is selected,
then click Next.

In the Modify Data Source window, as shown in Figure 8-11, enter EJBBANK as the
name and jdbc/ejbbank as the JNDI name. This name has to match the name
used in your application.

256 WebSphere Studio Application Developer Version 5 Programming Guide


Tip: The data source name and the JNDI name can be anything. We
recommend that you use the database name as the data source name and
jdbc/databasename as the JNDI name. See “Installing DB2 UDB” on page 786
for instructions on how to enable JDBC 2.0, which is required for data source
support.

Deselect Use this data source in container managed persistence (CMP). For now
we do not have any EJBs.

required for EJBs

Figure 8-11 Modify a Data Source

Click Next to continue to the next page of the wizard, as shown in Figure 8-12.
On this page, modify the databaseName field to be EJBBANK.

Chapter 8. Developing Web applications with database access 257


Figure 8-12 Create a Data Source - Specify database name

Select databaseName in the Resource Properties list, then enter EJBBANK in the
Value field. This is the only required property.

Click Finish and the data source is defined.

The Data source page of the server configuration is shown in Figure 8-13. Note
that you have to select a driver in the JDBC provider list to see the data sources
defined for that driver.

258 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 8-13 Server configuration with data source

The data source is now defined, so press Ctrl-S to save the server configuration.
If the server was running, it has to be restarted before running the application
that uses the data source.

Testing the database application


To test the generated database application, start the ItsoServer, select the
generated HTML input form (ListCreditsInputForm.html in this example), and
select Run on Server from its context menu.

A sample run is shown in Figure 8-14.

Chapter 8. Developing Web applications with database access 259


Figure 8-14 Sample database application run

Accessing a database using DB Beans


In this section, we explain how to use the DB Beans package to access a
database. The DB Beans classes can be found in the com.ibm.db.beans
package.

260 WebSphere Studio Application Developer Version 5 Programming Guide


To access the DB Beans from Application Developer, the following JAR file must
be available in the Web Content\WEB-INF\lib folder of the folder of the project:
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.dbjars_5.0.1\jars\
dbbeans.jar

Note: The dbbeans.jar file is already in the ItsoProGuideDataBaseWeb project


after using the DB Web Pages wizard.

To import a JAR file into the lib directory of a project:


򐂰 Select the lib folder and Import (context). Select File system, then navigate
to the dbbeans.jar file and import the file.
򐂰 Select the project and Properties (context). Select Java Build Path and on the
Libraries page click Add JARs and select the dbbeans.jar file.

The documentation for the classes in the package can be found in:
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.dbjars_5.0.1\jars\
dbbeans_javadoc.zip

Creating a JSP using DB Beans


After you have imported the package you can use the DB Beans classes by
using <jsp:useBean> to create the bean and then using scriptlets to execute
methods on it.

We begin by creating a new JSP called TestDBBeans.jsp. For more information


on creating a JSP, see “Working with JSPs” on page 210

A simple example of a JSP that executes an SQL statement using the DB Beans
classes is shown in Figure 8-15.

Note: This code was created using Page Designer by visually inserting beans
and scriptlets. To test the JSP, select Run on Server from its context menu.

In this example we use two of the DB Beans classes: DBConnectionSpec, which


handles the database connection, and DBSelect, which wraps an SQL SELECT
statement.

There is a small number of classes in the DB Beans package, and they are
straightforward to use.

Chapter 8. Developing Web applications with database access 261


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META name="GENERATOR" content="IBM WebSphere Studio">
<TITLE>TestDBBeans.jsp</TITLE>
</HEAD>
<BODY>
<H2>Number of rows in CUSTOMER table</H2>
<jsp:useBean id="Connect" class="com.ibm.db.beans.DBConnectionSpec"/>
<jsp:useBean id="SelectStatement" class="com.ibm.db.beans.DBSelect"/>
<% Connect.setDriverName("COM.ibm.db2.jdbc.app.DB2Driver");
Connect.setUrl("jdbc:db2:EJBBANK");
SelectStatement.setConnectionSpec(Connect);
SelectStatement.setCommand("SELECT * FROM ITSO.CUSTOMER");
SelectStatement.execute();
out.println("Row count is: " + SelectStatement.getRowCount());

%>
</BODY>
</HTML>

Figure 8-15 JSP with DB Beans example

The next section describes the JSP tags that have been built on top of the beans
to make it even easier to provide database access functionality to your Web
application.

Accessing a database using JSP taglib


Application Developer provides an alternative to using the DB Beans classes
described above. If you prefer, you can instead use a set of JSP tags built on top
of these classes. It is also possible to mix direct calls to DB Beans and JSP tags.

Note: The code referred to in this section can be generated using the
Database Web Pages wizard and selecting the IBM Database Access Tag
Library - Select Statement model. Refer to “Generate Web pages from SQL
queries” on page 249.

If you decide to use the JSP tags, you should be aware that there are some
restrictions compared to using the beans directly:
򐂰 For any of the JSP SQL actions that require a connection to the database, a
connection is opened when the tag is encountered, and closed after the tag
has been processed. Two actions cannot be performed within the same
transaction scope, or even using the same JDBC connection. The only

262 WebSphere Studio Application Developer Version 5 Programming Guide


exception to this is through the <x:batch> action. Actions inside the body of
the <x:batch> do share the same connection, and optionally, the same
transaction.
򐂰 Using the DB Beans directly, you have complete control over when a
database connection is opened and closed. You also have complete control
over transaction scopes, with the ability to turn AutoCommit on or off and to
do explicit commits or rollbacks.
򐂰 Some of the methods and properties of the DBSelect and DBProcedureCall
beans for handling large result sets are not offered in the JSP SQL actions:
– These methods and properties allow you to limit the number of rows
maintained in memory at any one time and to specify how many rows to
fetch at once when getting additional rows.
– This limitation is necessary because of the above limitation that the
database connection is closed after each JSP SQL action is processed. If
only a subset of the rows is initially fetched into memory, and then the
connection is closed, there is no way to later fetch the remaining rows.
– The JSP SQL actions do provide some support for large result sets via the
maxRows attribute of the <x:select> and <x:procedureCall> actions. This
attribute simply limits the number of rows that are fetched in any one result
set.
– The lockRows property of the DBSelect and DBProcedureCall bean is not
offered via the JSP SQL actions. This property causes a database lock to
be kept on a row in the result set while it is the current row. For a Web
application, it is not likely that you would want to maintain such a lock
across user interactions which could span an arbitrary amount of time.
– Because of the first limitation above, that the database connection is
closed after each JSP SQL action is processed, it is not possible for us to
maintain such a lock when you use the JSP SQL tags. When row locking is
not used, either with the JSP SQL tags or with direct use of the DB Beans,
optimistic locking is still used to prevent you from updating a row if
someone else updates it between the time that you read it and the time
that you attempt to update it.
– A greater variety of methods for moving between rows and between result
sets is available through direct use of the DB Beans than through the JSP
SQL actions.

To use the JSP database tags, you have to import the following two JAR files to
the Java build path into the WEB-INF\lib folder of your project:
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.dbjars_5.0.1\jars\jspsql.jar
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.dbjars_5.0.1\jars\dbbeans.jar

Chapter 8. Developing Web applications with database access 263


The jspsql.jar file contains the tags and dbbeans.jar contains the actual
classes used to access the database.

Creating a JSP
We now create a TestTagLib.jsp file to use tag libraries. See “Working with
JSPs” on page 210 for details about creating a new JSP.

Open TestTagLib.jsp in Page Designer. You can use the JSP editor to insert the
database tags into your page when you are in the Design view. To be able to use
the custom tags from the database tag library, you first have to do two things:
򐂰 Import the tag library into your Web application as described above.
򐂰 Create the taglib directive in the JSP.

To insert the taglib directive, bring up the context menu on the page in the Design
view and select Page Properties. In the dialog shown select JSP Tags and JSP
Directive - taglib from the Tag Type drop-down menu (Figure 8-16).

Figure 8-16 Insert JSP taglib directive

Click Add to select the tag library to add, and the dialog shown in Figure 8-17 is
displayed.

264 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 8-17 Selecting a tag library

Click Import to locate the jspsql.jar file to import. The Import a Tag Library
dialog opens (Figure 8-18). Click Browse to locate the JAR file:
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.dbjars_5.0.1\jars\jspsql.jar

Figure 8-18 Importing a tag library

Chapter 8. Developing Web applications with database access 265


Be sure to select Add an alias URI so that the tag library is added to the web.xml
file. The entry can be found on the References page.

Click OK to close the dialog. Now the tag library has been imported. Select the
jspsql check box to add it to the JSP (Figure 8-19).

Figure 8-19 Select the jspsql tag library

Select OK twice to close the dialog. The following tag is inserted into your JSP:
<%@taglib uri="jspsql" prefix="dab"%>

The full TestTagLib.jsp is available in:


\sg246957\sampcode\dev-webdb

266 WebSphere Studio Application Developer Version 5 Programming Guide


Building the JSP with custom tags
Now you can add tags to the JSP by selecting JSP -> Insert Custom. You should
see the following dialog (Figure 8-20).

Figure 8-20 Insert custom JSP tags

In the following example we create a JSP that displays a list of transaction


records. We show you some of the main tags that you would use to access the
database. The Application Developer online help contains descriptions for all the
tags that are available.

Note: Application Developer version 5 offers an improved New JSP wizard,


which includes a step to add tag libraries to a newly generated JSP file.

First, we have to create the connection to the database. To do this we use the
<dab:dataSourceSpec> tag. Select dataSourceSpec in the left list, then click
Insert. Click Close, then go to the Source view of the JSP editor. The following
new code has been added:
<dab:dataSourceSpec dataSource="" id="" />

Figure 8-21 shows the correct parameters and values to use for the
<dab:dataSourceSpec> tag. Update the tag in your JSP.

Chapter 8. Developing Web applications with database access 267


<dab:dataSourceSpec id="DSConnect" scope="page"
dataSource='jdbc/ejbbank'/>

Figure 8-21 Establishing a database connection

All the parameters for the connection are retrieved from the data source defined
in the server.

Tip: In the Properties view (Window -> Show View) you can see the properties
of each tag when you place the cursor within the tag.

Once you have established a connection, you can execute the query. Click JSP
-> Insert Custom again, and this time choose select and click Insert. Update the
new select tag to be the same as in Figure 8-22.

<dab:select id="select_master" scope="request" connectionSpec="DSConnect>">


<dab:sql>
SELECT ITSO.TRANSRECORD.TRANSID, ITSO.CUSTOMER.FIRSTNAME,
ITSO.CUSTOMER.LASTNAME, ITSO.TRANSRECORD.ACCID,
ITSO.TRANSRECORD.TRANSAMT
FROM ITSO.CUSTACCT, ITSO.CUSTOMER, ITSO.TRANSRECORD
WHERE ITSO.CUSTACCT.CUSTOMERID = ITSO.CUSTOMER.CUSTOMERID
AND ITSO.CUSTACCT.ACCID = ITSO.TRANSRECORD.ACCID
AND ITSO.TRANSRECORD.TRANSTYPE = 'C'
AND ITSO.CUSTOMER.LASTNAME LIKE :lastname
</dab:sql>
<dab:parameter position = "1" type="CHAR" value="Brown"/>
</dab:select>

Figure 8-22 Executing a select statement in a JSP tag

Here you use the connection created previously to issue the SQL select
statement. The input parameter is specified using the <dab:parameter> tag.

Assuming that you have created an HTML table to display the result, you can
then use <dab:repeat> and <dab:getColumn> to loop through the result set and
display the values. You can either use the insert custom method to get you
started, or enter the code shown in Figure 8-23.

268 WebSphere Studio Application Developer Version 5 Programming Guide


<TABLE border="1">
<TR>
<TH>TransID</TH><TH>Firstname</TH><TH>Lastname</TH>
<TH>Account</TH><TH>Amount</TH>
</TR>
<dab:repeat name="select_master" index="rowNum" over="rows" >
<TR>
<TD>
<dab:getColumn index="1"/>
<INPUT TYPE="hidden" NAME="ITSO_TRANSRECORD_TRANSID<%=rowNum%>"
VALUE='<dab:getColumn index="1"/>'/>
</TD>
<TD>
<dab:getColumn index="2"/>
</TD>
<TD>
<dab:getColumn index="3"/>
</TD>
<TD>
<dab:getColumn index="4"/>
</TD>
<TD>
<dab:getColumn index="5"/>
</TD>
</TR>
<%select_master.next();%>
</dab:repeat>
</TABLE>

Figure 8-23 Displaying result set values

As you can see from the discussion above, both the DB Beans and the
corresponding JSP tags give you an easy and quick way to access relational
data directly from a JSP. As was mentioned earlier, you have to be aware of the
potential problems of combining presentation and business logic in one JSP.

From a model-view-controller perspective, a JSP should ideally only implement


the presentation layer of your application, while the database access should be
handled by JavaBeans. However, if your application is small, or if you are building
a prototype, using the database access facilities described here may be a good
solution.

Chapter 8. Developing Web applications with database access 269


Running the JSP
Figure 8-24 shows the output of the JSP run execution.

Figure 8-24 JSP with DB Beans run

Summary
In this chapter we used the wizards within Application Developer to create
dynamic Web pages using SQL queries. We showed how to access databases
from a Web application, both by using the database Web page wizard and by
creating your own JSPs using tag libraries.

We also described the configuration of a test server with a data source.

270 WebSphere Studio Application Developer Version 5 Programming Guide


9

Chapter 9. Developing applications


with stored procedures
In this chapter, we discusses the following topics:
򐂰 What is a stored procedure?
򐂰 Creating a Java stored procedure
򐂰 Accessing a Java stored procedure
򐂰 Creating a stored procedure with multiple statements

Tip: When building stored procedures with DB2 be sure to use the DB2 app
JDBC driver. Using the BD2 net JDBC driver is unstable and may not work.

© Copyright IBM Corp. 2003. All rights reserved. 271


What is a stored procedure?
A stored procedure is a block of procedural constructs and embedded SQL
statements that are stored in a database and can be called by name. Stored
procedures allow an application program to be run in two parts, one on the client
and the other on the server, so that one client-server call can produce several
accesses to the database. This is good for performance because the traffic
between the client and the server is minimized.

Stored procedures can be written as SQL procedures, or as C, COBOL, PL/I, or


Java programs. In the following sections we will look at how to write and use a
Java stored procedure.

Note: The support for stored procedures varies between different data base
management systems. We are using DB2 stored procedures in the example.

Creating a Java stored procedure


In this section we create a simple stored procedure that takes a customer ID and
returns all customer information. Later we create a Web application that uses the
stored procedure.

Importing the database definition into a Web project


We use a new Web project ItsoProGuideStoredProcWeb for the stored procedure
examples. Create the project by following the instructions in “Creating a Web
project” on page 248.
򐂰 Open the Data perspective and go to the DB Servers view.
򐂰 Select the existing connection Con2 and Reconnect (context). Alternatively,
create a new connection as described in “Creating a database connection” on
page 145 (without a filter to get all the tables).
򐂰 Import the EJBBANK database into the ItsoProGuideStoredProcWeb project.
– Select the EJBBANK and Import to Folder, then select the
ItsoProGuideStoredProcWeb project and click Finish.
– The database is imported into Web Content/WEB-INF/databases.
򐂰 Figure 9-1 shows the Data Definition view in the Data perspective after the
EJBBANK database has been imported.

272 WebSphere Studio Application Developer Version 5 Programming Guide


imported database

folder for stored procedures

Figure 9-1 Data Definition view after importing EJBBANK database

Using the Stored Procedure Wizard


We are now ready to create the stored procedure. Select the Stored Procedures
folder and New -> Java Stored Procedure (or by selecting File -> New -> Other ->
Data -> Java Stored Procedure).

Enter getCustomer as the name of the stored procedure (Figure 9-2).

Figure 9-2 Specify stored procedure name

Chapter 9. Developing applications with stored procedures 273


Click Next and you are taken to the next page in the wizard. Here you specify the
settings and the SQL statement. Click Change to update the SQL statement.

In the SQL Statement window (Figure 9-3), you have several options for entering
an SQL statement:
򐂰 We recommended that you use the SQL Statement Wizard by clicking SQL
Assist (see “Using the SQL Statement Wizard” on page 165).
򐂰 You can enter the statement manually by typing the statement:
SELECT CUSTOMERID, TITLE, FIRSTNAME,
LASTNAME, USERID, PASSWORD
FROM
ITSO.CUSTOMER
WHERE
ITSO.CUSTOMER.CUSTOMERID = :customerID
This statement gets all fields from the customer table given a customer ID.
򐂰 We use one SQL statement (you can click Add to enter multiple statements).
򐂰 Click OK when done.

Figure 9-3 Specifying the SQL statement for the stored procedure

274 WebSphere Studio Application Developer Version 5 Programming Guide


Back in the wizard, the new SQL statement is shown in the statement text box. In
the remainder of this page of the wizard, you can add code fragments that you
wish to include in the generated stored procedure.

Click Next to go to the next page of the wizard, where you specify parameters for
the stored procedure (Figure 9-4):
򐂰 If you used SQL Assist to create the SQL statement, the parameter is already
filled in.
򐂰 If you typed the SQL statement, you have to create the parameter manually
by clicking Add and specifying In (as mode), customerID (as name), and
INTEGER (as SQL type).

Figure 9-4 Specify parameters for the stored procedure

Click Next to continue to the next page (Figure 9-5):


򐂰 Enter itso.storedproc as the Java package for the stored procedure.
򐂰 We leave the default values in the other fields. The Jar ID field is filled in by
default with a value containing the current time stamp.
򐂰 Do not select Build, we will build the stored procedure later.

Chapter 9. Developing applications with stored procedures 275


Figure 9-5 Specify options, such as Java Package, for stored procedure

Click Next, and a summary of the stored procedure is shown (Figure 9-6).

Figure 9-6 Summary of the new stored procedure before it is created

Click Finish to create the stored procedure. You can see the getCustomer stored
procedure in the Stored Procedures folder.

276 WebSphere Studio Application Developer Version 5 Programming Guide


The generated Java stored procedure code is shown in Figure 9-7. You can
double-click getCustomer to open the Java editor.

/**
* JDBC Stored Procedure ITSO.getCustomer
* @param customerID
*/
package itso.storedproc;

import java.sql.*; // JDBC classes

public class GetCustomer


{
public static void getCustomer ( int customerID,
ResultSet[] rs1 )
throws SQLException, Exception
{
// Get connection to the database
Connection con = DriverManager.getConnection
("jdbc:default:connection");
PreparedStatement stmt = null;
boolean bFlag;
String sql;

sql = "SELECT CUSTOMERID, TITLE, FIRSTNAME, "


+ " "
+ " LASTNAME, USERID, PASSWORD"
+ " "
+ " FROM"
+ " "
+ " ITSO.CUSTOMER"
+ " "
+ " WHERE"
+ " "
+ " ITSO.CUSTOMER.CUSTOMERID = ?";
stmt = con.prepareStatement( sql );
stmt.setInt( 1, customerID );
bFlag = stmt.execute();
rs1[0] = stmt.getResultSet();
}
}

Figure 9-7 getCustomer Java stored procedure

Chapter 9. Developing applications with stored procedures 277


Building the stored procedure
After a stored procedure is written locally, you must build it on the database
server. This uploads and compiles the procedure to the database server:
򐂰 Select the getCustomer stored procedure in the Data Definition view and Build
from the context menu.
򐂰 If you are prompted to create a new connection, select the Use Existing
Connection check box, select an existing connection in the combo box and
click Finish.
򐂰 Figure 9-8 shows the DB Output view, which contains the result of the build.

Figure 9-8 DB Output view with build output of stored procedure

Here we see that the build was successful. The GetCustomer class is compiled
and placed into a JAR file, and the JAR file is installed in the target database.

Tip: You can see stored procedures in the DB2 database system by opening
the Control Center.

278 WebSphere Studio Application Developer Version 5 Programming Guide


Executing the stored procedure
Application Developer provides a test facility for stored procedures:
򐂰 Select the getCustomer stored procedure in the Data Definition view and Run
from the context menu.
򐂰 The Run Settings dialog is displayed (Figure 9-9). Enter a customer ID, for
example 104, and click OK.

Figure 9-9 Run Settings dialog

򐂰 The output of the stored procedure is shown in the DB Output view


(Figure 9-10).

Figure 9-10 Output from running getCustomer stored procedure

We have now created a simple procedure that takes an input argument (a


customer ID) and returns the details about that customer from the database.

Tip: You can make changes to the stored procedure by selecting Properties
(context).

Chapter 9. Developing applications with stored procedures 279


Accessing a Java stored procedure
Once you have loaded a stored procedure into the database, it can be used from
an application. The code fragment below shows an example of how to call the
stored procedure:
CallableStatement cs = con.prepareCall("{call ITSO.GetCustomer(?)} ");
cs.setString(1, "104");
ResultSet rs = cs.executeQuery();
while (rs.next()) {
// get the data from the row
String firstName = rs.getString("firstName");
......
}

The ? is a place holder for a parameter. The second line sets 104 as the value for
the parameter. Following that, the stored procedure is executed and the results
are obtained from the result set.

Using a main program


We provide a main program called GetCustomerMain that you can import into the
ItsoProGuideStoredProcWeb project from:
\sg246957\sampcode\dev-proc\GetCustomerMain.java

Import the code into a new itso.storedproc.main package. A neat way to run
the main program in the Web application is by using the universal test client:
򐂰 Start the ItsoServer.
򐂰 Select the GetCustomerMain program and Launch Universal Test Client
(context).
򐂰 A Web browser with the universal test client opens with an instance of
GetCustomerMain created (Figure 9-11).
򐂰 Select the GetCustomerMain instance to expand.
򐂰 Select the main method.
򐂰 Click Expand to expand the String array the parameter.
򐂰 Click Add to create an entry.
򐂰 Enter a customer ID, for example, 104.
򐂰 Click Invoke.
򐂰 The result output is in the Console view.

280 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 9-11 Using the universal test client to run a main program

Generate a JavaBean to access the stored procedure


Application Developer provides a wizard to generate a JavaBean that accesses a
stored procedure:
򐂰 Create a itso.storedproc.bean package under Java Source.
򐂰 Select the getCustomer stored procedure in the Data Definition view and
Generate JavaBean (context).
򐂰 In the wizard (Figure 9-12):
– Click Browse to locate the ItsoProGuideStoredProcWeb/Java Source
folder.
– Click Browse to locate the itso.storedproc.bean package.
– Enter GetCustomberBean as the JavaBean to be generated.
– Select Stored procedure returns a result set and Generate a helper class.
– Click Next.

Chapter 9. Developing applications with stored procedures 281


Figure 9-12 Generate a JavaBean: class specification

򐂰 On the next page, describe the result set (Figure 9-13):


– Select the CUSTOMER table and the first six columns. Do not select the
ADDRESS column to match the SQL statement.
– Click Next.

Figure 9-13 Generate a JavaBean: describe result set

282 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 For connection information (Figure 9-14) select Use Data Source Connection
and Inside the execute () method and provide user ID and password. Click
Next.

Figure 9-14 Generate a JavaBean: connection information

򐂰 The last page (Figure 9-15) is a confirmation page that shows the methods
that are generated. Click Finish.

Figure 9-15 Generate a JavaBean: generated methods

Chapter 9. Developing applications with stored procedures 283


Two classes are generated:
򐂰 GetCustomerBeanRow—Provides access to one row of the result set.
򐂰 GetCustomerBean—Executes the stored procedure and provides a method to
retrieve an array of GetCustomerBeanRow objects.

Using the JavaBean


The generated JavaBean, GetCustomerBean, can be used in a servlet or JSP to
execute the stored procedure and access the result set.

A simple JSP to execute the JavaBean is shown in Figure 9-16. The code is
available in:
\sg246957\sampcode\dev-proc\RunGetCustomerBean.jsp

<BODY>
<H1>JSP -> JavaBean -> Stored Procedure</H1>
<jsp:useBean id="getCustomer"
class="itso.storedproc.bean.GetCustomerBean"></jsp:useBean>

<% getCustomer.execute( new Integer(106) ); %>

<% itso.storedproc.bean.GetCustomerBeanRow row = getCustomer.getRows()[0];


%>
<TABLE border="1">
<TR><TH align="left">ID</TH>
<TD><%= row.getCUSTOMER_CUSTOMERID() %></TD></TR>
<TR><TH align="left">Title</TH>
<TD><%= row.getCUSTOMER_TITLE() %></TD></TR>
<TR><TH align="left">Firstname</TH>
<TD><%= row.getCUSTOMER_FIRSTNAME() %></TD></TR>
......
</TABLE>
</BODY>

Figure 9-16 Simple JSP to execute the JavaBean with the stored procedure

The GetCustomerBean is instantiated using a <useBean> tag. The stored


procedure is executed and the first row of the result set (there is only one) is
retrieved and displayed.

Note that the customer ID is passed as a constant and no error checking is


performed. In a real application the code would be more complex.

Tip: Restart the enterprise application in the server after making changes to
the Web application deployment information.

284 WebSphere Studio Application Developer Version 5 Programming Guide


Using the JSP tag library
Stored procedures can also be executed through the jspsql tag library. See
“Accessing a database using JSP taglib” on page 262 for a description.

To make the tag library available for the Web application, we have to import the
JAR file into the lib directory and add the tag library to the deployment
descriptor:
򐂰 Select the ItsoProGuideStroedProcWeb\Web Content\WEB-INF\lib folder and
Import (context). Select File system, then locate the directory:
<wsadhome>\wstools\eclipse\plugins\com.ibm.etools.dbjars_5.0.1\jars
򐂰 Select only the jspsql.jar file and click Finish.
򐂰 Open the deployment descriptors (web.xml). On the References page, select
the JSP tag libraries tab. Click Add and select the jspsql tag library. Save the
deployment descriptor.

Figure 9-17 shows a sample JSP that uses the tag library to execute the stored
procedure. The code is available in:
\sg246957\sampcode\dev-proc\RunStoredProcedure.jsp

<%@taglib uri="jspsql" prefix="dab"%>


......
<BODY>
<H1>JSP with Stored Procedure Call</H1>
<dab:dataSourceSpec id="DSConnect" scope="page" dataSource='jdbc/ejbbank' />
<dab:procedureCall id="getCust" connectionSpec="DSConnect" scope="request">
<dab:sql>
{ CALL ITSO.GETCUSTOMER(:customerID) }
</dab:sql>
<dab:parameter parmName="customerID" type="INTEGER" mode="in" value="104"
/>
</dab:procedureCall>
<TABLE border="1">
<TR><TH align="left">ID</TH>
<TD><dab:getColumn name="getCust" index="1" /></TD></TR>
<TR><TH align="left">Title</TH>
<TD><dab:getColumn name="getCust" index="2" /></TD></TR>
<TR><TH align="left">Firstname</TH>
<TD><dab:getColumn name="getCust" index="3" /></TD></TR>
......
</TABLE></BODY>

Figure 9-17 JSP with tag library to execute stored procedure

Chapter 9. Developing applications with stored procedures 285


Generate JavaBean Web pages
You can use the Create Web Pages from a JavaBean wizard to build the input
and output pages to test the JavaBean that calls the stored procedure.

This wizard is described in “Creating Web pages from a JavaBean” on page 237,
therefore we only provide short instructions here to run through the wizard:
򐂰 Select New -> Other -> Web -> JavaBean Web Pages.
򐂰 Select /ItsoProGuideStoredProcWeb/Web Content as destination and
itso.storedproc.web as package.
򐂰 Select itso.storedproc.bean.GetCustomerBean as the bean. Click Introspect
if necessary.
򐂰 Select the rows property (the result of the stored procedure) and the execute
method (to run the stored procedure).
򐂰 Select Create a new front controller.
򐂰 Tailor the input page with:
– Title: Execute Stored Procedure
– Prompt: Enter a customer ID:
򐂰 Tailor the result page with:
– Title: Stored Procedure Results
– Label for rows property: Customer
– Expand rows, select the six properties (all except class), and set short
labels for all the properties (Title, Lastname, UserID, Password, ID,
Firstname)
򐂰 Leave GetCustomerBean as prefix and click Finish to generate the code. You
get a servlet, an HTML input page, and a result JSP:
GetCustomerBeanController.java
GetCustomerBeanInputForm.html
GetCustomerBeanResultsForm.jsp

To test the generated application, restart the enterprise application (select the
ItsoServer and Restart Project -> ItsoProGuide) or restart the server.

Select the GetCustomerBeanInputForm.html file and Run on Server. Enter a


customer ID and click Submit. A sample run is shown in Figure 9-18.

286 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 9-18 Running the generated Web application

Creating a stored procedure with multiple statements


Here we want to create a stored procedure that transfers money between two
accounts. Therefore, we have to execute two SQL statements in sequence, one
to withdraw money from one account, and one to deposit money into another
account.

To create this stored procedure:


򐂰 In the Data perspective, select the Stored Procedures folder and New ->
Stored Procedure.
򐂰 Enter transferMoney as name.
򐂰 On the definition page, select None for result sets and SP_JAVA_HDR.FRAGMENT
for the header fragment. Click Change to enter the SQL statements.

Chapter 9. Developing applications with stored procedures 287


򐂰 In the SQL statement dialog (Figure 9-19) enter the first SQL statement as:
UPDATE ITSO.ACCOUNT
SET BALANCE = (BALANCE - :amount)
WHERE ACCID = :account1
AND BALANCE > :amount
򐂰 Click Add to get space for another SQL statement and enter:
UPDATE ITSO.ACCOUNT
SET BALANCE = (BALANCE + :amount)
WHERE ACCID = :account2
򐂰 Click OK and then click Next.

Figure 9-19 Stored procedure with two statements

򐂰 In the Parameters dialog, one parameter named whichQuery is predefined.


The generated code assumes that you want to run one of the two statements.
We will have to run both. We will take care of this in the generated code.
򐂰 Define these parameters (Figure 9-20):
– In: account1, VARCHAR, 8
– In: account2, VARCHAR 8
– In: amount, DECIMAL, 8.2
– Out: success, INTEGER

288 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 9-20 Parameters for the stored procedure

򐂰 You can skip the rest of the dialog and click Finish.

Edit the generated code


The generated Java class TransferMoney uses the whichQuery parameter to
decide which statement to execute. We have to change the code to execute both
statements and to set the return value.

Our changes are as follows:


򐂰 Remove the whichQuery parameter.
򐂰 Remove the switch and case statements.
򐂰 Create variables for both SQL statements.
򐂰 Run both statements in sequence.
򐂰 Set the result as the sum of the changed rows (a result of 2 would be a
success).

The changed method is shown in Figure 9-21.

Chapter 9. Developing applications with stored procedures 289


public static void transferMoney ( int whichQuery,
String account1,
String account2,
java.math.BigDecimal amount,
int[] success )
throws SQLException, Exception
{
// Get connection to the database
Connection con = DriverManager.getConnection("jdbc:default:connection");
PreparedStatement stmt = null;
PreparedStatement stmt2 = null;
int updateCount = 0;
int updateCount2 = 0;
boolean bFlag;
String sql, sql2;
switch (whichQuery)
{
case 0:
sql = "UPDATE ITSO.ACCOUNT"
+ " SET BALANCE = (BALANCE - ?) "
+ " WHERE ACCID = ? "
+ " AND BALANCE > ?";
stmt = con.prepareStatement( sql );
stmt.setBigDecimal( 1, amount );
stmt.setString( 2, account1 );
stmt.setBigDecimal( 3, amount );
bFlag = stmt.execute();
rs1 = stmt.getResultSet();
updateCount = stmt.executeUpdate();
break;
case 1:
sql2 = "UPDATE ITSO.ACCOUNT"
+ " SET BALANCE = (BALANCE + ?) "
+ " WHERE ACCID = ?";
stmt2 = con.prepareStatement( sql2 );
stmt2.setBigDecimal( 1, amount );
stmt2.setString( 2, account2 );
bFlag = stmt.execute();
rs1 = stmt.getResultSet();
updateCount2 = stmt2.executeUpdate();
break;
default:
sql = "SELECT PROCSCHEMA, PROCNAME FROM SYSCAT.PROCEDURES";
stmt = con.prepareStatement( sql );
}
updateCount = stmt.executeUpdate();
// Set return parameter
success[0] = updateCount + updateCount2;
}

Figure 9-21 Updated stored procedure with two SQL statements

290 WebSphere Studio Application Developer Version 5 Programming Guide


Build and execute
Build the stored procedure by selecting Build from the context menu.

Test the procedure by selecting Run. Enter 106-6001, 106-6002, and 100.00 as
parameters. The DB Output view (Figure 9-22) shows the result value in the
Parameters tab.

Figure 9-22 Stored procedure run

Tip: The database is not updated by default. Select the transferMoney stored
procedure and Run Settings (context). On the Options tab you can select
Commit changes to the database.

Using a JSP
We provide the RunTranfer.jsp to execute the transferMoney stored procedure.
The core code is shown in Figure 9-23.

<dab:dataSourceSpec id="DSConnect" scope="page" dataSource='jdbc/ejbbank' />


<dab:procedureCall id="transfer" connectionSpec="DSConnect" scope="request">
<dab:sql>
{ CALL ITSO.TRANSFERMONEY (:account1, :account2, :amount, :success) }
</dab:sql>
<dab:parameter parmName="account1" type="VARCHAR" mode="in"
value="106-6002" />
<dab:parameter parmName="account2" type="VARCHAR" mode="in"
value="106-6001" />
<dab:parameter parmName="amount" type="DECIMAL" mode="in"
value="100.00" />
<dab:parameter parmName="success" type="INTEGER" mode="out" />
</dab:procedureCall>
......
Amount: <dab:getParameter name="transfer" parmName="amount" /><br>
Result: <dab:getParameter name="transfer" parmName="success" />

Figure 9-23 JSP to execute the transfer stored procedure

Chapter 9. Developing applications with stored procedures 291


Summary
In this chapter we developed two stored procedures, one with a result set and
one that updates the database.

We also showed how stored procedures can be invoked through JavaBeans and
JSPs.

292 WebSphere Studio Application Developer Version 5 Programming Guide


10

Chapter 10. Developing Struts


applications
In this chapter we introduce you to the Jakarta Struts framework and Application
Developer’s support for building Struts-based Web applications.

The chapter describes how to:


򐂰 Create a Web project with Struts support
򐂰 Create a Web diagram and lay out the components of the application
򐂰 Implement form beans, JSPs, and actions
򐂰 Use the Struts configuration file editor
򐂰 Test the application

© Copyright IBM Corp. 2003. All rights reserved. 293


What is Struts?
Struts is an open source framework for building Web applications according to
the model-view-controller (MVC) architectural pattern. Struts is part of the
Jakarta project, sponsored by the Apache Software Foundation.

By using Struts you can get a clean separation between the presentation and
business logic layers of your application. Struts also speeds up Web application
development by providing an extensive JSP tag library, parsing and validation of
user input, error handling, and internationalization support.

The scope of this chapter is not to teach you the Struts framework in detail, but to
show how to use Application Developer’s Struts tools for building a Struts Web
application. To learn more about the Struts framework, please refer to the official
Jakarta project Struts home page and the official Struts user guide at:
http://jakarta.apache.org/struts
http://jakarta.apache.org/struts/userGuide/introduction.html

There is also a number of very good Struts tutorials available on the Internet.

Note: Application Developer 5.0 includes support for Struts Version 1.02 and
Version 1.1 beta 2. At the time of writing, the latest version of the Struts
framework is version 1.1 Release Candidate 1.

MVC architectural pattern


The model-view-controller architectural pattern was conceived in the mid-1980's
by developers of the Smalltalk-80 GUI library. It has since then been extensively
applied in most object oriented user interface and application control toolkits,
as is the case with Struts, and has been improved to respond to specific platform
requirements, such as J2EE. It has also been generalized as a pattern for
implementing the separation of concerns among application layers in general,
and not only the three originally proposed layers.

According to the MVC pattern, a software component (an application, a module,


and so forth) should separate its business logic (the model) from its presentation
(the view). There are many reasons for this requirement, among which are these
facts:
򐂰 You may have more than one view of the same model. If both the business
logic and its presentation were built together, adding an additional view would
cause considerable disruptions and increase the component's complexity. A
good example of a model with two views would be a banking application that
can be accessed through both the Internet and mobile phones.

294 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 You do not want to have to change the model every time you modify the view.
The view is definitely dependent on the model, for it presents specific aspects
of the model to the user. It makes no sense, though, to have the model
depend on the view. Building both together dramatically increases the
chances of this happening, and of you having to change the model every time
you implement a small change to the view.

This separation can be achieved through the layering of the component into:
򐂰 The model layer, responsible for implementing the business logic.
򐂰 The view layers, each responsible for rendering the user interface (be it
graphical or not) to a specific client type and in a specific fashion.

With these two layers, we can implement the business logic and present it to the
user. That solves only half of the problem. We would also like to be able to
interact with the model. The implementation of this interaction is better left to a
third layer, called controller.

In the following sections we discuss some of the properties of each of these


layers.

Model
The model layer manages the application domain’s concepts, both behavior and
state. It responds to requests for information about its state and responds to
instructions to change its state.

Just like any software component, the model should have a well-defined and an
as simple as possible public interface. This is usually achieved through the use of
a facade. The intent of facades is to provide a simple and unified interface to the
otherwise complex model that lies behind it. By doing so, we reduce the
dependencies between the model classes and its clients. Less dependencies
mean more freedom to adapt to new requirements.

Note: Facade is a documented design pattern. For more information, refer to


Design Patterns: Elements of Reusable Object-Oriented Software.

As an example, consider an appliance with which you are certainly familiar: a


television set. You will probably agree that changing TV channels is quite a
simple task. Now ask yourself these questions:
򐂰 Do you know how the television set represents channels internally?
򐂰 Do you know exactly what goes on when you change TV channels?
򐂰 Do you think you should know these things?

Chapter 10. Developing Struts applications 295


Chances are that you have answered no to all of the questions above. What is
the advantage of you not knowing how TVs represent their data and implement
their operations? That way you can buy a new TV, which does these things
internally in a completely different way, and you could still change channels.

Figure 10-1 shows the model layer with its encapsulated business domain
objects and the exposed facade object.

Model

Façade

Figure 10-1 Model layer

Please note that the model does not have any dependences on views or
controllers.

View
The view layer implements a rendering of the model. The responsibility of the
view is to know what parts of the model’s state are relevant for the user, and to
query the model for that information. The view retrieves the data from the model
or receives it from the controller, and displays it to the user in a way the user
expects to see it.

Controller
The controller’s responsibility is to capture user events and to determine which
actions each of these events imply, depending on both the user’s and the
application’s state. This usually involves verifying pre- and post-conditions.
These actions can then be translated to messages to the model and view layers,
as appropriate.

296 WebSphere Studio Application Developer Version 5 Programming Guide


Dependencies between MVC layers
Figure 10-2 shows the dependencies allowed in the MVC pattern. Note that the
less dependencies your layers have, the easier it will be for the layers to respond
to requirement changes.

A B <=> A depends on B

Controller View

Model

Figure 10-2 Dependencies allowed in the MVC pattern

So, to summarize, the MVC pattern is really about separation.

MVC framework with Struts


Struts provides these components to develop applications using MVC
(Figure 10-3):
Model Struts does not provide model classes. The business logic must
be provided by the Web application developer as JavaBeans or
EJBs.
View Struts provides action forms to create form beans that are used
to pass data between the controller and view. In addition, Struts
provides custom JSP tag libraries that assist developers in
creating interactive form-based applications using JSPs.
Application resource files hold text constants and error message,
translated for each language, that are used in JSPs.
Controller Struts provides an action servlet (controller servlet) that
populates action forms from JSP input fields and then calls an
action class where the developer provides the logic to interface
with the model.

Chapter 10. Developing Struts applications 297


View Controller Model
Tag libraries

Action

: JSP
ActionServlet Action Model

: ActionForm
Action

configuration
Application file Action
Resources

Struts Support

Figure 10-3 Struts components in the MVC architecture

A typical Struts Web application is composed of these components:


򐂰 A single servlet (extending org.apache.struts.action.ActionServlet)
implements the primary function of mapping a request URI to an action class.
Before calling the action class, it populates the form bean associated to the
action with the fields from the input JSP. If specified, the action servlet also
requests the form bean to validate the data. It then calls the action class to
carry out the requested function. If form bean validation fails, control is
returned to the input JSP so the user can correct the data. The action servlet
is configured by an XML configuration file that specifies the environment and
the relationship between the participating components.
򐂰 Multiple JSPs that provide the end-user view. Struts comes with an extensive
tag library to make JSP coding easier. The JSPs display the information
prepared by the actions and requests new information from the user.
򐂰 Multiple action classes (extending org.apache.struts.action.Action) that
interfaces with the model. When an action has performed its processing, it
returns an action forward object which determines the view that should be
called to display the response. The action class prepares the information
required to display the response, usually as a form bean, and makes it
available to the JSP. Usually the same form bean that was used to pass
information to the action is used also for the response, but it is also common
to have special view beans tailored for displaying the data. An action forward
has properties for its name, address (URL) and a flag specifying if a forward

298 WebSphere Studio Application Developer Version 5 Programming Guide


or redirect call should be made. The address to an action forward is usually
hard coded in the action servlet configuration file but can also be generated
dynamically by the action itself.
򐂰 Multiple action forms (extending org.apache.struts.action.ActionForm) to
hold the data retrieved from the JSPs. The action forms are generic
Javabeans with getters and setters for the input fields available on the JSPs.
Usually there is one form bean per Web page, but you can also use more
coarse-grained form beans holding the properties available on multiple Web
pages (this fits very well for wizard-style Web pages). If data validation is
requested (a configurable option) the form bean is not passed to the action
until it has successfully validated the data. Therefore the form beans can act
as a sort of firewall between the JSPs and the actions, only letting valid data
into the system.
򐂰 One application resource file per language supported by the application holds
text constants and error messages and makes internationalization easy.

Figure 10-4 shows the flow of information for an interaction in a Struts Web
application.

: Web user : ActionServlet : Action : ActionForm : JSP


(Browser)

HTTP setXxx()
validate()

execute() getXxx()

setXxx()
"forward"

forward()

getXxx()

Figure 10-4 Struts request sequence

A request from a Web browser reaches the Struts ActionServlet. If the action
that will handle the request has a form bean associated with it, Struts creates the
form bean and populates it with the data from the input form. It then calls the
validate method of the form bean. If validation fails, the user is returned to the
input page to correct the input. If validation succeeds, Struts calls the action’s
execute method. The action retrieves the data from the form bean and performs
the appropriate logic. Actions often call session EJBs to perform the business

Chapter 10. Developing Struts applications 299


logic. When done, the action either creates a new form bean (or other
appropriate view bean) or reuses the existing one, populates it with new data,
and stores it in the request (or session) scope. It then returns a forward object to
the Struts action servlet, which forwards to the appropriate output JSP. The JSP
uses the data in the form bean to render the result.

Note: In Struts version 1.0 the execute method of the Action class was called
perform.

Application Developer support for Struts


Application Developer provides specific support for Struts-based Web
applications:
򐂰 A Web project can be configured for Struts. This adds the Struts run time (and
dependent JARs), tag libraries, and action servlet to the project, and creates
skeleton Struts configuration and application resources files. Application
Developer 5.0 provides support both for Struts 1.02 and 1.1 beta 2, selectable
when setting up the project.
򐂰 A set of component wizards to define action form classes, action classes with
action forwarding information, and JSP skeletons with the tag libraries
included.
򐂰 A configuration file editor to maintain the control information for the action
servlet.
򐂰 A graphical design tool to edit a graphical view of the Web application from
which components (forms, actions, JSPs) can be created using the wizards.
This graphical view is called a Web diagram. The Web diagram editor
provides top-down development (developing a Struts application from
scratch), bottom-up development (that is, you can easily diagram an existing
Struts application that you may have imported) and meet-in-the-middle
development (that is, enhancing or modifying an existing diagrammed Struts
application).
򐂰 Web Structure view that provides a hierarchical (tree-like) view of the
application. This view shows the artifacts, such as Web pages and actions,
and you can expand the artifacts to see their attributes. For example, an
action can be expanded to see its forwards, which can then be expanded to
see its links. This is useful for understanding specific execution paths of your
application. The Web Structure view is available in the Web perspective.
򐂰 Page Designer support for rendering the Struts tags, making it possible to
properly view Web pages that use the Struts JSP tags. This support is
customizable using Application Developer’s Preferences settings.

300 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 Validators to validate the Struts XML configuration file and the JSP tags used
in the JSP pages.

Developing a Web application using Struts


To show how to use the Application Developer Struts tools, we rewrite the
RedBank Web application we developed in “Sample application: RedBank” on
page 180 using the Struts framework.

The application is a banking application that allows a customer to enter his or her
customer number, select an account to work with, and then to perform four
different transactions: list the transactions for the selected account, deposit,
withdraw, and transfer money. The back-end of the application is, for sake of
simplicity, implemented as simple JavaBeans. We will implemented the back-end
using EJB technology in Chapter 12, “Developing EJB applications” on page 373.

Because the Struts framework provides us with the controller and view parts of a
Web application, but not the model, we will reuse the model from the RedBank
application and simply show you how to replace its controller and view with
Struts.

To create our Web application with Struts:


򐂰 We create a new Web project with Struts 1.1 beta 2 support.
򐂰 We import the parts of the existing RedBank application that we will reuse.
򐂰 We create a Web diagram where we lay out all the JSPs, form beans, and
actions that make up the application, and connect them to define the
application flow.
򐂰 We implement the components one by one.
򐂰 Finally, we do some customization using the Struts configuration file editor
and then launch the application in the built-in WebSphere Test Environment.

Note: Because this chapter focuses on Application Developer’s Struts tools


and wizards (more than the architecture and best practices of a Struts
application) we try to use the Struts tools and wizards as much as possible
when creating our application.

After having used the wizards to create some components (JSPs, form beans,
actions) you may be able to create new components even quicker by copying
and pasting from your existing components than by using all the wizards.

Chapter 10. Developing Struts applications 301


Creating a Struts Web project
Before we can start implementing the Struts application we create a Web project
with Struts support:
򐂰 Create a new Web project by selecting File -> New -> Web project and enter
ItsoProGuideStrutsWeb as the name of the project. Select Add Struts support
and then click Next (Figure 10-5).

Figure 10-5 Creating a Web project with Struts support

Note: If you create a Web project as part of creating an Enterprise


Application Project you will not be given the option to add Struts support at
that time. You will have to add the Struts support afterwards by selecting
Properties from the Web project’s context menu and check the Add Struts
support option there.

򐂰 Add the project to the existing ItsoProGuide enterprise application project.


Leave ItsoProGuideStrutsWeb as the context root and click Next
(Figure 10-6).

302 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 10-6 Web project settings

򐂰 On the Module Dependencies page, select the ItsoProGuideJava.jar project


to create a classpath reference to the model that we reuse and click Next
(Figure 10-7).

Figure 10-7 Specify module dependencies

Chapter 10. Developing Struts applications 303


򐂰 On the Struts Settings page, select Override default settings:
– Change the Struts version to 1.1 (beta2).
– Enter itso.strutsweb as the Default Java package prefix.
– Leave itso.strutsweb.resources as the Java package for the resource
bundle.
– Leave ApplicationResources as the resource bundle name.
– Click Finish (Figure 10-8).
Click OK when prompted to repair the server configuration. This action adds
the new Web project to the server configuration.

we used the Struts


beta support

Figure 10-8 Setting Struts properties

The new Web project is configured with:


򐂰 An application resources file:
Java Source\itso.strutsweb.resources.ApplicationResources.properties
򐂰 An action servlet (in web.xml)
򐂰 A configuration file (struts-config.xml) and six tag libraries
(struts-xxxx.tld) in Web Content\WEB-INF
򐂰 The Struts runtime classes (struts.jar and dependent JAR files) in Web
Content\WEB-INF\lib.

304 WebSphere Studio Application Developer Version 5 Programming Guide


Notes:
򐂰 If you create a Web project with Struts 1.02 support, there will be only one
JAR file (struts.jar) in the lib directory, because Struts 1.02 includes all
dependent classes in this single JAR. In Struts 1.1 these classes are now
split into multiple JAR files.
򐂰 Although not necessary for our simple application, you would probably
want to upgrade the Struts JAR file to a later version than the 1.1 beta 2
shipping with Application Developer 5.0. At the time of writing, the latest
version of Struts is 1.1 Release Candidate 1.
򐂰 The Struts action servlet is configured (in web.xml) to intercept all requests
with a URL ending in .do (the servlet mapping is *.do). This is common for
Struts applications, but equally common is using a servlet mapping of
/action/* to intercept all URLs beginning with /action.

Copying the facade


We will use the same model and facade as in Chapter 7, “Developing Web
applications” on page 179. The easiest way to get the facade is by copying:
򐂰 Select the itso.bank.facade package in the ItsoProGuideBasicWeb project
and Copy from the context menu.
򐂰 Select the Java Source folder in the ItsoProGuideStrutsWeb project and
Paste from the context menu.

Alternatively you can create the itso.bank.facade package manually and import
the Banking class from the \sg246957\sampcode\dev-struts\initial\facade
directory.

Importing RedBank Web content


We want to mirror the image and style sheet of the ItsoProGuideBasicWeb project
in the new ItsoProGuideStrutsWeb project:
򐂰 Open the Web perspective, J2EE Navigator view, select the
ItsoProGuideStrutsWeb\Web Content directory and Import (context).
򐂰 Select File system as source to import from and then click Next.
򐂰 Click Browse and locate:
\sg246957\sampcode\dev-struts\initial\Web Content
򐂰 Expand the Web Content directory and select the check box next to it.
򐂰 Click Finish (Figure 10-9).

Chapter 10. Developing Struts applications 305


Figure 10-9 Importing sample code

Updating ApplicationResources.properties
The wizard created an empty ApplicationResources.properties file for us and
we have to update it with the texts and messages for our application.

While developing Struts applications, you will usually find yourself having this file
open, because you will typically add messages to it as you go along writing your
code. Figure 10-10 shows an extract of this file.

306 WebSphere Studio Application Developer Version 5 Programming Guide


# Optional header and footer for <errors/> tag.
errors.header=<P><font color="#ff0000"><strong><ul>
errors.footer=</ul></strong></font></P>
error.missing.customerId=<li>You must enter your customer ID.
error.missing.accountNumber=<li>You must select an account to work with.
...
error.invalid.customerId=<li>Invalid customer ID. Please try again.
error.invalid.amount=<li>Invalid amount. Please correct your entry.
...
text.pageTitle=ITSO Bank
text.welcome=Welcome to the ITSO Bank
text.customersAccounts={0}'s Accounts
...
...
prompt.enterCustomerId=Please, enter your customer ID:
prompt.account=Select the account:
prompt.transaction=Select the transaction:
...

Figure 10-10 ApplicationResources.properties (extract)

򐂰 In the Web perspective, expand Java Source and then open the
itso.strutsweb.resources.ApplicationResources.properties file.
򐂰 Replace then contents of the file with the contents in:
\sg246957\sampcode\dev-struts\initial\ApplicationResources.properties
򐂰 Press Ctrl-S to save the file and then close the editor.

The exception classes we use extend the itso.bank.exception.BankException


class and have a method called getMessageKey. This method returns the key for
the error message so that we can retrieve the clear text message from the
ApplicationResources.properties file when an error has occurred. An example
of the getMessageKey method is:
public String getMessageKey() {
return "error.customerDoesNotExistException";
}

Creating the Struts Web diagram


We take a top-down approach to design the Web application by laying out all the
components in a Web diagram:
򐂰 Select the WEB-INF folder and New -> Other -> Web -> Struts -> Web diagram.
Click Next. Enter strutsbank as the file name and click Finish.

Chapter 10. Developing Struts applications 307


򐂰 The Web diagram editor opens on the strutsbank.gph file (.gph is the file
type for Web diagrams).
򐂰 Notice the icons in the tool bar:

The icons on the right are to place new components into the empty diagram.
The icons are connections, actions, form beans, JavaBeans, JSPs,
sub-diagrams, and Struts modules.

Adding the components


Use the icons in the toolbar to add four JSP pages, three actions, and two form
beans on the empty surface (Figure 10-11):
򐂰 When you drop a JSP page or an action, you can change its name to the
name shown in Figure 10-11.
򐂰 When you drop a form bean, you are prompted for a name and scope. Enter
customerInfoForm and transactionForm as names and select request as
scope.

Figure 10-11 Web diagram with initial components

Components in gray are not yet implemented, meaning they are only available in
the Web diagram and not as an underlying file such as a Java class or JSP.

308 WebSphere Studio Application Developer Version 5 Programming Guide


Designing the application flow
When the components are laid out, it is time to connect them to define the flow of
the application. Figure 10-12 shows the layout with connections.

Figure 10-12 Web diagram with components connected

򐂰 Select index.jsp and select Connection (context). A line appears connecting


index.jsp to the mouse cursor. Click the listAccounts action to complete the
connection. A dotted line appears from index.jsp to listAccounts. (You can
also use the Connection icon and click the two items to connect.)
򐂰 Connect listAccounts.jsp to the accountDetails action, the
accountDetails.jsp to the performTransaction action, and the
listTransactions.jsp to the accountDetails action.
򐂰 Connect the listAccounts action to listAccounts.jsp. Connecting an action
to a JSP page creates a forward, and you are prompted to enter a name for it.
Overtype <new> with the name success. The listAccounts action can then
lookup the listAccounts.jsp by referring to the name success.
򐂰 Connect the accountDetails action to the accountDetails.jsp and enter
success as the name for this forward as well.
򐂰 The performTransaction action uses four different forwards depending on
which transaction was performed:
– Connect the performTransaction action to listTransactions.jsp and call
this forward listTransactions.

Chapter 10. Developing Struts applications 309


– Add three forwards from performTransaction back to accountDetails.jsp
and call the forwards deposit, withdraw, and transfer, respectively.
򐂰 Connect the customerInfoForm to the listAccounts action and also to the
accountDetailsAction. The customerInfoForm is used by both actions.
򐂰 Connect the transactionForm to the performTransaction action.
򐂰 Save the Web diagram by pressing Ctrl-S.

Tip: You can select a component in the diagram and from the context menu
select:
򐂰 Change Path to change the name of a JSP or action
򐂰 Edit the forward name to change the name of a connection
򐂰 Change Description to add descriptive text to any components

To improve the layout of the application flow, you can drag components to
another spot and you can rearrange connections by dragging their middle
point.

Implementing the Struts Web diagram


When the Web diagram is laid out, it is time to start implementing the
components. This can be done in a different order, and the support you get from
Application Developer’s Struts tools depends on the order you choose:
򐂰 You can implement the form beans first. When you later implement the JSPs,
you can choose which fields from the form beans should be present on the
pages.
򐂰 You can implement the JSPs first. When you later implement the form beans,
you can choose which fields from the JSP pages should be added to the form
beans as properties.

We choose to implement the form beans first to have full control over their
contents and structure.

Developing the form beans


We start by implementing the customerInfoForm form bean:
򐂰 Double-click the customerInfoForm form bean in the Web diagram. This
opens up the New ActionForm Class dialog as shown in Figure 10-13.

310 WebSphere Studio Application Developer Version 5 Programming Guide


Figure 10-13 New ActionForm Class wizard

Application Developer automatically generates a Struts form bean class


called itso.strutsweb.forms.CustomerInfoForm and implement skeleton
methods for its reset and validate methods. The default values in the dialog
are fine, so click Next to proceed.
򐂰 On the next page we can select the fields from the JSPs we want to include in
the form bean. Because we do not yet have any implemented JSPs, we
cannot use this feature, so just click Next (Figure 10-14).

Chapter 10. Developing Struts applications 311


Figure 10-14 Selecting fields from JSPs

򐂰 On the third page of the wizard we can enter the fields we want our form bean
to hold. Click Add and add each of the following fields (Figure 10-15):
customerNumber String
customerName String (firstname lastname)
accountNumber String (after selection)
accountNumbers String[] (list retrieved from customer)
validateKey String (1 or 2, which action)

Figure 10-15 Adding form bean fields

Click Next.

Note: Make sure you press Enter after entering the text in each field.
Otherwise, when you click Next, Application Developer may not include the
last field you updated.

312 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 On the next page (Figure 10-16) you are prompted to add a mapping for the
form bean to the Struts configuration file. Accept the defaults and click Finish.

Figure 10-16 Adding struts-config.xml mapping

The form bean wizard creates a new Java class extending the
org.apache.struts.action.ActionForm class and opens it up in the editor.
򐂰 Replace the validate method (not the whole class) with the code shown in
Figure 10-17. The code is available in:
\sg246957\sampcode\dev-struts\initial\forms\CustomerInfoForm.txt

public ActionErrors validate( ActionMapping mapping,


HttpServletRequest request) {
ActionErrors errors = new ActionErrors();
// Validate the customerNumber
if ("1".equals(validateKey)) {
if (customerNumber == null || customerNumber.trim().length() == 0)
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError("error.missing.customerId"));
else if (customerNumber.trim().length() != 3)
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError("error.invalid.customerId"));
}

// Validate the accountNumber - defer to action class


if ("2".equals(validateKey)) {}

return errors;
}

Figure 10-17 CustomerInfoForm validate method

Chapter 10. Developing Struts applications 313


Because we use this form bean on multiple input pages, we have to know
which of the fields should be validated. We use the validateKey string for this
purpose. On the JSPs where this form bean is used, we pass an appropriate
value for the validateKey so we can validate the data entered on that
particular page only.
The validate method in a Struts form bean acts as a kind of firewall between
the input pages and the Struts actions, only letting validated data into the
actions. The validate method is useful for performing simple validation such
as verifying that data has actually been submitted, has the correct length, and
so forth. However, it is not the appropriate place to do more advanced
validation, such as calling an EJB to validate that a customer number really
exists. That type of validation is best carried out by the actions themselves.
The validate method returns an org.apache.struts.action.ActionErrors
object with the keys for the errors it has found. This is used by the JSPs to
inform the user that an entry has to be corrected.
When done, save and close the CustomerInfoForm class.
򐂰 Implement the transactionForm form bean using the same method. This
class should be called TransactionForm and have the following fields:
action String (ListTransactions, Deposit, ...)
amount String (for deposit, withdraw, transfer)
destinationAccount String (for transfer only)
accountID String (to remember)
accountBalance String (to remember)
transactions itso.bank.model.TransRecord[]
(retrieved for an account)
Make sure the form is added to struts-config.xml with the mapping name
transactionForm.
򐂰 Add an import statement:
import itso.bank.util.AmountConverter;
򐂰 Replace the definition of the action field at the beginning of this class with the
following line:
private String action = "ListTransactions";
This will make Struts select the List Transactions option in the
accountDetails.jsp page so that it will be the default.
򐂰 Set the default value also in the reset method:
action ="ListTransactions";
򐂰 Replace the validate method with the code shown in Figure 10-18. The code
is available in:
\sg246957\sampcode\dev-struts\initial\forms\TransactionForm.txt

314 WebSphere Studio Application Developer Version 5 Programming Guide


public ActionErrors validate(
ActionMapping mapping,
HttpServletRequest request) {

ActionErrors errors = new ActionErrors();

if (action != null && action.trim().length() != 0) {


if ("Deposit".equals(action)
|| "Withdraw".equals(action)
|| "Transfer".equals(action)) {

if (amount == null || amount.trim().length() == 0)


errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError("error.missing.amount"));
else
try {
java.math.BigDecimal a = AmountConverter.fromString(amount);
if (a.compareTo( new java.math.BigDecimal(0.00) ) <= 0)
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError("error.invalid.amount"));
} catch (Exception e) {
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError("error.invalid.amount"));
}
}

if ("Transfer".equals(action)) {
if (destinationAccount == null
|| destinationAccount.trim().length() == 0)
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError("error.missing.destinationAccount"));
}
}
return errors;
}

Figure 10-18 TransactionForm validate method

This method uses the action string to determine what fields should be
validated.
򐂰 Press Ctrl-S to save this class and then close the Java editor.

Chapter 10. Developing Struts applications 315


When the form beans are implemented, they show up colored in the Web
diagram. The next step is to implement the Web pages.

Note: If deleting a component from the Web diagram, you are prompted
whether you also want to delete the underlying resource. Underlying resource
here refers to the mapping in the struts-config.xml file, not the implemented
component itself. This means that if you delete a form bean and also delete
the underlying resource, it will remove the form bean from the Web diagram
and its mapping from the struts-config.xml file. It will not, however, delete
the Java source or class file for the form bean. If you then add a new form
bean with the same name to the Web diagram and attempt to implement it, the
Finish button that you must click to create the component is deactivated in the
wizard. This is due to the fact that this class already exists, it was not deleted.

Developing the JSPs


We start by implementing the index.jsp page:
򐂰 Double-click the index.jsp page. This opens up the New JSP File dialog as
shown in Figure 10-19. The defaults are fine, so click Next.

Figure 10-19 New JSP File wizard

316 WebSphere Studio Application Developer Version 5 Programming Guide


򐂰 On the tag libraries page (Figure 10-20), you can add the tag libraries that the
JSP requires. The wizard has already added the two most commonly used
Struts tag libraries, html and bean. Our index.jsp page does not require any
other tag libraries, so click Next.

Figure 10-20 Add tag libraries

򐂰 On the tag directive page, select Create Session Variable and true
(Figure 10-21). Click Next.

Figure 10-21 JSP page directive

Chapter 10. Developing Struts applications 317


򐂰 On the next two dialogs in the wizard, you can click Next and use the defaults.
These dialogs are not Struts-dependent, so we do not explain them here. For
information about these dialogs, refer to “Creating a Web project” on
page 185.
򐂰 On the Form Field Selection page (Figure 10-22), you are asked to supply the
name of the form bean from which index.jsp should get its fields, and specify
which fields to use.
Select the customerInfoForm form bean from the pull-down menu, select the
customerNumber, and validateKey fields. The customerNumber will be an input
field and the validateKey a hidden field that is passed to the validation
routine.
Click Next.

Figure 10-22 Choosing form bean fields for index.jsp

򐂰 On the next dialog (see Figure 10-23) you can design the input form used on
the index.jsp page. Unfortunately this feature does not use the Struts tag
libraries to its fullest.
For example, if you enter customerNumber as the label for a field, what you
really would like in the JSP is <bean:message key="customerNumber"/>, so
that the corresponding text from the ApplicationResources.properties file is
displayed. The result produced by the wizard, however, is the exact text you
enter.

318 WebSphere Studio Application Developer Version 5 Programming Guide


Therefore, for the customerNumber field:
– Label: <bean:message key="prompt.enterCustomerId"/>
– Size: 20
For the validateKey field:
– Label: blank
– Initial value: 1
– Field type: hidden
Click Finish.

Figure 10-23 Designing input fields

The index.jsp is created and opened in the Page Designer.

As you can see in the editor, the wizard has inserted the two Struts tag libraries
we requested:
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>

Chapter 10. Developing Struts applications 319


It has also created an input form that prompts for the customer number and
submits it to the listAccounts action for processing:
<html:form action="/listAccounts">
<TABLE border="0">
<TBODY>
<TR>
<TH></TH>
<TD><html:hidden property='validateKey' value='1' /></TD>
</TR>
<TR>
<TH><bean:message key="prompt.enterCustomerId" /></TH>
<TD><html:text property='customerNumber' size='20' value='' /></TD>
</TR>
<TR>
<TD><html:submit property="submit" value="Submit" /></TD>
<TD><html:reset /></TD>
</TR>
</TBODY>
</TABLE>
</html:form>

The Struts <html:form> tag is used to generate the body of the input form. The
<html:text>, <html:submit>, and <html:reset> tags generate the fields and
buttons.

In the Tasks view you see an error:


Target /listAccounts does not exist in the following modules: /

This is because the form’s action refers to the listAccounts action that we have
not yet developed. This error will be fixed when we implement listAccounts.

Note: If you do not see the errors in the tasks view, it may be due to your
filtering settings in the Tasks view.

Tailoring the JSP


The index.jsp that our application uses is a little more complex than the
index.jsp page the wizard has generated for us:
򐂰 This JSP defines the two Struts tag libraries that we use:
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
򐂰 It then defines the start of the HTML section using the following tag:
<html:html>
򐂰 Change the <TITLE> tag to:
<TITLE><bean:message key="text.pageTitle"/></TITLE>

320 WebSphere Studio Application Developer Version 5 Programming Guide


This tag takes the mandatory parameter key which refers to the message in
the ApplicationResources.properties file that should be inserted. The
<bean:message> tag automatically converts any non-printable characters into
their HTML representation (for example, the ampersand character is
converted into &amp;).

Tip: You can use the JSP -> Insert Custom option to select any custom
tags from the Struts tag library. For example, for the heading:
򐂰 Select the message tag in the bean library and click Insert.

In the Properties view, set the key value to text.pageTitle.

򐂰 Under the <BODY> tag, add the RedBank text and image in the same way as in
the index.html file in “Using the Page Designer” on page 196:
<TABLE border="0">
<TBODY>
<TR>
<TD>
<H1><FONT color="red">Red</FONT>Bank</H1>
</TD>
<TD><IMG border="0" src="images/itso.gif" width="50"
height="40"></TD>
</TR>
</TBODY>
</TABLE>
򐂰 Add a heading 2 with:
<H2><bean:message key="text.welcome"/></H2>
򐂰 After the header, you can display error messages by using the <html:errors>
tag:
<html:errors></html:errors>
This tag displays the error messages returned as an ActionErrors object by a
form bean’s validate method (or placed in the request scope by an action). In
the ApplicationResources.properties file we have defined the following
special keys that applies basic formatting for the error messages:
errors.header=<P><font color="#ff0000"><strong><ul>
errors.footer=</ul></strong></font></P>
If these two keys are present, the <html:errors> tag inserts their content just
before and after the actual error messages. This makes our errors appear as
an unordered list and in red color. In the ApplicationResources.properties
file we prefix each error message with <li> so they are displayed as a
bulleted list.

Chapter 10. Developing Struts applications 321


򐂰 The <html:hidden> tag is used to supply the additional validateKey
parameter we need to determine which fields to validate:
<html:hidden property="validateKey" value="1"/>
򐂰 The <html:text> tag is used to populate the input field with the contents of
the corresponding field from the CustomerInfoForm form bean:
<html:text property="customerNumber" size="20"/>
򐂰 The submit button of the form is rendered using the <html:submit> tag:
<html:submit property="submit" value="Submit" />
We can use the <bean:message> tag to supply a label from the resources:
<html:submit><bean:message key="text.submit"/></html:submit>
򐂰 Add a footing after the form:
<P><bean:message key="text.footer"/></P>

The complete JSP is shown in Example 10-1.

Example 10-1 Complete index.jsp


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<html:html>
<HEAD>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" session="true" %>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM WebSphere Studio">
<META http-equiv="Content-Style-Type" content="text/css">
<LINK href="theme/Master.css" rel="stylesheet" type="text/css">
<TITLE><bean:message key="text.pageTitle"/></TITLE>
</HEAD>
<BODY>
<TABLE border="0">
<TBODY>
<TR>
<TD>
<H1><FONT color="red">Red</FONT>Bank</H1>
</TD>
<TD><IMG border="0" src="images/itso.gif" width="50" height="40"></TD>
</TR>
</TBODY>
</TABLE>
<H2><bean:message key="text.welcome"/></H2>
<html:errors></html:errors>
<html:form action="/listAccounts">
<TABLE border="0">
<TBODY>
<TR>

322 WebSphere Studio Application Developer Version 5 Programming Guide


<TH></TH>
<TD><html:hidden property='validateKey' value='1' /></TD>
</TR>
<TR>
<TH><bean:message key="prompt.enterCustomerId" /></TH>
<TD><html:text property='customerNumber' size='20' value='' /></TD>
</TR>
<TR>
<TD><html:submit><bean:message key="text.submit"/></html:submit></TD>
<TD><html:reset /></TD>
</TR>
</TBODY>
</TABLE>
</html:form>
<P><bean:message key="text.footer"/></P>
</BODY>
</html:html>

Application Developer Struts tools also provide real-time rendering of the Struts
tags. Switch to the Design view of the Page Designer to see what the JSP will
look like (Figure 10-24).

Figure 10-24 Rendering Struts tags in Design view

򐂰 Save and close the index.jsp file.

Chapter 10. Developing Struts applications 323


򐂰 Compare your code with the sample code in:
\sg246957\sampcode\dev-struts\solution\jsp\index.jsp

Note: The rendering of the Struts tags can be customized using the Window
-> Preferences -> Web tools -> Struts tools -> Page Designer Struts Support
dialog. The options available are self-explanatory so we do not cover them
here.

The listAccounts.jsp, accountDetails.jsp, and listTransactions.jsp files


are all implemented using the same method. However, listAccounts.jsp and
listTransactions.jsp require an additional Struts tag library, the logic library.
򐂰 Implement these pages in the same way as you did with index.jsp.
򐂰 When you reach the second page of the New JSP File dialog (see
Figure 10-20 on page 317), click the Add Tag Library button.
򐂰 On the Select a Tag Library page, select the /WEB-INF/struts-logic.tld tag
library and enter logic as its prefix. Then click OK (Figure 10-25).

Figure 10-25 Add Struts logic tag library

324 WebSphere Studio Application Developer Version 5 Programming Guide


Implementing the listAccounts JSP
Here are short instructions for the listAccounts JSP:
򐂰 Start the wizard, add the logic tag library, and proceed to the form fields.
򐂰 Select the customerInfoForm.
򐂰 Select the validateKey, accountNumber, and customerName properties.
– accountNumbers—Field type: radio, label:
<bean:message key="prompt.account" />
– validateKey—Field type: hidden, no label, initial value 2
– customerName—Field type: hidden, no label
򐂰 Create the JSP and the editor opens.
򐂰 Find the <jsp:useBean> tag for the customerInfoForm and replace the line
with the following:
<bean:define id="customerInfoForm" name="customerInfoForm"
type="itso.strutsweb.forms.CustomerInfoForm" />
򐂰 Change the title:
<TITLE><bean:message key="text.pageTitle"/></TITLE>
򐂰 Create a heading with the customer’s name:
<H2><bean:message key="text.customersAccounts"
arg0="<%=customerInfoForm.getCustomerName()%>" /></H2>
򐂰 Display error messages after the heading:
<ht