Websphere5 0
Websphere5 0
Websphere5 0
Learn by example
Carla Sadtler
Justin Bogers
Shailen Borkar
Andri Firtiyan
ibm.com/redbooks
International Technical Support Organization
September 2003
SG24-6555-01
Take Note! Before using this information and the product it supports, be sure to read the
general information in “Notices” on page xiii.
This edition applies to WebSphere Application Server - Express V5.0.2 for use with the Windows
2000 and Linux Operating Systems.
Notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii
Trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiv
Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
The team that wrote this redbook. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xv
Notice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Comments welcome. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Contents v
8.3 Using JSPs in the Online Catalog sample. . . . . . . . . . . . . . . . . . . . . . . . 265
Contents vii
13.1.1 Configuration and management . . . . . . . . . . . . . . . . . . . . . . . . . . 456
13.1.2 Managing test application servers. . . . . . . . . . . . . . . . . . . . . . . . . 457
13.2 Using the Server tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
13.2.1 Setting preferences for the Server perspective . . . . . . . . . . . . . . . 460
13.3 Defining servers and server configurations . . . . . . . . . . . . . . . . . . . . . . 462
13.3.1 Server types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
13.4 Using the Express test environment . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
13.4.1 Creating a server and server configuration . . . . . . . . . . . . . . . . . . 466
13.4.2 Publishing an application to the test environment . . . . . . . . . . . . . 468
13.4.3 Updating the server configuration for the application . . . . . . . . . . 470
13.4.4 Starting the test environment server . . . . . . . . . . . . . . . . . . . . . . . 471
13.4.5 Running the application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
13.5 Working with an Express server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
13.5.1 Defining the server to Studio Site Developer . . . . . . . . . . . . . . . . 476
13.5.2 Publishing the application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
13.5.3 Updating the server configuration for the application . . . . . . . . . . 482
13.5.4 Starting the Express server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
13.5.5 Running the application. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
13.6 Working with server configurations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
13.6.1 Classloaders and file location . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
13.7 Server operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
13.7.1 Starting the server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
13.7.2 Stopping the server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
13.7.3 Restarting the server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
13.8 Deploying applications for production . . . . . . . . . . . . . . . . . . . . . . . . . . 489
13.8.1 Exporting an enterprise application to a file location. . . . . . . . . . . 489
13.8.2 Exporting an enterprise application using FTP . . . . . . . . . . . . . . . 490
13.9 IBM Agent Controller settings and status . . . . . . . . . . . . . . . . . . . . . . . 491
13.10 For more information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 492
Contents ix
16.5.1 Adding JAAS authentication to a server . . . . . . . . . . . . . . . . . . . . 571
16.5.2 Setting up a datasource using JAAS. . . . . . . . . . . . . . . . . . . . . . . 572
16.6 Securing the IBM Agent Controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
16.6.1 Implementing SSL for IBM Agent Controller communications . . . 574
16.6.2 Importing a security certificate into the Workbench . . . . . . . . . . . 576
16.7 Using SSL with applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
16.8 For more information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 580
Contents xi
xii IBM WebSphere Application Server - Express V5.0.2 Developer Handbook
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.
™ Cloudscape™ Perform™
^™ CICS® Rational Rose®
Redbooks (logo) ™ DB2® Rational®
developerWorks® Informix® Redbooks™
ibm.com® IBM® VisualAge®
iSeries™ MQSeries® WebSphere®
AIX® OS/400®
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.
This IBM Redbook introduces IBM WebSphere Application Server - Express V5,
an IBM offering that provides a comprehensive development tool and a
single-server application server environment designed for the small and medium
business customers who want to have a Web presence for their business. It
provides development tools and application server capability in a single offering.
IBM WebSphere Application Server - Express V5 users can develop and test
applications using WebSphere Studio Site Developer, then test and deploy
applications on a lightweight version of IBM’s WebSphere® Application Server.
We refer to this lightweight server as the Express Application Server.
This redbook guides you through the process of developing and testing
applications. It gives you an overview of Studio Site Developer and how it
supports the technology required to build effective Web applications. It provides
information on how to use the tools and takes you through the process of building
and testing Web applications.
The focus of this book is on the development process. For information about
server administration, see WebSphere Application Server - Express V5.0.1
Administrator Handbook, SG24-6976.
Andri Firtiyan is an IT Specialist with the IBM Software Group based in Jakarta,
Indonesia. He has seven years of experience in the entire application
development life cycle and for the last two years has been involved in presenting
and demonstrating various WebSphere technology to IBM customers. He holds a
Masters degree in Computer Science from the University of Indonesia. His areas
of expertise include WebSphere and MQSeries® family products.
Peter Kovari
International Technical Support Organization, Raleigh Center
Mark Edwards
IBM Raleigh
Kevin Postreich
IBM Raleigh
Moji Trasti
IBM Raleigh
Tim DeBoer
IBM Toronto
Ian Brown
ASTECH Solutions Inc.
Comments welcome
Your comments are important to us!
Preface xvii
xviii IBM WebSphere Application Server - Express V5.0.2 Developer Handbook
1
Web
Services
Data Access
Cloudscape
DB2
CVS
SQL
Repository Oracle Server
Web applications can be tested in the Studio Site Developer test environment
and then deployed to the Express Application Server.
Express Application Server can be installed on the same system as Studio Site
Developer or on a separate system. A Web-based administrative console is
provided to configure the server environment. Administration and operation can
also be performed using the server tools in Studio Site Developer, but this is
primarily for development testing purposes.
For specific database support information, see the IBM WebSphere Application
Server - Express v5.0 Installation Guide (which is shipped with the project).
A Web server plugin is provided with Express Application Server that can be
installed with supported Web servers. The plugin allows you to use an external
Web server that serves the HTML content of an application and directs requests
for servlets and JSPs to the Express Application Server. The Express Application
Server administrative console is used to generate and maintain the HTTP plugin
configuration file needed to route incoming requests.
This book will discuss testing and deploying applications from a developer’s point
of view. This means that we will cover using the server tools of Studio Site
Developer. This is a perfectly acceptable way of configuring and managing both
the embedded test environment and remote servers. As you move into the
production environment, it is more likely that you will want to use the
administrative console for managing the production server. The administrative
console exposes more configuration options and is browser-based, meaning you
don’t have to have Studio Site Developer installed on the machine in order to
manage an Express Application Server.
Important: This doesn’t mean that you need this many people. All of these
roles can easily be performed by one person. It is simply easier for us to
distinguish which “hat” that person is wearing at the time.
You will find the following Web sites, books, and articles useful as you develop
and deploy applications for WebSphere Application Server - Express.
General information
To find information on IBM products, see the following sites:
The IBM Redbooks site at the following URL:
http://www.ibm.com/redbooks
The WebSphere Developer Domain Web site at the following URL:
http://www.ibm.com/websphere/developer
Installation
Installation information can be found in the following locations:
WebSphere Application Server - Express V5.0.1 Administrator Handbook,
SG24-6976
– Location: The IBM Redbooks site at the following URL:
http://www.ibm.com/redbooks
– Content: An overview of the different ways to set up a WebSphere
Application Server - Express, planning information, and installation
scenarios.
Express readme file
– Location before installation: launchpad.exe on the installation CD-ROM.
– Location after installation: Start -> Programs -> IBM WebSphere
Application Server -> Express v5.0.2 -> README or
<express_install>/readme.html.
– Content: The main readme contains information about the product, known
problems and limitations, and links to installation information and release
notes.
IBM WebSphere Application Server - Express v5.0 Installation Guide (which
is shipped with the project)
– Location before installation: launchpad.exe on the installation CDROM.
– Location after installation: Link from the Express Readme or
<express_install>/install.htm.
– Content: The install guide contains information to help you install the
product, including hardware requirements, software requirements, and
install instructions.
Migration
For information on migration issues, see:
IBM WebSphere Studio Site Developer Version 5.0 Migration Guide (which is
shipped with the project)
– Location before installation: launchpad.exe on the installation CDROM.
– Location: <express_install>/migrate.html.
– Content: Information on migrating from previous versions of WebSphere
Studio or VisualAge® for Java.
Problem determination
For problem determination information see the support site at:
http://www.ibm.com/software/webservers/appserv/express/support.html
Note: Throughout this publication there are references to specific file locations
within WebSphere Application Server - Express. We will use the following
terminology:
<express_install>: Refers to the high-level installation directory, for
example, C:\WebSphere\Express502 on Windows or
/opt/IBM/WebSphere/Express502 on Linux
<server_install>: Refers to the installation directory for Express
Application Server, for example, C:\WebSphere\Express502\AppServer on
Windows or /opt/IBM/WebSphere/Express502/AppServer on Linux
<studio_install>: Refers to the installation directory for Studio Site
Developer, for example, C:\WebSphere\Express502\SiteDeveloper on
Windows or /opt/IBM/WebSphereStudio on Linux
<rac_install>: Refers to the installation directory for the IBM Agent
Controller, for example, C:\WebSphere\Express502\RAC on Windows or
/opt/IBMRAC on Linux
When using this notation, we will use a generic indicator for the directory
structure (forward slashes for all operating systems, versus using a backslash
for Windows.)
If you haven’t installed WebSphere Application Server - Express yet, you should
see WebSphere Application Server - Express V5.0.1 Administrator Handbook,
SG24-6976 for planning and installation approach information.
The first place to start when getting familiar with WebSphere Application Server -
Express is with Studio Site Developer.
1. To get started, bring up Studio Site Developer:
– Windows: Select Start -> Programs -> IBM WebSphere Application
Server-Express V5.0.2 -> Studio Site Developer.
– Linux: /opt/IBM/WebSphereStudio/wasexpress.
2. The first time you open Studio Site Developer you will be asked to select a
location for the workspace. You can take the default or choose a folder name.
You can use these sample applications as a basis for your own application or as
a reference when coding new applications. You can also use these as a learning
tool. Each sample has a readme file that will describe how to do the base setup
for the application and will point you to instructions for modifying the sample to
add new features.
Among the examples included are five that were specifically developed to
illustrate the capabilities of WebSphere Application Server - Express:
Document management application: the application allows you to store and
retrieve documents from the server’s file system. Users of the system fall into
one of the following categories: administrator, publisher, or consumer. The
sample illustrates techniques for a simple login and user role scheme, storing
and retrieving files from the server, database searches (both new and “search
on previous search results”). Modification scenarios included are:
– Using SSL
– Adding e-mail
– Encoding stored passwords
Survey application: this application has two parts. The first provides a voting
booth. Web users can vote on an issue and the votes are tallied for display.
Second, the user can fill out a survey. The user can customize the application
by selecting a language for the interface to be displayed in. The sample
4. Click Finish.
The application will be brought into your workspace where you can begin
exploring its features. The first thing you will see is an introduction to the
application. The introduction is presented in a Web browser window within
Studio Site Developer.
5. Read the introduction. It will describe the function of the application and tell
you how to deploy the sample to the WebSphere test environment.
6. Deploy the sample (the instructions are in the introduction) and try it out. If
you like what you see, explore the application elements. The best way to get
started with this is to first become familiar with the Studio Site Developer
environment by browsing through Chapter 3, “Using Studio Site Developer”
on page 43.
To begin, select File -> New->Template Application. You will see a list of
available templates. Click each one to see a description of the template. There
are also additional templates available from a Web site. You can see these by
clicking the Download button.
User information was not stored directly in our application database. Since
WebSphere provides functionality to store user profiles in a predesigned
SALESAPP database, we decided to make use of this feature to simplify the
implementation of an authentication mechanism and storage of user-related
data.
HTTP(S)
320
TCP/IP Enterprise
Web server,
Information
Application server,
Systems
Transaction server,
Servlets, JSP,
Thin client, Business Logic
Browser Beans, Data Access
Beans, Connectors
Netscape/IE,
PDA,
Mobile phones,
HTML pages,
Web TV
First tier
The main function of the client in this model is to present information and results
produced by an application to the user. In this system model, the clients are
sometimes referred to as thin clients. This means that little or no application logic
is executed on the client and, therefore, relatively little software is required to be
installed on the client.
Second tier
Middle-tier servers include a standards-based Web server to interact with the
client tier and define user interaction, and a Web application server to execute
business logic independently of the client type and user interface style. The Web
application server is the platform that provides the runtime environment for the
application's business logic. It is implemented using various Internet and Java
technologies, including the HTTP server and the Enterprise Java services that
enable rapid development and deployment of applications in a distributed
network environment.
Java servlets, JavaServer Pages, and Enterprise JavaBeans are examples of the
components deployed in the Web application server. These server-side
components communicate with their clients and other application components
via Hypertext Transfer Protocol (HTTP) or IIOP, and use the directory and
security services provided by the network infrastructure. They can also leverage
database, transaction, and groupware facilities.
Third tier
The Enterprise Information System (EIS) tier includes new and existing internal
applications, services, data, and external applications.
Connectors provide the link between the new business logic in the middle tier to
the vast accumulated assets in a company's existing applications and data
systems.
The IBM Patterns for e-business effort does just this. Its purpose is to capture
e-business approaches that have been tested and proven. The information
captured is thought to fit the majority of situations. By making these approaches
available and classifying them into useful categories, we save the e-business
planners, architects, and developers both time and money.
These approaches are further refined into useful, tangible guidelines. The
patterns and their associated guidelines allow the architect to start with a
problem and a vision, find a conceptual pattern that fits this vision, define the
necessary functional pieces that the application will need to succeed, and then
actually build the application using coding techniques outlined in the guidelines.
The IBM Patterns for e-business Web site (below) contains the information and
references you need to design and build a solution from beginning to end.
http://www.ibm.com/developerworks/patterns/
The Unified Modeling Language (UML) is the industry standard language for
modeling software systems, providing practice for modelling large complex
systems. Although WebSphere Application Server - Express is geared toward
simpler applications, it is a good idea to become familiar with UML and to use it
as a basis for designing your applications. More information about UML can be
found at:
http://www.omg.org
In UML, diagrams are used to model a solution. The most basic is the use-case
diagram. Use cases are a way to illustrate to the user/developer functionality of a
system. The two main components of a use-case model are actors that represent
external elements and use cases that represent functions provided by the
system.
Note: Throughout this publication, we will use a sample called the Online
Catalog to illustrate the various features of WebSphere Application Server -
Express. The application will be a simple one that provides a means of
publishing an inventory of goods on the Web and allowing customers to place
orders via e-mail or by phone.
Actors
The first step in designing the application flow is to determine who will be
interacting with the application and what types of activities they will perform. The
people that interact with the application are known as actors in UML and are
represented by a stick figure in the following figures, as shown in Figure 2-2.
A c to r
As you can see, in our example these actors are fairly simple and distinct. The
function of each within the application appears to be different, based on the
names. If the distinction is not as clear in your application, consider things such
as security levels or training required for the user.
Use cases
Use cases depict interaction between the actor and the system. They represent
functionality available to an actor. A collection of transactions that can be
identified as a unit of work is a good candidate for a use case. Use cases are
depicted by a ellipse in UML notation, as shown in Figure 2-3.
Use Case
Figure 2-3 UML notation of a use case
Use-case model analysis usually starts with an overall main use-case diagram
with actors and major use cases. In the case of our sample application, we see
two main interaction types with the application. These two interactions are
identified as:
Maintain inventory
Buys item
Figure 2-4 on page 25 shows the main use-case diagram for our sample. You
can see the major use cases and the relationship with the actors.
B u s in e s s O w n e r
B u y s It e m
B uyer
The model can then be decomposed into more detailed use cases, as shown in
Figure 2-5.
Business Owner
Buy Item
Validate Buyer
Login
View Items
Register
Request Info
Buyer
The buys item use case has been broken down into the possible activities the
customer can perform, including:
View items
Buy item
Register
Requests info
Using these technologies, applications can range in complexity from very simple
applications that return simple data from local resources, to very complex
applications that perform many tasks, including interacting with other
applications.
Over time, two programming models have emerged that are often referred to as
Model 1 and Model 2 architecture. Model 1 architecture is more suited to small
applications where separation of presentation from business logic activities
seems to introduce more complexity than is needed. Model 2 architecture
addresses the more complex applications where separation of tasks becomes
the best method of building efficient, maintainable applications.
Application Server
1
Request
Browser 2
JSP Database
Response
For small projects, prototyping, and to quickly get an application completed, the
Model 1 architecture is quite popular because of its ease of development.
However, more complex applications will need to follow a different approach.
That approach is described as Model 2 architecture.
1 Int
2
Input Page Request
Serlvets era
ct ive
(View) (Control)
3 JavaBean
(Model) Database
Display Page
Display Page JSP
(View) Response
(View) 4
5
Model 1 versus Model 2: It is not the intention of this publication to single out
any one model as being better than the other. For the purposes of WebSphere
Application Server - Express and the targeted market of WebSphere
Application Server - Express, the Model 1 architecture is better suited. As
mentioned earlier, Model 1 architecture lends itself towards small projects that
can be developed quickly or when development teams do not have strong
Java servlet skills. That said, it is important to note that using the Model 1
architecture will hinder future scalability of applications. Extending the
application using Model 1 architecture becomes difficult since the page
presentation is so tightly coupled to the business logic. If a project is planned
for future growth, then a Model 2 or MVC architecture is recommended and
encouraged. It may be beneficial to “pay now versus pay later” to gain the
flexibility provided by the MVC design pattern.
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.
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 public interface that
is well defined and as simple as possible. 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. Fewer dependencies
means more freedom to adapt to new requirements.
Chances are that you have answered no to all of the questions above. What is
the advantage of not knowing how TVs represent their data and implement their
operations? You could buy a new TV, which does these things internally in a
completely different way, and you could still change channels.
Figure 2-8 on page 31 shows the model layer with its encapsulated business
domain objects and the exposed facade object.
Façade
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.
Controller
The controller’s responsibility is to capture user events and to determine which
actions each of these events implies, 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.
Controller View
Model
2.4.1 JavaScript
Browser-based or client-side JavaScript is common. WebSphere Application
Server - Express also supports server-side JavaScript through the Bean
Scripting Framework (BSF) of the Express Application Server.
BSF enables you to use scripting language functions in your Java server-side
applications. This framework also extends scripting languages so that you can
use existing Java classes and JavaBeans in the JavaScript language. With BSF,
you can write scripts that create, manipulate, and access values from Java
objects, or you can write Java programs that evaluate and access results from
scripts. BSF provides an access mechanism to Java objects for the scripting
languages it supports, so that both the scripting language and the Java code can
access code exclusive functions. The access mechanism is implemented
through a registry of objects maintained by BSF.
2.4.2 Servlets
Java servlets are Java alternatives to Common Gateway Interface (CGI)
programs. As with CGI programs, Java servlets can respond to user events from
an HTML request, and then dynamically construct an HTML response that is sent
back to the client. Java servlets have the following advantages over traditional
CGI programs:
Java-based
Because Java servlets are written in Java, they inherit all the benefits of the
Java technologies.
Persistence and performance
A servlet is loaded once by a Web server and invoked for each client request.
Java servlets do not incur the overhead of instantiating a new servlet with
each request. CGI processes typically must be loaded with each invocation.
Java servlets can work better than CGI programs, especially for business logic
and control flow.
However, for a servlet to return an HTML page to a browser, it must output HTML
from within the Java code. A Java programmer has to write many out.println
statements to return the HTML. This mixes the roles of the content developer and
the Java programmer, even limiting the usefulness of content-authoring tools.
While JavaServer Pages look like HTML pages that access dynamic data, they
are actually Java servlets. The application server compiles JavaServer Pages
and executes them. Being a servlet is what allows JavaServer Pages to easily
add dynamic content.
However, while JavaServer Pages are good for producing HTML, they are not
good for writing business logic and control because having Java code inside
JavaServer Pages could easily make them hard to read or maintain.
Tag libraries reduce the necessity of embedding large amounts of Java code in
JSP pages by moving the functionality provided by the tags into tag
implementation classes. In doing so, tag libraries make authoring JSP pages
easier, both for the Web page author and for tools that expose the functionality
encapsulated by the library to the author.
Finally, JSP tag libraries are portable; they can be used by any JSP page
independent of the page's scripting language, any authoring tool supporting tag
libraries, and any JSP 1.1-compliant server.
2.4.5 XML
eXtensible Markup Language (XML) is a markup language for the exchange of
structured documents. It is a meta-language, meaning a language for defining
other languages. XML by itself does not define any tags; it provides a facility to
define custom tags and the structural relationships between them.
These services can be new applications or just wrapped around existing legacy
systems to make them network-enabled. Services can rely on other services to
achieve their goals.
Struts also provides utility classes to support XML parsing, automatic population
of JavaBeans properties based on the Java reflection APIs, and
internationalization of prompts and messages.
A typical Struts Web application has a single servlet that uses an XML file for
configuration information. There will be multiple action classes and JSPs (using
the Struts taglibs).
In this section, we will explain some database concepts that need to be applied
to create a sound, efficient data model.
2.5.1 Normalization
Normalization is the process of determining the structure of database tables. The
objective is to introduce flexibility into the structure, while reducing redundant
data. The reduction in data can improve the performance of update and delete
statements, since the data is only touched once. By normalizing data, you try to
ensure that all columns in the table depend on the primary key.
There are four levels or degrees of normalization. We will limit our discussion to
the third normal form for the sake of simplicity and to be within the scope of this
publication.
In Table 2-1 we can see that the DeptName column is dependent on the DeptNo
column. This table does not conform to the third normal form. If we update
DeptName for one employee, it would not automatically update the DeptName
column for other employees belonging to the same department
Table 2-1 Table not in third normal form
EMPNO(Primary Key) LastName DeptNo DeptName
To normalize this data to conform to the third normal form, we would create two
tables. The first table, Table 2-2, contains the relation between the employee and
the department number. The second table, Table 2-3, contains the relation
between the department number and the department name. An update to the
department name only needs to be done once.
Table 2-2 Table in third normal form
EMPNO(Primary Key) LastName DeptNo
001 Brown 01
002 Smith 02
01 Support
02 Sales
One consideration when normalizing tables is that the more you normalize, the
better it results in insert and update performance. However, it can slow down the
query response time.
2.5.2 Indexes
Indexes are used to improve query performance. They provide a faster
mechanism to search the database table for a particular column value(s) and
avoid expensive and slower table scans. Columns of a table that are often used
in search clauses are prime candidates for indexes. The downside of indexes is
that they take up disk space and slow execution of insert and update statements.
We came up with the following entities that map to the business requirements of
the Online Catalog sample.
Customer: This entity contains all attributes/information about a buyer who
buys from the online store.
Item: This entity contains all attributes/information about items on sale in the
online store.
ShippingOrder: This entity contains all information needed to complete a
shipping order.
Users: This entity contains the user name/password of all admin users.
The data model of the tables required by the Online Catalog sample is shown in
Figure 2-10 on page 40.
USERS
ORDER_NUMBER : INTEGER
CUSTOMER_ID :CHAR(10)
USERNAME :CHAR(8) ITEM_NUMBER :CHAR(5)
PASSWORD :CHAR(8) QUANTITY :INTEGER
SALE_PRICE :DECIMAL(9,2)
ORDER_DATE :DATE
STATUS :CHAR(1)
SHIPPING_ORDER
Figure 2-10 Data model for the Online Catalog sample application
As you proceed through the publication, you will see how the database built
based on this model is used by the application.
This chapter will introduce the Studio Site Developer workbench and its features.
The topics covered are:
Workbench overview
Perspectives, views, and editors
The workspace
Finding help
Recovering files
In this window, you also have the option of suppressing the message on future
startups and always using the current directory you specify.
Tip: If you choose to suppress the workspace option at startup, you can
change your mind later. Simply start Studio Site Developer with the following
commands:
cd <studio_install>
wasexpress -setworkspace
Since there is a memory overhead associated with having multiple projects in the
workspace at the same time, you may wish to configure multiple workspaces for
different projects. This reduces the amount of clutter in the navigator views, and
also minimizes the number of entries in the Server control panel, making it easier
to find a particular server configuration or instance. Each workspace is created
as a separate folder in the file system.
For example:
wasexpress -data c:\user-workspace
A history of all files that you have changed is cached locally. This allows you to
compare a resource with a previous version and, if required, replace it with that
version. The local history of each file is updated when you create or modify a file.
Each time you save a file, a copy of its previous state is also saved. A new history
for a resource is created the first time you modify the base version of it.
This allows you to compare the current file state to a previous state and to
replace the file with a previous state. Each state in the local history is identified
by the date and time the file was saved.
Each version kept in the local history is listed at the top. Select the listing to
compare that version with the current copy. The differences are highlighted in the
window below.
3.2 Perspectives
Perspectives provide different ways of viewing and working with resources. A
perspective consists of a set of views, editors, and toolbar options suited to the
task most likely performed within that perspective. For example, the Server
perspective is designed with server or unit test environment operation in mind.
There is a view for the server console, a view that shows server configurations, a
view that allows you to start and stop servers, and so forth. The Web perspective
is designed for a Web application developer and, by default, views and tools are
available that are most suited for that task.
For example, Figure 3-4 on page 48 shows the default layout for the Web
perspective. The Web perspective is used primarily to develop Web application
resources, such as HTML and JSP files.
Open perspective
Each pane you see in Figure 3-4 represents a view, and the tabs you see below
the panes can be used to toggle that pane to show another view. Note that there
are several views visible and some that are not. The toolbar at the top will contain
tools relevant to the perspective and view. As you change perspectives or views,
you will see the toolbar change also.
For example, the top right pane in this perspective is the editor area. In this area
you can see a JSP open in the Source view. By selecting the tab at the bottom of
the pane, you can see the same file using the Design view, which presents a
graphical view of the file. Multiple files can be open simultaneously for editing.
The workbench window can have several perspectives opened, but only one is
visible at one point in time. You can switch easily between perspectives by
clicking the different icons in the shortcut bar.
Among the predefined perspectives you will find in Studio Site Developer are
those listed in Table 3-1. These are the perspectives we found to be the most
commonly used during Web application development in a WebSphere
Application Server - Express environment.
Table 3-1 Perspectives
Perspective Task
Web For building HTML and JSP files. This is the primary
perspective used for application development in WebSphere
Application Server - Express, and you will see it used
throughout the publication.
CVS Repository For team development tasks using Concurrent Version System
(CVS). You will see this perspective used in Chapter 15,
“Development in a team environment” on page 515.
Server For configuring and operating the runtime test and production
environments. You will see this perspective used in Chapter 13,
“Deploying applications” on page 455.
XML For working with XML resources. You will see this perspective
used in Chapter 10, “Working with XML” on page 309.
Perspectives can easily be customized to suit your needs and just as easily reset
to their original configuration. You can also compose your own perspective by
defining the views it should contain. You will see the more commonly used
perspectives in more detail in the appropriate chapters.
3.2.1 Editors
Resource types used in Web applications have default editors associated with
them. When you double-click a resource in the workbench the associated editor
for that type opens the file for editing. For example, in Figure 3-4 on page 48, the
active editor is the Page Designer, which is associated with JSP and HTML files.
If no editor is currently associated with a particular file extension, the Workbench
checks to see if there is one associated in the operating system and, if so, uses
that editor to open the file.
You can change or add editors associated with a file extension using preference
settings:
You can have multiple resources that use different editors open simultaneously.
Switching between them in the editing pane is as easy as selecting the file name
on the top bar above the editor area. If there is an asterisk (*) to the left of the file,
it means that it contains unsaved changes.
Tip: When you open a file and then switch perspectives, Studio Site Developer
will keep the file synchronized between the perspectives. To conserve system
resources it is good practice to do the following:
Close perspectives that you do not need.
Do not open multiple perspectives of the same type (it is allowed).
Close resources open in the editor area when you no longer need them
open.
This setting says that if you are in a perspective and open a view (Window ->
Show View) that is not in the perspective, the view will be opened temporarily in
the perspective. An icon representing the view will show in the shortcut bar on
the left. The view will only remain in sight as long as it is current (you have the
cursor in it). If you move the cursor outside the view and click, the fast view will
disappear. You can bring it back by selecting the icon.
For example, in Figure 3-5 on page 51, we have opened the Java Hierarchy view
from within the J2EE perspective. The view initially opens in the left half of the
perspective and an icon is placed in the shortcut bar.
New icon
You can also designate views in the perspective as fast views. This effectively
removes them from the perspective and puts an icon in the shortcut bar. To do
this right-click the title bar of the view and select Fast View. For example, if you
took the Properties view in Figure 3-5 and made it a fast view, you would no
longer see the Properties tab, but would instead see an icon for the view in the
toolbar (see Figure 3-6 on page 52). The view would only be active when you
select the icon. Moving the cursor to another view would hide the view.
New icon
The fast views are only defined for the current perspective and will only exist as
long as the perspective is open. This does not mean that you cannot switch from
perspective to perspective without losing the fast view, but if you select the
perspective in the shortcut bar, right-click, and select Close you will.
If you want to retain the fast views across Studio sessions, you should save the
perspective.
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 cannot dock the floating view at this point.
Double-clicking the title bar of a view to make it fill the window. Double-click
the title bar again to return it to normal size and position.
Adding views. You can add a view by doing the following:
a. Open the perspective you want to customize.
b. From the main menu bar, select Window -> Show View.
c. Select the view you want to add and click OK.
d. The view will dock in its default position but can be moved to any location.
Saving the perspective either by overlaying the original definition or under a
new name by selecting Window -> Save Perspective As.
Important! Until you are confident that you want to permanently change
the perspective, we recommend that you save it as a new perspective.
Once you overlay a perspective definition, you cannot reset it to its original
state.
To reset a perspective to its saved state, select Window -> Reset Perspective
from the main menu.
To synchronize the navigation frame with the current topic, you can click the
Show in Table of Contents button. 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.
Note: Throughout this publication you will see the terms Web module, Web
application, and Web project. For the context of this publication they all mean
the same thing and are used interchangeably. The same is true for the terms
enterprise application, enterprise application project, and enterprise
application module.
WebSphere Application Server - Express does not support EJB modules, so the
typical enterprise application built and deployed with WebSphere Application
Server - Express will consist primarily of Web modules and supporting JAR files.
As you can see, the deployment descriptor is in XML format. The application
element is the root element and contains information about the enterprise
application and its elements. The module element represents a single J2EE
module, which can contain EJB, Web, or Java elements. You can also see the
security-role element that contains the J2EE roles to be used for application
security.
The specification also defines a hierarchical structure for the contents of a Web
application that can be used for deployment and packaging purposes. Many
servlet containers, including the one provided by Express Application Server,
support this structure.
Directory structure
The directory structure for a Web application requires the existence of a
WEB-INF directory. This directory contains Java and support classes that contain
application logic. Access to these resources is controlled through the servlet
container, within the application server.
Servlet2.class Servlet3.class
Although there are no other requirements for the directory structure of a Web
application, we recommend that you organize the resources in separate logical
directories for easy management; for example, an images folder to contain all
graphics.
All the Java components of the same Web application share information and
have access to the same pool of resources. This information is encapsulated in
the servlet context provided by the servlet container. Since there is one and only
one servlet context per Web application, servlet instances of a Web application
will point to the same ServletContext instance.
An application server can contain many Web applications with every Web
application rooted to a specific path. The server manages a servlet context for
each of these Web applications.
The server is responsible for encapsulating the data sent by the client into an
HttpServletRequest object. This task includes identifying the following elements,
obtained from the client’s request for a URL:
Context path: The path prefix leading to the Web application. This context
path is associated with the servlet context of the application.
Servlet path: The section of the requested URL that directly corresponds to
the mapping that activated this request. Typically, mapping consists of
The servlet will have access to these elements that can be configured on the
deployment descriptor or later on the servlet container for each Web application.
We recommend that you start by creating the Web project and let that wizard
create the enterprise application project for you.
3. Click Next.
4. Click New... beside the EAR Project listbox.
8. Click Next.
Tip: You have several Web Project Features to choose from. These are for
your convenience and can be selected after the Web project has been
created. To access the Web Project Features, select your Web project and
then select Project -> Properties from the main menu. From the
Properties window, select Web Project Features. The Available Web
Project features list allows you to select the available features for your Web
project.
9. Select JSP Tag Libraries to include all the supported tag libraries to the
project.
10.Click Next.
Important: A new feature of the New Web Project wizard allows you to
select a default template for your project. Once selected, the template will
be applied to any new pages created using Web Site Designer. Web Site
Designer can be accessed by expanding your Web project and
double-clicking Web Site Configuration from the project directory
structure.
11.Select the Use a default Page Template for the Web Site check box.
12.Select the Sample Page Template radio button.
13.From the Thumbnail selection box, scroll down to and select B-01_blue.htpl.
14.Click Finish.
The new Web project will be created. This includes the appropriate directory
structure, the style sheet, and Web deployment descriptor. A module entry for
this Web module is added to the enterprise application deployment descriptor.
The Template Application Wizard (File -> New -> Template Application) guides
you through the process of selecting a template, customizing it, and generating
the application. The wizard allows you to select a template from the library, from
custom templates that you have created and saved, or from the Web using a
download button that takes you to the Web site.
The toolbar and drop-down options at the top give you easy access to tools and
wizards designed to make building Web applications easy. The items in the
toolbar change based on the active editor and resource. You can control the
options you see to some extent by modifying the toolbar viewing options in the
Toolbar drop-down.
The default views in the Web perspective are designed and positioned for
optimum efficiency. Note that the default layout for perspectives tends to change
over time from one product release to another. This can be due to new views,
usability feedback, or just the fact that developers have discovered a more
convenient and popular way of doing things. In Studio Site Developer V5.1, the
Web perspective has the following views in its default layout:
Project Navigator
Gallery
Struts Explorer
Attributes
Styles
Thumbnails
Quick Edit
Tasks
Colors
Servers
Palette
Snippets
Other views may appear as you perform tasks. For example, the first time you
test an application and use the Servers view, the Console view will appear.
We will discuss a few of the default views briefly here, and in addition, a few other
views that we find helpful in working with Web applications. For information about
adding views and rearranging the views on your workspace, see 3.2.3,
“Customizing perspectives” on page 52. The descriptions of all views can be
found in the Studio help text.
The structure shown in the navigator aligns with the structure of J2EE enterprise
and Web applications.
Attributes view
The Attributes view shows you the attributes of the selected element in the editor
and allows you to change them. For example, if the cursor in the editor is within a
table tag, you will see table attributes in the Attributes view. You can set things
like the table or cell background colors, text alignment within the cell, and the size
of the cell. If the cursor is within a link, the attributes will show you the URL to link
to, the window to open, and other link attributes.
In Figure 5-1 on page 78, the cursor in the editor area is immediately after the
<BODY> tag. In the Attributes view, you have access to the attributes you can set
for that tag. If the cursor was situated within a table, the Attributes view would
look like Figure 5-2.
When you open any of the folders in the Gallery view, the available files are
displayed in the Thumbnail view.
Gallery view
Thumbnails view
The Gallery view, working together with the Thumbnail view, allows you to easily
add or apply the files available in the gallery to your HTML file. To use the gallery:
1. Open the folder (for example, the Image folder) in the Gallery view.
If you select a style sheet (.css) file, the new style will be applied to the target
page, and a link to the style sheet will be added to the HTML source in the proper
location.
Links view
The Links view shows Web pages that link to the current file, and the Web pages
that the open file links to. The Links view is an important tool in keeping track of
the overall flow of the application and in maintaining the integrity of the links in
the application.
The current file is the focus (center) of the view. Which file is current depends on
where the cursor is. If the cursor is positioned in a file in the editor area, then that
file is current and will be in the center of the Links view. If you have selected a file
in the Project Navigator view, that file is current.
You can open any of the files in the view by double-clicking their icon. Opening a
new file, changes the Links view so that the new file is current. Holding the cursor
over a file will give you a pop-up showing you the full directory location. A “+” icon
means that the file has links that aren’t displayed in the view. You can display
them click clicking the plus sign.
In Figure 5-4, you can see that AddNewItem.jsp is the current file (it is situated in
the middle of the view). There is one broken link (represented by a line with
double slashes) to back.gif.
broken link
Table 5-1 on page 83 shows the symbols you will see in the view and their
meaning.
Colors view
The Colors view allows you to select colors for background or text from a color
palette. To assign a color to text, highlight the text, select the color in the palette,
and select Set as Text Color from the drop-down list. The background color for a
table (or cell or row) or for the page can be selected in the same manner by
placing the cursor in the appropriate position.
Tasks view
The Tasks view contains a list of two types of elements:
Problems Problems are tool-determined issues that have to be resolved.
Example problems are Java compile errors, syntax errors, or
broken links for HTML/JSP files. They are automatically added to
the Task view when working with the tool. When you double-click
a problem, the editor for the file containing the problem opens
and the cursor is pointed at the location of the problem.
Tasks You can manually add tasks yourself. For example, you can add
a task that reminds you that you have to implement a Java
method. Place the cursor in the method’s implementation,
right-click, and select Add -> Task. When you double-click the
task, the file opens and the cursor is located in the method. You
can also add general tasks that do not refer to a specific file.
In Figure 5-1 on page 78, the filter has been set to on in this case to limit the
items seen to the current file. You can see that one item is in the Tasks view,
indicating a problem in the code. Double-clicking the task will bring the line where
the error is into focus in the editor. A corresponding icon appears in the editor
where the problem is. In this case, it is a broken link. Once the problem is
corrected, the entry in the Tasks view will disappear.
The left pane displays a list of possible events associated with the selected tag.
The right pane is a script editor. After selecting an event in the left pane, you can
add a script for that event in one of the following ways:
Enter the script directly.
Drag and drop a snippet from the Snippets view.
Insert simple actions by selecting from a list.
The icons on the toolbar allow you to perform the following actions:
Select a script language, for example Java or JavaScript.
Apply the script to the current HTML or JSP file.
Reset the script currently in the Quick Edit view back to the original document
contents.
Use the drop-down menu to perform additional actions:
– Filter the list of events in the events list.
– Insert or edit the script for a simple action by selecting from a list. In some
cases, a dialog box opens so you can enter variables related to the simple
action.
As you add or change scripts in the Quick Edit view, the HTML or JSP file is
updated if you select another tag, select another event for scripting, or click the
Apply Script button on the toolbar.
Besides scripting events, you can use Quick Edit to modify SCRIPT, jsp:scriptlet,
jsp:expression, and jsp:declaration scripts.
The Palette view contains a series of drawers that you can open. Each drawer
contains related items that you can drag and drop into the active editor. For
example, if you are editing an HTML page in Page Designer, you can open the
HTML drawer and drag and drop an image into the page. A window will open to
let you select an image from the file system to add. The drawers and their
contents vary depending on the active editor.
Palette view
Snippets view
The Snippets 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.
Snippets view
Outline view
The Outline view gives you an overview of the key elements that make up the
resource that is being edited. It allows quick and easy navigation through your
resource. By selecting one of the elements in the Outline view, the line in the
editor view that contains the selected element is highlighted.
For example, you can use the Design view to position graphics in the page, then
switch to the Preview view to see how it will look from a Web browser. The
Source view can be used to view the raw source code for the file, but not the
screen presentation. The Page Designer provides full visual editing capabilities,
including the ability to drag and drop from the Project Navigator view, the
Thumbnail view, and Microsoft Internet Explorer.
Source view
The Source view enables you to view and work with a file's source code directly.
You can see the Source view in Figure 5-1 on page 78. The Outline and
Attributes views both have features that supplement the Source view.
Preview view
The Preview shows you how the current page is likely to look when viewed in an
external Web browser. This view is only useful for viewing static content HTML.
There is no runtime capability so dynamic content (such as JSP tags) will not be
shown. To view JSP dynamic content, you will need to use the Run on Server
option (WebSphere test environment) from the page's context menu in the
Project Navigator view.
Tip: You can also use the Tools -> Launch External Web Browser menu
option to open the current file in an external Web browser.
Syntax validation
The HTML Syntax Validator included in Studio Site Developer validates HTML
basic syntax and HTML DTD compliance for HTML and JSP files created in Page
Designer. You can turn it on or off and configure an option on the preferences
page (accessed by clicking Window -> Preferences -> Web and XML Files ->
HTML -> HTML Annotations) to also validate your code as your type.
Syntax validators are available for checking basic syntax as you work with files.
Before getting started, it is a good idea to check the preferences to make sure
that the appropriate validators are active. For example, the HTML syntax
validator is not turned on by default.
The Web Site Designer is used to create the structure for your application in
much the same way you would create a book outline to serve as the basis for
writing a book. You use the Web Site Designer to visually lay out the flow of the
application, rearranging the elements (JSPs, HTML pages) until it fits your
needs. Then you continue by creating pages based on this design.
A typical application development scenario using the Web Site Designer might go
through the following steps:
1. Create a Web project. Select a default page template to use for the Web
pages. For information about page templates, see 5.1.5, “Using Page
templates” on page 109. As you create Web pages, the default template will
be used.
2. Open the Web Site Configuration file. You will find this in the root directory of
the project. It is automatically created when you create the Web project. This
file is actually an XML file called .website-config that will contain Web site
design information as you build your Web site using the designer.
3. Begin designing your application by adding pages to the configuration. At this
stage, you are simply adding elements to the design that represent JSP and
HTML pages, and defining their relation to each other. For example, you could
start by creating a top page called index.html.
4. Add additional pages and place them in the design so that the application flow
is illustrated. For example, if index.html will have four menu options, you
should select the index.html box and add four new child pages (one per
option) to the flow.
5. Continue to visually lay out the application flow by creating design elements
that represent each HTML and JSP page in the application. You can move
elements around the diagram as you go to change the application flow.
6. When you are done, create a real page for each design element (you could
also create the Web pages as you go along).
As you build your Web site design, the information is stored in the .website-config
file so that navigation links and site maps can be generated automatically. This
means that when the structure of a site changes, for example, when a new page
is added, the navigation links are automatically regenerated to reflect the new
Web site structure.
When opened for editing, the default editor for the page is used. In this case of
HTML and JSP pages, the default editor is the Page Designer.
Note: See 5.2, “Adding HTML pages to the Online Catalog sample” on
page 135 for an example of using the Web Site Designer.
The table below lists (and describes) all the items of the context menu and
groups them into the appropriate category.
Table 5-2 Context menu items
Item Sub Item Category Description
Icon border
Note: The icons become gray in color if the function associated with the icon
is not enabled. For example, in Figure 5-14 on page 102, the Navigation root
icon is grayed out because this page icon is not set as a Navigation root.
Navigation root
Enabling the Navigation root function sets the associated page as a navigation
root for the site. Traditionally, the index.html page of a site is set as the navigation
root. By default, this function is not enabled; to enable (or disable) it, right-click
the page icon and select Navigation -> Set Navigation Root from the context
menu.
Navigation label
The navigation label of the page icon is the text that will appear in the site
navigation menu. Therefore, the label should be simple and descriptive of the
page being linked to, for example, Home or View Catalog.
Icon border
If there is no page associated with an icon, the icon border is dashed (as in
Figure 5-14 on page 102). Once a page is created or associated to the icon, the
border becomes solid. In addition to the border being changed, a fourth icon will
be added to the page icon: the Code icon. If the icon is a less than and greater
than sign icon, it means that the associated page is an HTML page. If the icon is
a blue diamond, then the associated page is a JSP.
Icon border
Page templates
If a page template has been applied to a page, the top part of the icon is blue.
To add a template to a page, right-click the page icon, select
Page Template -> Apply Template... from the context menu, and then follow
the wizard instructions.
To remove the applied template, right-click the page icon and select Page
Template -> Detach Template from the context menu.
When a template is applied to the page, you can also open the template and
replace the template. To open the template, right-click the icon and select
Page Template -> Open Template With -> Page Designer for Template
from the context menu.
To replace the template, right-click the page icon, select Page Template ->
Replace Template... from the context menu, and then follow the wizard
instructions.
Note: If you use a page template to govern the layout and visual design of all
the pages in a Web site, you can insert a navigation trail onto the page
template, rather than adding the navigation to every page individually. The
links in the navigation trail are then updated dynamically for each individual
page in the site.
You can modify the appearance of site parts by editing the associated
specification page:
1. In a Web page open in Page Designer, select a site part tag, such as
siteedit:navbar.
2. In the Attribute view, click Edit. The specification page opens.
3. Edit the specification page as you would edit any other HTML file.
Note: You must enter tags and expressions in the Source page of Page
Designer.
4. Save the specification page when you are finished.
Example 5-1 on page 108 shows an example of a spec.html.
Page templates can be applied to a Web page in one of the following ways:
By specifying the template when you use a wizard to create the page. This is
true regardless of whether you are using the wizard from a navigation view, a
tool bar or the Web Site Designer.
By using the Web Site Designer. You can apply a template as you create
pages or to existing pages as you add them to the Web Site Configuration.
You can also apply or replace templates to pages already in the configuration.
By using the Page Designer. With the page open, select Page -> Page
Template. You can apply, replace, or detach the template. You also have the
option of opening the template for modification.
A default page template can be specified when you create a Web project. If you
specify a default template, it will be automatically selected when are given the
option in wizards to select a template for a page.
A page template can act as a style sheet if you set your styles within the page
template. Since the template is used by every page in your site, any settings in
the page template will be reflected in the corresponding pages. That said, this is
not the recommended development scenario. It is best to keep the page template
and style sheet separate.
As an example, let’s build an entry for a Web site using a frameset. We will create
a parent frame called index.html. It will have the following frames:
A frame that spans the top called header.html. It will contain the company
logo and links to company information.
A frame on the lower left called menu.html. It will contain menu options.
A frame on the lower right called main.html. It will contain the page displayed
when the user selects an option.
Click OK.
4. In the Design view, you will see a bar splitting the frame into two horizontal
frames. Place the cursor in the bottom frame.
5. On the workbench menu bar, click Frame -> Split Frame -> Split Vertically.
A bar is displayed, splitting the bottom frame into two vertical frames. Drag the
bars so they are positioned as shown in Figure 5-20 on page 114.
When you are in the Design view, the source code updated depends on which
frame the cursor is in. You can see the current file name in the upper left
corner of the editor area.
6. On the workbench menu bar, click File -> Save All. You will have the
opportunity to name each page of the frame. In this case:
a. Save newpage1 as header.html.
b. Save newpage2 as menu.html.
c. Save newpage3 as main.html.
As you are asked to save each page, the relevant frame will be identified with
a dotted outline in the editor area. You may need to move the wizard window
to the side in order to see which window you are naming.
You can also switch to the frameset parent (index.html) in the Design view
using the Show Frames toggle switch above the editor pane, but there is no
visual indication of the frameset tags so you are limited as to what you can do.
Note that the frame attributes can be modified for each frame by placing the
cursor within the appropriate <FRAME> tags.
As you work with the text, you will find several useful toolbar options. For
example, you can select text and use icons to make it bold, center it, enlarge it,
change the font, or underline it.
Resizing a table
You can resize the table by selecting the columns, rows, or the complete table
and dragging to the new size. Otherwise, the table cells will be the size of
whatever their content is.
Table attributes
Attributes for the table can be set using the Attributes view. The attributes listed
in Table 5-3 can be set.
Table 5-3 Table attribute options
Table attributes Cell attributes Row attributes
Adding a link
Studio Site Developer provides the tools to easily add links to files or URLs using
the Insert -> Link toolbar option. The types of links you can choose from are file,
http, FTP, e-mail, or other.
Tip: You can also drag and drop files into the page from the Project Navigator
bar, the Thumbnail view, or even from Windows Explorer. When you do this, a
window opens with options that determine how the file is included. In this
window, you simply state that you want a link to the file inserted.
If the file is from a directory outside of the project, the file will be copied into
the project directly under the Web Content directory. You can move this to
another directory by dragging it to the folder in the Navigator view. The links
will be automatically updated to reflect the new location.
These values can be changed once the link has been added by using the
Attributes view.
Tip: In the previous frameset example, we assigned frame names with the
Attributes view. If you are working with frames, you can enter the name of the
frame as a target window for a link. Then, when adding additional links, you
will have that frame as a selection too.
Most activities related to creating and editing forms are available by clicking
Insert -> Form and Input Fields. To create a form, place the cursor where you
want to position the form and select Insert -> Form and Input Fields -> Form.
After determining a layout scheme for your form elements, you can use the
options in Insert -> Form and Input Fields to insert the following fields and
controls:
Submit, Reset, Image, General, and Extended buttons
Radio button
Check box
List box
Drop-Down menu
Group box
Text area
Text field
File Selection field
As you add form elements, the dialog for each object will open so that you can
supply format, style, and content details.
Style sheets can be created when the Web project is created (see 4.3.2,
“Creating a Web project” on page 66) or at any time using File -> New -> Other
-> Web -> CSS File from the toolbar. To work with a style sheet, you open it as
you would any other file. A special editor called the CSS Designer will be used to
open the file.
Figure 5-24 shows the default style sheet, called blue.css, that is added to Web
projects when they are created. You will find it under the Web Content/theme
folder.
Tip: If you have embedded styles in the HTML file, the embedded styles
override the style specifications in an external style sheet file.
Tip: You can insert an image created with WebArt Designer into a Web page
in the same way as a regular image file.
Object
Stack
Gallery
Canvas
Building an image involves working with objects. The following are object types
used in WebArt Designer:
Shapes: consisting of lines.
Logos: designed text.
Buttons: images that resemble a button.
Photo frames: photo frame that decorates a photographic image.
Clip art: Windows metafile read by WebArt Designer. Maintains better quality
when its size is changed compared to an “image” object.
Image: all images other than the preceding four types of objects. Any image
file created by software other than WebArt Designer is this type of object.
Basically, you will build an image by adding objects to the canvas and saving the
canvas for use in projects. You can also save objects to add to the gallery.
4. Highlight Buttons in the gallery and select the About Us object. Drag the
object to the canvas and place it near the top of the wallpaper.
5. Add text by selecting the text icon to the left of the canvas. Move the cursor to
the canvas and type Welcome to our Site. As you add each object, notice
that it is also placed in the object stack area. The top object is in front of the
other objects. You can change the order by dragging objects to a new position
in the object stack area. For example, if you put the wallpaper object at the
top, all other objects are hidden.
6. Add an oval object and stack it over the text. You will need to rearrange the
objects in the object stack area so the text appears over the oval. Right-click
in the oval and select Edit Object to change the color.
7. If you think you will use this new image again in graphic design, you should
save the canvas as a WebArt file (*.mif). Just select File -> Save Canvas as.
Or, if you want to save certain objects, you can select the object (or group
multiple objects into one) and then save the object with File -> Save Object.
For example, if you want to save the oval and text in Figure 5-28, select the
oval object and the text object in the object stack area. Then group the
selected objects using Object -> Group -> Group. With the new grouped
object selected, use the File -> Save Object option to save it.
Note: You can select multiple adjacent objects by holding the Shift key
while you click the objects at both ends of the list. You can use the Ctrl key
instead if the objects are not next to each other in the list.
The objects you save as WebArt files are available to you by browsing to the
folder where they are stored in the gallery under the Folder option.
You will notice that the new group is represented as one object in the object
stack area.
8. The last step is to save the canvas as a GIF file so that you can use it in your
application. Select File -> Save Canvas as and enter the folder and image
name. You can place the image directly into your project (for example, an
images file) by browsing to the project location in the workspace. Or you can
save it to a local directory and use drag and drop to add it to your Web page.
This example is very basic. To effectively use the WebArt Designer, you need to
open the WebArt Designer help. We suggest you read through the help topics
before beginning.
Frame
An animation created with AnimatedGif Designer is a collection of frames. A
frame is displayed in the frame display window. If you double-click a frame, a
dialog for setting frame properties appears.
Frames are categorized into three types: the image frame, the attribute frame,
and the comment frame, as shown in Figure 5-30 on page 130.
Attribute frame: the first frame of an animation. You cannot move this frame
from its location or delete it. The attribute frame contains information related
to the entire animation, such as the specification of the color palette and the
repetition count. To view and change those attributes, double-click the
attribute frame. This frame does not appear on the screen when the animation
is played on a Web browser.
Image frame: aframe for a single image in an animation. Image frames are
generated when you insert image files or when you add animation effects. To
change the properties of an image frame, double-click it.
Comment frame: the frame used for inserting your comments into the
animated GIF file. You can insert, for example, the date when the animation
was created or the name of the person who created it. To insert a comment
frame, click Edit -> Insert Comments on the menu bar. This frame does not
appear on the screen when the animation is played on a Web browser.
Note: If you do not see the Tools drop-down, open an HTML or JSP file in
the editor.
2. Select the Create an animation using more than one image option, and
then click the Next button (note the other options here).
3. In the next window of the wizard, click the Add Image button, select an image
file, and then click the Open button. Each image you select is added to the
list. You can repeat this step as many times as you like until you have added
all of the images you want to use.
Tip: If you click files while holding down the Shift key or the Ctrl key, you
can select more than one file at a time. The Shift key allows you to select
multiple sequential files. The Ctrl key allows you to select files at random.
Click Next.
5. In the next screen, specify the repetition count of the animation and the delay
time of each frame.
7. Click the Finish button. The Animation Wizard ends and the frames for the
images used in the animation are displayed in the animation window with the
title newimagex.
8. Click File -> Save As on the menu bar and specify the location and file name
of the animated GIF file to be saved. Then click the Save button.
The animated GIF can be added to a Web page just as you would add any other
image file.
The animation you have created is saved as a single animated GIF file.
Tip on finding the default welcome page for a Web application: The Web
deployment descriptor contains a list of file names that will be used to
determine the initial application welcome page. This list is seeded with default
file names, including index.html, when you create the Web project. To see the
list, open the Web deployment descriptor by double-clicking it in the Project
Navigator view. When it opens in the editor area, select the Pages view.
4. Change the page title by highlighting the text between the <title> tags and
typing Tom, Dick & Harry’s RVs....
5. Change to the Design view by clicking the Design tab at the bottom of the
editor.
6. Click the data cell to the right of the default company logo and type in Tom,
Dick & Harry’s RVs....
7. The default text color is black, which is difficult to see against the blue
background. To address this, we will create a new Cascading Style Sheet
(CSS) class and apply it to the text.
Highlight the Tom, Dick & Harry’s RVs... text and right-click.
8. From the context menu, select Style -> Add Style Rule.... The Set Selector
of New Style dialog opens.
Important: Using this method adds the style to the page. In this example, it is
fine because we are working with a template and all changes made in the
template will be reflected in any page that is referencing the template. If you
are not using a template, the CSS class being created should first be added to
a CSS file and then referenced in the page. For more information on using
CSS, please see 5.1.9, “Working with style sheets” on page 120.
9. Select the Class radio button and enter .page-header as the Class name.
17.Click OK.
18.Now that a new CSS class called .page-header has been created, we can
apply it to the text. Highlight Tom, Dick and Harry’s RVs... once again and
right-click. From the context menu, select Style -> Apply Class ->
page-header. The text will be edited to include the display features that were
created.
19.Save the B-01_blue.htpl page by closing the Page Designer for Template
Editor and clicking Yes from the Save Resource window.
20.The last thing to do before creating the HTML page is to edit the company
logo. From the theme folder, double-click the logo_blue.gif file. WebSphere
Studio Art Designer is opened and the image is shown in the editor.
2. The Web Site Designer opens in the editor area with two views: Navigation
and Detail. Right-click in the Navigation view and select Add New Page -> As
Top.
A page icon will appear representing a Web application page. The first page
created in a new Web site only has the option of becoming the top page, or
the top of the navigation hierarchy. The next page that is added can be set in
relation to the top page.
5. You will be prompted to select whether you want to create a new HTML or
JSP page. Select HTML and click OK.
6. Make sure that /OnlineCatalog/Web Content is shown as the folder name
and enter index for the file name. Verify that HTML and Page Template have
been selected for the Markup Language and Model, respectively.
7. Click Next.
8. Verify that the B-01_blue.htpl template has been selected.
9. Click Finish.
The new file opens in Page Designer.
10.Close Page Designer by clicking the X on the index.html tab and return to the
Web Site Designer.
11.Now you have a new Web site with the top page defined. You can continue
populating your site by creating page icons in Web Site Designer to map out
your site (see Figure 5-52 on page 149). You can use Web Site Designer to
plan and layout your whole site's organization, and then create each of the
Web page files to fill out the site.
12.To add an additional page icon, right-click in the Navigator view and select
Add New Page -> As Child from the context menu. This will add a child page
to index.html.
13.Change the Navigation Label text to About Us.
14.Creating the new page is done in the same manner as was done with
index.html. Right-click the About Us page icon and select Create Page from
the context menu.
15.Select HTML as the file type.
16.Click OK.
17.Name the page aboutus.html and click Next.
Web Site Designer can be closed by clicking the X on the OnlineCatalog tab.
21.When the Web site is run on the server, the navigation links on the template
will dynamically be generated based on the site map created.
The Navigation Root feature is helpful if you wish to set a page in the site as a
navigation root. By default, the first page you add to the Web diagram is set as
the navigation root and any page added as a child of the navigation root page
will have links added to the navigation bar (as long as they are navigation
candidates). But what if you wanted to start a different navigation root within
your site? Right-click the page in the Web site diagram editor and select
Navigation -> Navigation Root from the context menu. This page will no
longer contain the child links from the original navigation root page, but rather
will have links to any child pages from itself.
The Site Map Candidate feature is also very interesting. If a page in the Web
site diagram is enabled as a Site map candidate, the page will show up in the
site map if the Site Map item from the Site Parts drawer of the Palette view is
used. To enable and disable the site map candidate feature, right-click a page
icon in the Web diagram editor and select Site Map -> Site Map Candidate
from the context menu. For more information on using a site map, please see
“Inserting a site map” on page 106.
Note: This chapter assumes that you have installed a database product. The
example assumes that you have installed IBM DB2 on the Studio Site
Developer system. Assuming that the development machine, the database
server machine, and the application server machine are three separate
physical machines, you will need the following:
Database server: Must have a database product installed
Development machine (with Studio Site Developer): Must have access to
database drivers
Server machine (with Express Application Server): Must have access to
database drivers
Java Application
JDBC API
The JDBC API sends the SQL commands from the application to the JDBC
driver manager, which in turn talks to the vendor-specific driver that actually
connects to the database.
The JDBC 2.0 Standard Extension API introduced an alternative way of handling
database connections using data source objects. By using data source objects,
you have access to a pool of connections to a data source. Connection pooling
gives you the following advantages:
If you are connecting to an existing database, you can import the database
design into the project. This makes information about the database available to
wizards that assist in building database access code. If you are building an
application and have not created a database yet, you can design the database in
Studio Site Developer and create the SQL needed by the database product to
create the schema and tables needed for the application.
To illustrate the database access features of Studio Site Developer we will take
you through the process we used to create and work with the SALESAPP
database for our sample application. We recreated the sample using IBM DB2,
Oracle, and Microsoft SQL Server.
DB2
In DB2 you can use the DB2 Control Center to create a database by selecting
Databases -> Create -> Database. Or you can open a DB2 command window
and enter:
db2 create db SALESAPP
The user that creates the database will be granted full access. You should
consider creating a user ID (on the database server) and giving that user ID the
proper access for the application. You can use the DB2 Control Center to do this.
Oracle
In Oracle a database name is specified during installation and tablespaces are
created afterward to hold data. In this example, we have installed an Oracle
instance and are now creating a tablespace named SALESAPP. This can be
done either interactively in the Enterprise Manager console, or by doing the
following with SQLPLUS:
1. Create a tablespace called SALESAPP. For example:
create tablespace salesapp datafile ‘saleslog’ size 4M reuse autoextend on
next 2M maxsize unlimited
2. Create a user and grant the dba option. For example, to add the db2admin
user execute the following:
create user db2admin profile default identified by db2admin default
tablespace salesapp ;
grant dba to db2admin with admin option;
a. DB2 connection
The values needed in the wizard for connecting to a DB2 database are
shown in Figure 6-4.
• The Connection name will be OnlineCatalogConn. This name is only
used to identify the connection. It is chosen at random.
• The Database name is SALESAPP. This must be the same value you
named your database when you created it using your database
software.
• The User ID and Password you enter must have the proper
authorization to access the database. In this case, we will use
db2admin and db2admin, for the user ID and password.
4. Click Finish.
In this case, the database has been newly created so the import will just add a
folder for the database and a Statements folder underneath. If you had imported
a database with existing tables, views, schema, etc., you would see much more.
Creating a schema
When you imported the database to the Web project, a directory structure was
created under the Web Content/WEB_INF folder to contain the database design
information. You can see this in the Data Definition view by expanding the
OnlineCatalog Web project folder.
Note: If you have installed the sample application and created the database
using the DB2 commands included with the additional material, the tables
have already been created for you and the following steps do not apply. Just
read through them so you will know how we did it.
2. Enter a schema name. For example, a common schema is the user ID of the
user that will be accessing the database. For the Online Catalog application
we use db2admin.
3. Click Finish.
We will show you the layout of each table and then show you how to use Studio
Site Developer to create the SQL statements needed to create the tables.
ITEM_NUMBER character 5 N Y
ITEM_SHORT_DESC varchar 50 Y N
QUANTITY integer Y N
SOTD_FLAG character 1 Y N
CUSTOMER table
The CUSTOMER table contains information about registered customers
(Table 6-2).
Table 6-2 CuSTOMER table
Column type Length Nullable Key
CUSTOMER_ID character 10 N Y
CUSTOMER_NAME varchar 40 Y N
ADDRESS varchar 40 Y N
CITY varchar 40 Y N
STATE character 2 Y N
EMAIL_ADDRESS varchar 20 Y N
PHONE character 10 Y N
CC_TYPE character 2 Y N
CC_NUMBER varchar 20 Y N
ZIP character 5 Y N
INTEREST1 character 1 Y N
INTEREST2 character 1 Y N
PASSWORD character 10 N N
ORDER_NUMBER integer N Y
CUSTOMER_ID character 10 N N
ITEM_NUMBER character 5 N N
QUANTITY smallint Y N
ORDER_DATE date Y N
STATUS character 1 Y
USERS table
The USERS table contains users with administrative capabilities (Table 6-4).
Table 6-4 USERS table
Column type Length Nullable Key
USERNAME character 8 N Y
PASSWORD character 8 N N
When you created the schema (db2admin) earlier, a new folder structure for the
schema was created under the SALESAPP folder. This structure includes
subfolders for database elements (tables, views, etc.). To create the ITEM table
in our database schema:
1. Select the WEB-INF/databases/SALESAPP/db2admin/tables folder,
right-click, and select New -> New table definition.
2. Enter ITEM for the table name.
Click Next.
3. In the next window, add each column name and data type using the Add
Another button. Use Table 6-1 on page 165 as a reference for the columns
that are needed in the ITEM table. When you are finished you should have a
layout that looks like Figure 6-9 on page 168.
Click Next.
4. Now the wizard prompts for the primary key. In the case of our ITEM table, the
ITEM_NUMBER column represents a unique value and so is a candidate for
the primary key. All the other columns were nullable and so will not show up
as key candidates. When you created the ITEM_NUMBER column you should
have selected the Key column field (see Figure 6-9), so the key should
already be selected. Change the primary key name to PK_ITEM. The wizard
should now look like Figure 6-10 on page 169.
2. Enter the name of the folder where you want the generated .sql file to be
stored and select options for the generation.
– Generate SQL DDL with fully qualified names: This will include the
schema name when referring to tables.
– Generate SQL DDL with delimited identifiers: This option adds enclosing
quotes, which are needed by some database vendors.
– Generate associated drop statements: This option helps in dropping
existing tables. This option is typically required for incremental database
modifications when tables already exist.
– Open SQL DDL file for editing when done: This will open the file at the end
of the wizard. You do not need to select this unless you are curious to see
the generated SQL. The table.sql file will be placed in the databases folder
by default and you can open it at any time for editing or viewing.
3. Click Finish.
4. Find the SQL DDL file you just created, right-click, and select Run on
Database Server.
5. Click Next. The next screen will ask you to select the items you want to
create. Make sure the statements are selected and click Next.
7. Click Next. Select the box to use an existing connection and select the
connection to the SALESAPP database. For example, our connection was
called OnlineCatalogConn (see Figure 6-4 on page 160).
8. Click Finish to create the table in the database.
9. Follow the same procedure to generate and execute the DDL for the rest of
the tables.
The DB Output view includes an actions list on the left side of the view and
several tabbed pages on the right side. The pages on the right side display
information that is related to the action that is selected in the actions list:
A Messages page displays messages, including the progress of actions
A Parameters page displays the parameters involved with a certain routine
A Results page displays the results of SQL statements that are executed by a
routine
The left side of the DB Output view contains the following fields:
Status, which indicates the current state of the statement.
Action, which indicates what kind of action occurred.
Object Name, which contains the name of the statement.
In this example, we are assuming that we will use the pages as generated and
will place them in a folder called Wishlist under Web Content.
1. Switch to the Web perspective.
2. In the Project Navigator view, find and highlight the location where you want to
create the pages. This can be directly in the Web Content directory, or in an
application-specific directory. In our example, we select the Web
Content/wishlist folder under the OnlineCatalog project (note that this folder
must already exist).
3. Right-click, and select New -> Other -> Web -> Database Web Pages.
4. Click Next to start the Database Web Pages wizard.
First select the Save SQL Statement option and enter a descriptive name for
the saved statement. This way you can reuse the SQL statement you create if
you need to do this again.
Your options to create the SQL statement are:
– Be guided through creating an SQL statement
– Manually type an SQL statement
In our example we will let the wizard guide us through the process of creating
the SQL statement. For short statements or for those that you have stored in
a file, you could choose to type in the statement (copy/paste will work).
Finally, you can select a database model to work with. The options are:
– Use existing database model. This implies that you have connected to the
database and imported the design to your Web project (as we have in this
example).
– Connect to a database and import a new database model. This allows you
to go through the connect and import process now.
In our example, we will select the SALESAPP database that we imported to
our project by browsing to the correct folder in the Web project.
Click OK.
7. Click Next to begin creating the SQL statement.
8. Select the Table tab. Select the ITEM table in the Available Tables column.
Click > to move it to the Selected Tables column.
9. Move to the Columns tab to choose the columns you want included in the
select. You can include each column by selecting it in the Available Columns
panel and clicking > to move it to the Selected Columns window. In this case,
since we want all the columns, we move them all at once using the >> button.
10.We will skip the Join tab since all of our information is coming from just one
table.
11.Click the Conditions tab. The way we envision our search is that we will look
for a match or partial match in the long description (ITEM_LONG_DESC
column) based on criteria provided by the user.
The conditions for the search are built by selecting the appropriate values in
each condition column:
– Column: Click in the first field under Column and select
ITEM_LONG_DESC in the drop-down list.
– Operator: Select LIKE.
– Value: Values are expressions that are used to define the query. They can
be as simple as a constant or something more complex. You can type in a
value directly or you can use the Expression Builder wizard to build it.
In this case we are going to use the Expression Builder wizard to create a
variable (signified with a colon (:) at the beginning) to hold the search
criteria. The variable will be represented by an input field on an HTML form
and will be filled in by user input.
Select Build Expression. As you go through the wizard you will be asked
for the expression type and name. In this sample we want to define a
variable called item_desc.
13.Click Next. The SQL Statement page now displays the generated SQL
statement and gives you a chance to modify it.
Note: Testing the SQL: In our sample, we have not populated the database
with data, but if you are using a database that contains data you could test
your SQL statement by doing the following:
1. Click Execute. A new panel will appear.
2. Click Execute on this panel.
3. A window will pop up asking for a value for the host variable; for
example, our search would require the user to enter a description to
search on. We would enter something like ‘%Fleetwood%’ (including
the single quotes). The case of the argument must match the case
found in the database. The % signs allow you to search for any
character String containing Fleetwood. The long description for each
item would be searched for that character String and the results
returned.
In “Update the search argument” on page 193, we will show you how to
modify the code generated by the wizard so that the user does not have to
enter the % marks or be concerned about case to get a match.
5. Click Next. In the controller page you can make decisions that determine how
the flow of control is handled.
7. Click Next.
This page lets you make minor changes to the first results page. This page
will display a list of all the entries that result from the search in a table format.
You can change column titles for the table, change the page title, colors used,
and you can select the columns to display.
Because we selected the master detail pattern earlier, the pages are built so
that the user can select an item in the table to see the complete details. This
means that you can be more selective in what you display on the initial results
page.
a. In our example, we are only going to display the item number, price, and
the short description. Start modifying this page by de-selecting the other
columns.
b. Select the Item_Number column in the Result set columns window, and
then select the Fields tab below. Change the value of the Label property
to Item. This will change the heading for that column in the output table.
8. Click Next. The next step is to design the details page. This page is used to
display the details of an item selected from the first results page.
a. The process is the same as with the previous pages. Deselect the
SOTD_FLAG column. For the other columns change the Field properties
to useful values. In our sample we used the information given in Table 6-6.
Table 6-6 Details view page fields
Column Label Size Max length
ITEM_NUMBER Item 5 10
ITEM_SHORT_DESC Description 15 20
QUANTITY Quantity 20 40
PRICE Price 20 40
b. Click the Page tab and change the value of the page title to Item Details.
9. Click Next. In the Specify Prefix window, change the prefix to SearchItem. The
prefix is used to build the page names.
This does two things. It sets the case for both the input and the database values
to upper case so they are the same, and it adds a % character to the beginning
and end of the input parameter. This changes the input from a specific character
string to a pattern allowing any characters before and after the string to be
ignored during the match.
The JSPSQL tag library (dab:) is used to connect to and access the database.
Tag libraries are discussed later in Chapter 9, “Using tag libraries” on page 275.
You do not need to understand tag libraries yet to learn the concepts in this
section.
The thing to notice here is that the connection code uses three initialization
parameters (user name, password, and dataSourceName) stored in the servlet
entry in the Web deployment descriptor to make the connection. When the
Database Web Pages wizard created the JSPs, it registered them as servlets in
the Web deployment descriptor and created these initialization parameters to
define the database connection parameters.
Note: In this situation, the password used to access the database is stored
unencrypted. An alternative to storing the user ID and password as servlet
initialization parameters is to store them as JAAS authentication alias entries
(where the password is encrypted). The wizard does not give this option, but
you can easily update the code and create the definitions required for this. For
information on this method, see 16.5, “JAAS security” on page 570.
6. In the Details window, select Application for the authentication type and
Shareable for the sharing type.
</resource-ref>
When the application is installed into a production server using the administrative
console, the administrator will map the resource reference to an existing data
source definition. In the Express test environment, a data source definition must
exist in the server configuration with the same JNDI name.
Note: This step is not necessary if you are using the driver manager
connection.
4. Click Add beside the JDBC provider list (the top box).
5. Select IBM DB2 in upper window and DB2 JDBC Provider in lower window.
6. Click Next and enter the information shown in Figure 6-37 on page 203. The
name and description can be anything. The implementation class name and
class path you see are the default for the DB2 JDBC provider. The driver
specified in the class name must be available in the class path specified. Note
that in this case, the class path uses a variable. You will see how to ensure
that this variable is set correctly a little later.
Note that we left the Native path entry empty. This is only required if the JBDC
provider chosen uses non-Java (native) libraries.
Important: By default, the db2java.zip file does not support the JDBC 2.0
specification. You need to open the sqllib\java12 folder and execute
usejdbc2.bat to copy the correct drivers to the zip file.
7. Click Finish. The Data sources configuration page now looks like that shown
in Figure 6-38 on page 204. Note that the entries in the lower boxes have
disappeared. This is because they are not relevant to the selected JDBC
driver. Since we just added the DB2 driver, it is selected and there are no data
source or resource properties defined for it yet.
8. With the IBM DB2 driver selected in the JDBC provider list, click the Add
button next to the data source section.
9. Select DB2 JDBC Provider and Version 5.0 data source.
Click Next.
Note: If this is a J2EE 1.2 Web project, you must select Version 4.0 data
source. If this is a J2EE 1.3 Web project, you must select Version 5.0 data
source.
The JNDI name must match the name that you use in the application code. If
you used the Database Web Pages wizard to create the application pages,
this name is specified during the wizard (see Figure 6-25 on page 185) and is
stored as the dataSourceName initialization parameter for the servlet in the
Web deployment descriptor.
Note: In 6.2.7, “Database connections” on page 194, you saw that the
Database Web Pages wizard generated connection code that specified a
user ID and password retrieved from the servlet initiation parameters to
authenticate to the database.
11.Click Next. In the next window select the databaseName property. In the
value field, enter SALESAPP.
12.Click Finish.
The Data sources page should now look like Figure 6-42 on page 209.
13.You used a variable to define the path to the JDBC driver (see Figure 6-37 on
page 203), so you need to switch over to the Variables tab and define the
variable. The variable, DB2_JDBC_DRIVER_PATH, is predefined in the node
settings for you, but the value is empty.
Oracle users
The process for Oracle is similar to DB2. For example, to create a data source
using the Oracle thin driver:
1. Create a JDBC driver:
a. Database type = Oracle
b. JDBC Provider = Oracle Thin
c. Implementation class name =
oracle.jdbc.pool.OracleConnectionPoolDataSource
d. Class path = ${ORACLE_JDBC_DRIVER_PATH}/classes12.zip
2. Create a data source:
a. JDBC Provider = Oracle JDBC Thin Driver
b. Data source type = Version 5.0
c. Name = database_name
d. JNDI Name = jdbc/database_name
e. Data source helper class name =
com.ibm.websphere.rsadapter.OracleDataStoreHelper
f. databaseName property = database_name
g. URL = jdbc:oracle:thin:server_name:1521:database_name
3. Update the ORACLE_JDBC_DRIVER_PATH variable, for example,
c:\oracle\ora81\jdbc\lib\.
5. The first step is to choose a table to select from. You can do this in several
ways, depending on your preference:
– You can drag and drop the table from the Data Definition view into the SQL
Source view.
– You can open the context menu from the query in the Outline view and
select Add Table.
– You can use the context menu in the Tables view.
We prefer the drag-and-drop method, so we locate the DB2ADMIN.ITEM
entry in the database design and drag it to the SQL Source window.
As you select the columns, you will see the SQL being created in the SQL
Source view.
7. Use the Statement view at the bottom to add conditions, change the sort
order, etc.
8. Close and save the new statement.
Tip: Saved SQL statements can be tested by selecting Execute from their
context menu. Make sure that you are connected to the database.
If you are not familiar with servlets, this chapter will introduce you to the
necessary concepts. These concepts are also important in understanding Java
Server Pages (JSPs). If you are familiar with servlets, read on to find out how to
build servlets with Studio Site Developer. The following topics are discussed in
this chapter:
Servlet overview
Studio Site Developer and servlets
Using servlets in the Online Catalog sample
Important: This chapter only outlines and illustrates WebSphere Studio Site
Developer support for servlets. If you would like information on Java support,
please see the WebSphere Studio Application Developer Version 5
Programming Guide (SG24-6957) redbook.
Application Server
request request
Web Servlet Container
Client Server
response response
Servlet
A client makes an HTTP request to a Web server. This Web server manages that
request and sends it to a servlet container within an application server. The
servlet container calls the servlet, passing objects representing the request and
the response to it. The servlet then uses the request object to get the information
submitted by the user and executes its business logic, generating a response to
be sent back to the client.
Note: The terms servlet container and Web container are used
interchangeably in this publication. Both containers serve the same purpose,
in that they provide the support classes and context for servlets and JSPs.
Web containers, however, also provide an environment to deploy and run Web
applications.
Typically, there is only one instance of a servlet class loaded in the servlet
container at any time. Clients of the same application asking for the servlet will all
deal with the same instance of the object, unless the servlet was reloaded
previously.
Servlets are protocol-independent. They are mainly used with the HTTP protocol,
but their functionalities can be extended to other protocols. A servlet’s output can
be XML content or any other type. However, we will focus on servlets dealing with
Web clients in our examples.
Loading
Initialization
Service
handling
Destruction
Final state
All along its life, a servlet interacts closely with its container. Following the J2EE
specification, the container is in charge of providing a runtime execution for the
components. It is also responsible for handling a set of services such as
concurrency, administration, and security.
The servlet container is implied in all the steps through the servlet’s life cycle:
1. Loading: The servlet container uses a classloader to locate the class file of
the servlet and to instantiate it. This operation follows the Java class loading
process. An instance of the servlet class (and only one) is then available at
the end of this step.
2. Initialization: The container activates the servlet by calling one of its
methods, the init() method. The init() method must be implemented by a
servlet class. This method is called once by the container and is used to
initialize a set of parameters for the servlet instance. The servlet is then ready
to handle requests from clients.
3. Service handling: Each client request generates a call to the service() method
of the servlet class. This method can either generate the response and
transfer it to the Web server (via the servlet container) or dispatch the request
to another component within the container.
For each request on the same servlet instance, the container is responsible for
creating and managing a new thread to serve the request.
The servlet container provides the same services regardless of the platform it is
operating on. This allows the servlet developer to focus on the logic of the
component, without considering deployment issues. A servlet container must at
least support the HTTP 1.0 protocol. To provide its services, a servlet container
interacts with other Java objects, such as the servlet configuration and the servlet
context objects.
The servlet container uses this object to pass configuration information to its
servlet instances, such as the name and the value of a parameter located in the
servlet container. The ServletConfig object is accessible to the servlet through its
getServletConfig() method. Moreover, a ServletConfig object allows the access
to a ServletContext object.
The servlet context provides information about its environment to a servlet. It can
be shared by a group of servlets and provides access to the following:
A set of attributes: a set of name/object pairs that can be shared between
servlets and other components to maintain persistency. A servlet can either
add or remove an attribute or simply change its content. A servlet can also
access its init parameters, which are name/value pairs.
Resources: servlets sharing the same context can also share resources such
as files. They can access these resources via their servlet context.
A log file: a servlet can write a set of events to a log file.
A request dispatcher: this object, created and managed by the servlet
container, allows a servlet to forward its request to another servlet or to
include the content of another servlet into its own response. It allows servlets
sharing the same context to communicate with each other.
There can be several servlet context objects in a servlet container at the same
time, each managing its pool of servlets. Each servlet instance is running in one
of these contexts and all the servlet instances running in the same context will
share the same resources. Following that, a servlet class may have more than
one instance in a container, with each of these instances attached to a different
servlet context.
Finally, the servlet context is the way for the servlet to interact with its
environment (its container, but also other resources) without having to reconsider
its own logic. Every servlet container has at least a default servlet context.
Servlets are the link between the client request and the model. They must
interface with the components performing the business logic of the application.
Once the business logic is performed, the servlet will have to interface with the
presentation layer, providing an object used to generate the output. So the
servlet also manages the link between the model and the presentation and may
decide to delegate the output to an HTML page.
7.2.1 Wizards
Studio Site Developer provides wizards that aid in the development of servlets.
One is a Servlet wizard and the other is a Package wizard. The Package wizard
is not required to create a servlet since the servlet wizard will place the servlet in
the default package. If you would like to create your own package for
organizational purposes, use the Package wizard.
Package wizard
To create new Java packages in the Package Explorer:
1. Navigate to the JavaSource folder in your project.
2. Right-click the JavaSource folder and select New > Other from the context
menu.
3. From the New dialog, select Java from the left pane and then select Package
from the right pane.
4. Click Next.
5. Edit the Source Folder field to indicate in which container you want the new
package to reside. You can either type a path or click Browse to find the
container. If a folder was selected when you chose to create the new
package, that folder appears in the Source Folder field as the container for the
new package.
6. In the Name field, type a name for the new package.
Servlet wizard
The Servlet wizard takes you step-by-step through the process of creating a Java
servlet and provides you with output files you can use or modify for your Web
application.
Note: See 7.3, “Using servlets in the Online Catalog sample” on page 232 for
an example of a servlet being created.
– The Class Name value should be the class name of the servlet.
– Specify a superclass for the servlet class. A servlet created by this wizard
can have HttpServlet, or any class that has HttpServlet in its hierarchy, as
its superclass. Click Browse to choose from the available superclasses.
3. Click Next.
4. Select a modifier to specify whether your servlet class is public, abstract, or
final (classes cannot be both abstract and final).
5. Specify whether the servlet you create implements the SingleThreadModel
interface by selecting the Use Single Thread Model option. This guarantees
that there will not be simultaneous access to the same servlet instance, which
has a tendency to stabilize thread execution ordering.
6. The javax.servlet.Servlet is provided as the default Interface. You can also
add additional interfaces to implement. Click Add... to open the Interface
Selection dialog. In this dialog, as you type the name of the interface that you
are interested in adding in the Choose interfaces field, the list of available
interfaces listed in the Matching types list box updates dynamically to display
only the interfaces that match the pattern. Choose an interface to see the
Qualifier and click Add. Click OK when you are finished.
7. Select any appropriate method stubs to be created in the servlet file. The
stubs created by selecting the Inherited abstract methods option must be
implemented if you do not intend to create an abstract servlet. This is not true
for Constructors from superclass.
8. Click Next.
9. If you select the Add to web.xml check box, the servlet, along with its display
name, and any URL mappings and initialization parameters associated with
the servlet, will be automatically included in the Web project web.xml file.
Note that the Class Name value provided in the first page of the wizard is
automatically mapped on this page. The mapping is updated if you change
the value in the Servlet Name field.
10.Click Finish.
Java editor
The Java editor is used to edit the source code of your servlet. It is similar in
nature to Page designer.
Java editor
The Java editor also provides specialized features for editing Java code. The
editor includes the following features:
Syntax highlighting
Content assist
Code formatting
Quick Fix
Keywords
Comments
Strings
Code formatting
The Java editor supports the formatting of Java code according to your personal
preferences.
1. From the workbench menu bar, select Window -> Preferences. The
Workbench Preferences page opens.
2. In the left pane, expand the Java category and select Code Formatter. The
Code Formatter Preferences page opens.
3. In the New Lines, Line Splitting, and Style tabs, select the code formatting
conventions that you want the formatter to follow.
4. Note that at the bottom of the page, you can observe an example effect of
each individual code formatting option and see a preview of what your
formatted code will look like.
5. Click OK when you are done.
Quick Fix
The Java editor offers corrections to problems found while typing and after
compiling. To show that correction proposals are available for a problem or
warning, a “light bulb” is visible on the editor's annotation bar.
Left-clicking the light bulb or invoking Ctrl+1 (Edit / Quick Fix) brings up the
proposals for the problem at the cursor position. To select one of the proposals,
double-click it from the pop-up window and it will be inserted into your source
code.
Outline view
Associated with the Java editor is the Java-specific Outline view, which shows the
structure of the active Java compilation unit (for example, the servlet). It is
updated as the user edits the compilation unit.
Clicking the different elements of the structure will position your cursor in the
Java editor to the element location in the compilation unit. This can be very useful
if your compilation unit contains many elements and you wish to navigate to a
specific one.
To work with the Servlets page of the Web deployment descriptor editor:
1. Open a Web project in the Project Navigator.
2. Double-click the Web project's Web Deployment Descriptor file in the Project
Navigator. The Web deployment descriptor editor opens.
3. Click the Servlets tab to open the Servlets page.
4. You can edit settings in the following sections of the Servlets page:
– Servlets and JSPs - list servlets and JSPs used in this application. You
can add, edit or remove servlets and JSPs from the list.
– Details - lists details about the selected servlet or JSP. Details listed
include the servlet class, the display name, and a description.
– Initialization - lists the initialization parameters that are configured for the
selected servlet or JSP file. Initialization parameters could include the user
ID, password, URL, and driver properties for a database connection.
– Run as - lists details of the selected servlet's run-as element. See 16.4,
“Securing applications with role-based security” on page 556 for additional
information.
– Icons - lets you view or change icons (small or large) used to represent the
selected servlet or JSP file.
– WebSphere Extensions - list and lets you change the details of the Servlet
Extension for the selected servlet. You can add a new extension by
clicking Add. The Add Markup Language entry wizard appears.
Important: If you are downloading the Online Catalog sample from the
additional material section of the Redbook site, it will not have the servlet login
process linked up. The servlet in this example (along with other servlets) will
be located in the common package. Any JSPs or HTML pages associated with
the example will be located in the servlet_login folder in the WebContent
directory.
The login function in the sample will use a JSP to verify that the username and
password submitted are valid by referencing a table in the SALESAPP
database.
The first step in the login process is login.html. This page collects the user name
and password from the user and passes control to LoginServlet. LoginServlet
captures the user name and password from the login.html form, verifies them
using additional database connection wizards, and then forwards the user to the
site administration selection page; admin.html.
Note: The servlet login function included with the Online Catalog sample uses
four servlets, one HTML file, and two properties files. The four servlets
(LoginServlet, LogWriter, DBConnection, and DBDriver) can be located in the
common package under the JavaSource folder. The two properties files can
be located in the root of JavaSource and the single HTML file is located in the
servlets_login folder under WebContent.
5. Click Next.
6. The Servlet page asks you to specify Modifiers, Interfaces, and method stubs.
We are only concerned with having the doPost() method created at this time,
so uncheck the doGet() and Inherited abstract methods checkboxes. The
other options can be kept as is.
7. Click Next.
8. The Deployment Descriptor allows you to add any information to the
deployment descriptor related to the servlet being created. Select the Add to
web.xml check box to add a URL mapping for the servlet. This is optional but
we recommend it. You can also specify and initialization parameters if you
wish. For example, you could specify database connection properties here if
you required.
9. Click Finish. Upon creation, the LoginServlet servlet will be opened in the
Java editor.
The final code for the LoginServlet servlet can be seen in the example below.
Example 7-1 LoginSerlvet.java
package common;
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import java.sql.*;
/**
* Process incoming HTTP POST requests
*
* @param request Object that encapsulates the request to the servlet
* @param response Object that encapsulates the response from the servlet
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect(response.encodeRedirectURL("/OnlineCatalog/administration
/admin.html"));
}
else {
PrintWriter pw = response.getWriter();
pw.println("<font face='Arial' size='2'>LOGIN ERROR - Invalid user or
password</font><br>");
pw.println("<font face='Arial' size='2'><a
href='/OnlineCatalog/administration/login.html' >Click here to Try
Again</a></font>");
try {
// Connect to the database
DBConnection dbConnection = new DBConnection();
// Query database
ResultSet rs = dbConnection.getFromDB("SELECT password, username FROM
users WHERE username = '" + user + "'");
if (!rs.next()) {
try {
common.LogWriter.getInstance().writeToLog("Login Error: Invalid
username " + user);
} catch (InterruptedException ex) {}
return false;
}//if
} else {
try {
common.LogWriter.getInstance().writeToLog("Login Error: Invalid
password entered for " + user);
} catch (InterruptedException ex) {}
}//if
return result;
} catch (Throwable e) {
try {
common.LogWriter.getInstance().writeToLog("Login Exception: " + e);
return false;
} catch (InterruptedException ex) {
return result;
}
}
}
}
Note: The login component illustrated in this section is only mentioned here to
show the use of servlets in Studio Site Developer. The login component is not
a proper Web site security solution and is not recommended for “real-life”
situations. To reiterate, when the user logs in, a servlet will verify that the user
and password exist in a database table and forward the user to a new page.
No session information is used in the process, therefore if the user knew the
full path of the location he or she could get there without using the login.
Request 1 - foo.jsp
Does
foo.class foo.jsp
exist?
Request 2 - foo.jsp
No
Yes
No
There are two distinct phases in JSP invocation, the translation and the request
phase. Central to this is the fact that within the Web container, requests for
individual JSPs result in the creation of a Java class. This class is actually a
servlet. That is, it implements the javax.servlet.Servlet interface. The two phases
represent the creation of the servlet class and its subsequent invocation.
Phase 1: Translation
In Figure 8-1, Request 1 represents the first request for foo.jsp since the JSP
was deployed to the server. In this case, there is no existing servlet class for the
JSP. The first step in this phase is to translate the JSP source file into a Java
source file, which can then be compiled into a servlet, known as the JSP page
implementation class.
The .class and .dat files are stored on the file system. The .java file may or may
not be retained after the translation stage. This translation phase is performed
once per JSP. If a compiled class file already exists on the file system, then the
request for the JSP proceeds directly to phase 2.
For Request 1, this phase is entered immediately after phase 1. If the servlet is
not already loaded, it is brought into memory and the request serviced.
For Request 2, the Web container knows of the existence of an already compiled
servlet class loaded in memory, and directly services the request.
By default, the JSP implementation in WebSphere also checks the source .jsp
file for changes. If it has been modified it will enter the translation phase. Each
subsequent request is handled by the servlet until the servlet is unloaded from
memory, for instance, when the application server is stopped. This load/service
request/unload life cycle is exactly the same as for servlets.
The traditional JSP syntax looks like that shown in Example 8-1.
Example 8-1 JSP syntax
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<%@ taglib uri="jspsql" prefix="dab" %>
<%@ page
language="java" import="java.util.*, java.io.*"
contentType="text/html; charset=WINDOWS-1252"
pageEncoding="WINDOWS-1252"
The same JSP as an XML document would look like that shown in Example 8-2.
Example 8-2 JSP document
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:dab="jspsql"
version="1.2">
<jsp:directive.page language="java" import="java.io.*"
contentType="text/html; charset=WINDOWS-1252"
pageEncoding="WINDOWS-1252" session="true" />
<jsp:text><![CDATA[ <?xml version="1.0" encoding="WINDOWS-1252" ?> ]]></jsp:text>
<jsp:text><![CDATA[ <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> ]]></jsp:text>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=WINDOWS-1252" />
<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>AddNewItemProcess.jsp</title>
</head>
<body>
<p>Place AddNewItemProcess.jsp's content here.</p>
</body>
</html>
</jsp:root>
A JSP document has jsp:root as its root element. The root element has one
mandatory attribute, the version of JSP specification it is using. The root can
contain xmlns elements, which enable the use of the standard elements, for
example tag libraries.
Each of these elements is described below, but first we introduce some common
objects available to every JSP page.
request The request that initiated the invocation of the JSP. For an HTTP
request, it is a subtype of javax.servlet.HttpServletRequest.
exception Available when the JSP is acting as an error page. Allows access
to the exception object thrown from the calling page.
For more information about servlets, see Chapter 7, “Working with servlets” on
page 215.
Object scope
Each implicit object belongs to a particular scope within the Web application.
Indeed, the same scopes also become important when using JavaBeans within
JSPs. Table 8-2 lists the available scopes.
Table 8-2 JSP object scopes
Scope Description Applies to
The implicit objects available through the pageContext, request, session, and
application variables each provide getAttribute() and setAttribute() methods,
which allow objects to be stored and retrieved within the particular scope they are
associated with. As such, objects stored using the pageContext.setAttribute()
method have the most limited scope: They exist only for the duration of that page
invocation. Conversely, objects stored using the application.setAttribute() method
have the widest scope: They exist for as long as the Web application is running.
extends Allows the JSP page implementation class to extend a class other than
the Web container’s implementation of javax.servlet.jsp.JspPage.
import Allows the definition of classes and packages that will be available to
scripting elements within the JSP. Classes within the following
packages are available by default:
java.lang.*
javax.servlet.*
javax.servlet.jsp.*
javax.servlet.http.*
session If true, the implicit object variable session will refer to a session object
either already existing for the requesting user, or explicitly created for
the page invocation. If false, then any reference to the session implicit
object within the JSP page results in a translation-time error. The
default is true.
buffer Defines the buffering model for the JspWriter underlying the out implicit
object variable. The default is an 8-kb buffer. It can be set to a value of
xkb, or none.
autoFlush If true, the buffered output is flushed when full. If false, an exception is
thrown should the buffer fill up. A value of false, if the value of the buffer
is set to none, will result in a translation-time error. The default is true.
isThreadSafe If true, the JSP page implementation class will implement the
javax.servlet.SingleThreadModel interface, and requests for the JSP
will be handled sequentially in the order in which they were received.
If false, then requests will be dispatched to the page on arrival and
handled by individual threads. The default value is false.
isErrorPage Specifies if the page acts as an error page for other JSPs. If true, then
the exception implicit object variable is available for use. If false, any
reference to exception will result in a translation-time error. The default
is false.
errorPage Defines a URL to which any uncaught exceptions thrown during page
execution can be directed. The URL must specify a JSP page that has
isErrorPage set to true. The exception class is placed in the request
object sent to the JSP acting as the error page where it is made
available through the exception implicit object variable.
contentType Defines the encoding of the JSP page and the response content.
The list in Example 8-3 shows a snippet of JSP source code containing example
page directives.
Example 8-3 Page directive example
<!Example page directive tags>
<HTML>
<HEAD><TITLE>Date and time</TITLE>
<%@ page import="java.util.*" session="false" isErrorPage="false" %>
<%@ page errorPage="/error.jsp" %>
</HEAD>
<BODY>
<P>The current date and time is: <%= new Date() %></P>
</BODY>
</HTML>
The file attribute defines a relative URL, or URI, to the file to be included within
the JSP page. This URI may be either page or context relative.
The included file may contain any valid JSP tags. These tags will be translated to
Java source and included in the JSP page compilation class. The rules regarding
page directives stated in “The page directive” on page 248 still apply to page
directive tags within the included file. A page directive tag contained within the
included file will apply to the whole JSP at translation time. Any page directives
within the included file that conflict with tags contained in the “including” JSP
source will cause compilation time errors. For instance, if a JSP file contains a
page directive specifying session=“false”, and then includes another file
containing a JSP scripting element referencing the session attribute, a error will
occur.
The contents of the file to be included, file1.jsp, are shown Example 8-5.
Example 8-5 file1.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<HTML>
BODY>
<P>First File Contents.</P>
</BODY>
</HTML>
Scripting elements
Scripting elements allow the insertion of code into the JSP. Technically the actual
code is defined by the scripting language. As mentioned in Table 8-3 on
page 248, the only scripting language required by the JSP 1.2 specification is
Java. In addition, WebSphere Application Server - Express provides support for
JavaScript and IBM’s Bean Scripting Framework.
Let us take a look at how the scripting elements can be used to insert segments
of Java code into your JSPs.
Declarations
Declarations allow us to perform the declaration of variables and methods within
our JSP source. We can then use these variables and methods within other
scripting elements on our page. The syntax for a declaration element is:
<%! declaration(s) %>
To declare a method:
<%! public boolean isPositive(int x){
if (x<0)
return false;
else
return true;
} %>
Scriptlets
A scriptlet is the most general purpose JSP element, but also the element to use
with the most caution. They can contain any valid Java code that you could
normally place within the body of a Java method, including variable declarations,
method calls, and so on. The contents of any scriptlet expressions within a JSP
will be included within the jspService() method of the JSP page compilation
class. The syntax of a scriptlet tag is:
<% scriptlet %>
Or in XML syntax:
<jsp:scriptlet> scriptlet </jsp:scriptlet>
Individual scriptlets do not have to contain a complete piece of Java syntax, they
can interleave themselves with other page elements, allowing you to build up a
conditional display of static page elements. However, if the combination of the
scriptlets at translation time does not yield valid Java syntax, then a
translation-time error will occur.
One way to avoid this cluttered programming is to evaluate how taglibs can be
used instead of hand-coding Java. The Jakarta Web site (http://jakarta.com),
among others, has many tag libraries that can be used for common tasks. More
on this will be covered in Chapter 9, “Using tag libraries” on page 275.
Another way is to create a bean and then reference it in the JSP page.
Expressions
Expressions attempt to convert the result of the expression evaluation to a String.
Expressions take advantage of the fact that the object within Java can be
represented as a String, either through implementing a toString() method, or
inheriting one from a parent class or, ultimately, java.lang.Object. Primitive types
can also be directly output.
Or in XML syntax:
<jsp:expression> expression </jsp:expression>
Actions
The third type of JSP element is the set of action tags. We will only briefly
introduce the standard action tags defined within the JSP 1.2 specification here.
For now we will concentrate on the param, include, and forward tags.
All action tags use the same tag syntax, which, unlike the previous tags, is XML
compatible. Action tags have two forms, either an open or closed body tag. The
exception is the param action, which only appears in the form of a closed body
tag.
The value attribute may be an expression tag that is evaluated at runtime. For
example:
<jsp:param name=”surname” value=”<%= customer.getSurname() %>”/>
Or as an open-bodied tag:
<jsp:include page=”urlSpec” flush=”true”>
<jsp:param ... />
</jsp:include>
The page attribute specifies the relative URL, or URI, for the resource to include.
The resource may be a static file, JSP, or servlet. The value of the page attribute
may be specified via a JSP expression tag. The flush attribute specifies a
boolean value indicating whether the page buffer should be flushed before the
inclusion.
If the resource specified in the page attribute is a JSP, then that JSP undergoes
the normal life cycle of translation processing/request processing. As it is being
included in a runtime context, any change to the included JSP will cause it to go
through the translation phase again. If we refer back to our example of the
include directive and re-code it to use an include action tag instead, then any
changes we make to file1.jsp between invocations of file2.jsp will be reflected in
the next invocation.
Or as an open-bodied tag:
<jsp:forward page=”urlSpec”>
<jsp:param .../>
</jsp:forward>
When a JSP page uses a forward action tag, it terminates its own execution and
hands responsibility to the resource specified in the page attribute. If the output
buffer contains any output written before the forward action tag is processed,
then the buffer is cleared before the forward takes place. The resource specified
in the page attribute will provide all of the output, including headers.
The JSP 1.2 specification states that any output written to the page buffer will be
cleared when the forward tag is called. Therefore, that output will not appear.
However, if output has already been flushed from the buffer, or a page directive
specifies a buffer size of none and output has been written, the attempt to clear
the buffer will result in a request-time exception being thrown.
Preferences
The Preferences dialog can be opened by selecting Window -> Preferences
from the workbench main menu. The JSP Files page can be displayed by
expanding Web and XML Files from the left pane and clicking JSP Files. The
JSP Annotations, JSP Macros, and JSP Styles pages can be found by exanding
the JSP Files option.
JSP files
Allows you to select line delimiters for the operating system that applies to
your development. Line delimiters are used to indicate the start of a new line.
Allows you to use the workbench encoding when creating files, or you can
specify another one from the Encoding drop-down list.
JSP annotations
Allows you to specify the annotation colors for the default JSP editor.
JSP macros
This page allows you to create, delete, or edit macros available to you when
creating JSPs.
JSP styles
You can specify the syntax highlighing colors for the default JSP editor.
Properties
The Properties dialog can be opened by right-clicking your project and selecting
Properties from the context menu. Select JSP Fragment from the left pane to
display the page properties.
JSP fragments
You can specify the encoding, language, and content type for the JSPs in the
project.
The basic use of the Web perspective when working with JSPs is very similar to
working with HTML pages as described in “Using the Web perspective” on
page 78. The difference being, some of the views have specific support related to
JSPs.
Content assist
JSP toolbar menu
Page designer
Outline view
Snippets view
Palette view
Page designer
Page designer is the default JSP editor and is used in the same fashion as when
editing HTML pages. For more information about Page designer, please see
“Editing with the Page Designer” on page 90.
The resulting code added to the JSP would look like Example 8-6.
Example 8-6 JSP include code
<jsp:include page="login.jsp" flush="true">
<jsp:param name="message" value="Invalid login"></jsp:param>
</jsp:include>
For all the options you see, the processing is intelligent. For example, if you
select Insert Results from Bean but have not defined a useBean, then you will
get a message saying that the useBean needs to be defined first.
Content assist
The content assist menu can be used to select code or tags to enter. You can
open the content assist menu by using Ctrl+spacebar, or by right-clicking the
editor window and selecting Content Assist.
If you move the cursor over a few spaces so that it follows the sql:statement, then
you only see a list of what is expected next. In this case, the id attribute is
expected and that is your only choice.
Outline view
The Outline view gives you an overview of the structure of the JSP. Clicking an
item in the outline highlights that element in the editor window.
Palette view
The Palette view JavaServer Pages drawer contains items very similar to the JSP
toolbar menu options. When using Page designer to edit the JSPs, simply drag
and drop the items from the drawer into the source code of the JSP.
Reset Submit
AddNewItemProcess.jsp
AddNewItem.html
4. Click Next. You will be prompted for tag libraries you want to use. We have not
discussed tag libraries yet, but for now just be aware that we will be using a
tag library to access the application database.
5. Click Add taglib. You will be able to select from a list of tag libraries that have
been included in your Web project.
For our example, we used the tag libraries listed in Table 8-5.
Table 8-5 Taglibs for sample code
URI Prefix
http://coldjava.hypermart.net/servlets/validtag if
http://coldjava.hypermart.net/servlets/backtag go
jspsql dab
In each case, we will scroll down to the taglib and select it. A prefix (of your
choice) is needed to identify the tag library within the JSP. The prefixes we
use in the sample code are shown in Table 8-5.
In this case, all the defaults fit our needs, so click Next.
8. The next page allows you to add a servlet entry for the JSP in the Web
deployment descriptor. This is optional, but saves you time if you find that you
need to do this later. One prime reason for doing this would be to add URL
pattern mappings to make it easier to refer to the JSP in the code. Another
reason would be to add initialization parameters.
Select the Add to web.xml box. This will add a corresponding servlet entry in
the Web deployment descriptor. You may or may not need this later but it is
always a good practice to do so.
9. Click Finish.
A JSP file with the minimal JSP and HTML framework is generated using
information we provided before and is opened in the editor area. With the JSP
created, you can add the following code to it to complete the process of creating
a JSP. Manually enter the code below to see the different tools available in Studio
Site Developer.
Example 8-7 AddNewItemProcess.jsp
<%@include file="../dbConn.jspinc"%>
<!-- If item number is unique, and there were no validation errors, then insert
into db, otherwise the rest of the page is skipped -->
<% if (finish.equals("yes")) { %>
In our sample, we use the following line of code to include a file into our JSP. This
file contains the database connection information and is referenced by the
connectionSpec parameter in the dab tags.
<%@include file="../dbConn.jspinc"%>
We did not hard-code the connection information into the JSP because we were
concerned with session data issues related to our Wishlist feature of the site. If
we had inserted the connection information into the JSP, we would have lost the
connection parameters when the wishlist page was viewed. This occurs because
we remove the database session object from the wishlist page. The wishlist page
simply uses session attributes to display the users item selections.
We will focus mainly on understanding the content of tag libraries and how to
incorporate existing tag libraries into a Web application. If you are interested in
creating tag libraries, please refer to Programming J2EE APIs with WebSphere
Advanced Server - Express V5.0.2 Developer Handbook SG24-6124.
Taglibs can be developed by the programmer, but more often are downloaded
from existing sources. For example, the following sites contain tag libraries for
download:
Open-source utility tag libraries available from the Apache Group’s Jakarta
project:
http://jakarta.apache.org/taglibs
Note: The Jakarta Tag Library project is an open-source repository for JSP
custom tag libraries and associated projects. Detailed information for each
of the Jakarta tag libraries below can be found at:
http://jakarta.apache.org/taglibs/index.html
By using custom tags, we can harness the possibility of making our JSP pages
quicker and easier to develop, and also more maintainable. What is more, by
using them to wrap common tasks, we can also take advantage of portability by
reusing custom tags across Web applications. Whole libraries of third-party
custom tags are freely available.
There are also advantages possible only by using custom tags. The most notable
is the ability to post-process JSP output before it is written. This is a potentially
powerful piece of functionality that is not achievable using scriptlets.
Disadvantages
Despite the obvious potential advantages to their use, custom tags should not be
viewed as a remedy for the problems associated with JSP development. Overuse
of custom tags can lead to other problems:
Creation of meta-languages: By forcing a multitude of custom tags onto the
JSP authors we also force them to learn the syntax of all the tags. Effectively
we create another language, which may have a simpler interface than Java,
but still needs learning. In any case, custom tags should always be supplied
with sufficient documentation and examples.
By basing the decision to implement a custom tag on the need to have the
functionality, you reduce the temptation to implement some function that really
should go elsewhere. The custom tags you implement should stay true to the
overall application architecture and design. For some designs (for example, those
based on the page-centric model of JSP usage) custom tags for database
access and the like may well be necessary. However, if a database tag is used
within an MVC-based design, then this suggests that the functionality is
implemented in the wrong place.
You should also give consideration to the factors surrounding the authoring of the
JSPs. If the JSP authors are confident with Java, then they may prefer scripting
to using custom tags. Conversely, if the JSP authors are non-Java programmers,
then a custom tag interface will be better suited. Custom tags are also useful
when the dialog between the JSP author and Java programmer is limited by
physical distance or communication factors.
Tag libraries, or taglibs, are normally packaged as JAR files. The taglib is made
up of the following elements:
Tag library definition (TLD): An XML file containing elements that describe
each tag in the library. The TLD will be used by the Web container during
translation time to interpret each tag, and at request time to find and invoke
the tag code.
Tag handler: A Java class that provides the Web container with access to the
functionality of the tag. However, this does not necessarily mean that the tag
handler implements the tag functionality. As we hinted, this may be contained
within other classes/JavaBeans. The taglib will contain a tag handler class for
each custom tag.
Supplemental classes: The implementation of a custom tag may include
some optional files that, if used, need to be included within the taglib.
The programmer downloads these files and puts them where they will be
available to the application. A directive is added to the JSP that refers to the
library and assigns it a prefix. In the JSP code, the prefix is used to invoke tags
within the library. The Web application deployment descriptor (web.xml) provides
the link between the directive used in the application and the actual JAR file
containing the classes that execute the function.
It is important to note that if you are simply using an existing taglib, the only thing
you really need to know is that these things exist. We want to show you a quick
example to take the mystery out of taglibs.
Implementation bean
The actual tag implementation is contained within a JavaBean called HelloBean,
shown in Example 9-1. The bean supplies one method, hello(), which accepts a
String argument. The method outputs a message.
Example 9-1 Simple custom tag example: HelloBean.java
//Simple custom tag example: HelloBean.java
package com.ibm.itso.j2eebook.tagexamples.beans;
/**
* JavaBean which displays a Hello message.
*
* @author: Adrian Spender
*/
public class HelloBean {
/**
* HelloBean default constructor.
/**
* Returns a string saying hello to the name argument.
*
* @return A hello message
* @param name java.lang.String The name to say hello to
*/
public String hello(String name) {
return "Hello " + name;
}
}
Now we have the syntax for our tag defined, and the bean that provides the
implementation. The rest of the steps are best described as cookbook code. That
is, the code is largely the same whatever tag you are implementing. The classes
and methods you need to define are always the same. The first few times you go
through these steps will perhaps seem tedious, but creating them soon becomes
relatively trivial.
import java.io.IOException;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import com.ibm.itso.j2eebook.tagexamples.beans.*;
/**
* Handles the hello tag.
*
* @author: Adrian Spender
*/
public class HelloTag extends javax.servlet.jsp.tagext.TagSupport {
/**
* HelloTag default constructor.
*/
public HelloTag() {
super();
}
/**
* Called when the end of the tag is reached. Here we simply
* call our bean to get our output and then write it out.
*
* Note that we have access to the pageContext implicit object.
*
* At the end of the method we return an integer that tells the
* Web container whether the rest of the JSP page should be
* executed. If set to SKIP_PAGE then the JSP execution will
* stop. If set to EVAL_PAGE, execution will continue.
*
* @return indication to continue page execution
* @exception javax.servlet.jsp.JspException
*/
public int doEndTag() throws JspException {
try {
// and here we write the message back out
pageContext.getOut().write(mess);
} catch (IOException e) {
// whoops
e.printStackTrace();
}
release();
return result;
}
... as our tag is a bean, we also provide accessor and setter methods
}
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>j2eebook</shortname>
<info>Tag examples from ITSO J2EE Redbook</info>
<tag>
<name>hello</name>
<tagclass>com.ibm.itso.j2eebook.tagexamples.HelloTag</tagclass>
<bodycontent>empty</bodycontent>
<info>
Takes a name and says hello
</info>
<attribute>
<name>name</name>
<required>true</required>
</attribute>
</tag>
</taglib>
The TLD is an XML document that describes the contents of a tag library to the
Web container. It helps the container identify custom tags within a JSP page, find
the tag handler, recognize the attributes of the tag, and in combination with any
TEI, validate the tag.
Note: The JSP container uses the TagExtraInfo (TEI) class at translation time
to provide information over and above that provided by the TLD.
The structure of the TLD is pretty self-explanatory. As an XML file, the TLD
contains a standard XML root element and DTD statement.
Of these, the URI element is the most important. It ties the taglib directive defined
within a JSP page with a specific tag library. Alternatively, the URI may be
defined in the web.xml file for the Web application.
The tag element defines most of the information needed by the Web container for
a particular tag. The subelements of the tag element are listed in Table 9-2.
Table 9-2 Sub elements of the <tag> TLD element
Sub element Description
The tag element will include an attribute element for each attribute of the tag. The
attribute element has three subelements:
Name: A required element and defines the name of the attribute
Required element: If true, tells the Web container that a translation-time error
should occur if the attribute is not specified within a given tag instance
rtexprvalue: If true, specifies that the Web container should allow the attribute
value to be expressed using a JSP expression tag
Taglib directive
The taglib directive tells the Web container how to find the TLD for the taglib and
the identifier (prefix) that will be used in the application to signal that the taglib is
to be used. The format for the taglib directive is:
<%@taglib uri=“tag_uri” prefix=“tag_prefix”%>
The URI we specify can be abstracted from the physical location of the TLD,
allowing us more flexibility and portability when deploying our Web applications.
For example:
<%@taglib uri=“http://jakarta.apache.org/taglibs/utility” prefix=“utils”%>
The URI specified here is absolute, that is, it specifies a protocol, host, and uri.
Within the web.xml file for our Web application, we must provide a taglib element
to map this to a particular location. The location specifies a relative URI for the
location of the TLD.
In this case, the Web container still looks for such a URI within the taglib
elements of the web.xml descriptor for the Web application. If we do not specify
one then it will use the relative URI to attempt to find the TLD directly.
Finally, the taglib directive may specify a JAR file for the URI. For example:
<%@ taglib uri=“booktags.jar” prefix=“book” %>
In this case, the TLD must be located within the META-INF directory of the
booktags.jar file.
The URI refers to the uri attribute of a taglib directive on the JSP page on which
the tag library is used. The Web container uses the information provided in
web.xml to map this uri to a physical TLD defined by the location attribute.
The code used to invoke the tag is shown in Example 9-5. First, the taglib is
declared with a taglib directive, giving it a prefix, book, which we will use to
identify the tags. Then the prefix is used to invoke the taglib function.
Example 9-5 Simple custom tag example: helloSample.html
<!Simple custom tag example: helloSample.html>
<%@ taglib uri="Web-INF/j2eebook.tld" prefix="book" %>
<HTML>
<HEAD>
<TITLE>Simple custom tag example</TITLE>
<%@ page session="false" %>
</HEAD>
<BODY>
<H2>Simple custom tag example.</h2>
<P><book:hello name="Adrian"/></P>
</BODY>
</HTML>
As described in “Using a tag library in the Online Catalog sample” on page 301,
the steps to using tag libraries are listed below. Notice that in addition to the
steps, some of the tools above are listed. This indicates that these tools can be
used to complete a step.
1. Create a JSP (JSP wizard).
2. Add a taglib directive to the JSP (JSP wizard or Insert custom tag dialog or
Snippets view).
3. Add the appropriate taglib tags to the JSP (Insert custom tag dialog).
4. Insert the final JSP scriptlet and HTML code into the JSP; this step is
optional.
For step two, all three tools are listed. When using the JSP wizard, you can select
the tag libraries that you wish to use in the JSP. If a tag library is selected, a taglib
directive will be added to the JSP for that tag library. Likewise, in order to use the
Insert custom tag dialog, you must first select the tag library; if a tag library is not
listed, you can add it. In doing so, a taglib directive will be added to the JSP. The
Snippets view simply adds a page directive. Each of these tools is described in
greater detail in the following sections.
a. You can select a tag library from the list by selecting the check box beside
the taglib entry.
i. Once the tag library is selected, you must specify a Prefix to be used.
ii. Click OK to add the tag library to the list of included tag libraries for
your JSP.
b. If the tag library you want is not displayed in the list, you can click Import
to open the Import JSP Tag Library dialog.
6. Click Finish to create the JSP. If you open the JSP, you will notice that the
taglib directives have been added to the top of your JSP.
For the illustration below, we have downloaded a validation tag library (validtag)
from:
http://coldjava.hypermart.net
Assuming you have downloaded the taglib you want to use into a temporary
directory, you are ready to import it to your Web application. To import a tag
library into your project:
1. Switch to the Web perspective.
2. Right-click your project and click Import from the drop-down menu.
Figure 9-6 Updating the JSP tag library references in web.xml - References view
3. Click Add.
4. A window will open with a list of tag libraries in the WEB-INF/lib folder. Select
the Validtag tag library from the window. The URI will be filled in for you and a
list of tags in the tag library will appear in the bottom screen.
5. Click Finish.
6. Save and close the deployment descriptor.
Hopefully, the site that provided the taglib will also provide information on how to
use it, but viewing the TLD file is a quick shortcut into finding out what valid tags
and attributes exist.
You will find that when downloading a taglib, the JAR file is all that you are
required to download. The JAR file contains the classes required to implement
the tag library and the TLD file. However, you usually have the option to
download a separate TLD file also.
If you choose to download the TLD file to your file system, you can use a text
editor to view it. You can also import it to your project as a separate file, though
this is not necessary if it exists in the JAR file.
If you open a TLD file in Studio Site Developer, it will open with the XML editor.
To insert a tag library tag into your JSP, complete the following steps:
1. Click a spot in your JSP where you wish to place the the tag library tag and
select JSP -> Insert Custom... from the main menu. The Insert Custom Tag
dialog will open.
2. The left pane of the dialog contains a list of the tag libraries that are found in
the JSP. The right pane contains the tags that belong to the selected tag
library from the right. Locate the tag you wish to insert and click Insert. The
tag will be added to your JSP.
3. If the tag library you want has not been included with the JSP being edited,
click Add.... This will open the Select a Tag Library page as shown in 9.2.1,
“JSP wizard” on page 288. If you add an incorrect tag library, select the tag
library from the left pane and click Remove.
Table 9-3 on page 297 shows these options and what you get. If you did not
select an option when you created the Web project, you can add these options
later from the Web projects Web property menu. Just right-click the Web project
in the Project Navigator view, select Properties, then select Web.
Tags are provided to access information in the HTTP request for HTTP input
parameters from a POST or GET, HTTP headers, cookies, request attributes,
and session information related to this request.
This includes creating cookies and setting their values, setting HTTP headers,
returning back an HTTP error, or sending an HTTP redirect.
Session attributes are what makes it possible to store information about a client’s
session between multiple HTTP requests. A session attribute consists of a name
and value. To save information about a user’s session on your server, use the
setattribute tag.
Table 9-4 on page 300 shows the tag libraries used in the examples applications.
Figure 9-10 shows how tag libraries are used in a Web application.
WEB-INF/lib/taglibs-mailer.jar
...
mail.class mailer.jsp
1 setrecipient.class
from.class
<%@ taglib uri="/WEB-INF/lib/taglibs-mailer.jar" prefix="mt" %>
message.class
send.class or 3
taglib.tld
... <%@ taglib uri="http://jakarta.apache.org/taglibs/mailer-1.1" prefix="mt" %>
<taglib>
2 <taglib-uri>http://jakarta.apache.org/taglibs/mailer-1.1</taglib-uri>
<taglib-location>/WEB-INF/lib/taglibs-mailer.jar</taglib-location>
</taglib>
We will assume at this point that the inforequest.html page has already been
created and that the values to, server, cc, name, from, subject, and message are
the names of the parameters that will be sent to the mailer.jsp when the form is
submitted.
3. Select taglib directive and drag it to the mailer.jsp; drop it in a location just
after the bean taglib directive.
4. The Insert Template:taglib directive dialog opens. Set the uri value to
/WEB-INF/ib/taglibs-mailer.tld and the prefix value to mt.
The following example displays the final mailer.jsp. Notice the getParameters
inside the mailer tags. Also notice the error and success output that is added.
Example 9-7 mailer.jsp code
<mt:mail server='<%=request.getParameter("server")%>'>
<mt:setrecipient
type="to"><%=request.getParameter("to")%></mt:setrecipient>
<mt:from><%=request.getParameter("from")%></mt:from>
<mt:setrecipient
type="cc"><%=request.getParameter("cc")%></mt:setrecipient>
<mt:subject><%=request.getParameter("subject")%></mt:subject>
<mt:message>
Name: <%=request.getParameter("name")%>
Message: <%=request.getParameter("message")%>
</mt:message>
<mt:send>
<P>The following errors occured<br>
<mt:error id="err">
<jsp:getProperty name="err" property="error"/><BR>
</mt:error>
<BR>Please back up a page, fix the error and resubmit.<P>
</mt:send>
</mt:mail>
Thank you
<p></p>
Your message has been successfully sent.
This chapter describes XML use in applications and the support provided in
Studio Site Developer.
XML overview
Working with XML in Studio Site Developer
Using XML in the Online Catalog sample
We will not go into detail on how to build and use XML documents in this
publication. For detailed information, see The XML Files: Development of
XML/XSL Applications Using WebSphere Studio Version 5, SG24-6586.
There are six kinds of markups that can occur in an XML document:
Elements Elements are the most common form of
markup. Elements identify the content they
surround: <Date>17.07.2002</Date>.
Elements begin with a start tag <Date> and
end with an end tag </Date>.
Non-empty elements contain child elements or
character data. Empty elements have no
content and can be written in one of two
forms: <empty-element></empty-element> or
<empty-element/>.
Attributes Attributes are name-value pairs that occur
inside element tags after the element name,
such as the Price element has a currency
attribute:
<Price currency="Rp">1000</Price>.
All attribute values must be enclosed in single
or double quotation marks. These specify the
characteristics of an element.
Entity references Entity references insert reserved characters or
arbitrary unicode, refer to repeated or varying
text, or include the content of external files:
' <!-- Apostroph -->
℞ <!-- Indonesia -->
Entity references begin with the ampersand
and end with a semicolon.
Figure 10-1 on page 312 shows the basic elements of an XML document.
The example in Figure 10-1 spawns the following content structure shown in
Figure 10-2.
message book-info
book-title
date day
month
year
date day
month
year
email
filename
Note: Similar rules exist for HTML; the XHTML specification defines them.
However, HTML browsers also accept HTML documents that are not well
formed.
Or internally:
<!DOCTYPE rootElement [ ...(declarations)... ]>
Here is an excerpt of the DTD of our example from Figure 10-1 on page 312:
<!ELEMENT welcome (message,book-info*)>
<!ELEMENT message (#PCDATA)>
<!ELEMENT book-info (...)>
Because DTDs are superseded by XML schemas, we do not go into more detail
here.
10.1.4 Validation
A well-formed document is valid only if it contains a proper document type
declaration and if the document obeys the constraints of that declaration.
All valid documents are well formed; not all well-formed documents are valid.
Tag names should be globally unique, but for performance reasons they also
should be short; in order to resolve this conflict, the W3C namespace
recommendation defines an attribute xmlns, which can amend any XML element.
If it is present in an element, it identifies the namespace for this element.
The globally unique name uses URI syntax, but it is not a real URI that can be
accessed with a browser through HTTP. Predefined global names exist, for
example, for the data types defined in XML schema and in the SOAP standard.
The namespace definition in the first line assigns the global name
http://www.my.com/acct-REV10 to the local qualifier acct. This qualifier is used
on the element names such as name in order to attach them to the namespace.
In this example, all tags in the customer record are qualified to reside in the
namespace http://www.my.com/acct-REV10. No explicit prefix is needed
because the default namespace is used. Note that the default namespace
applies to any attribute definitions.
XML schemas (XSDs) bring to XML the rich data descriptions that are common
to other business systems. A schema allows you to precisely define cardinality
constraints and enforce data type compliance. XSDs are defined by a W3C
recommendation dating May 2, 2001.
In this section we will introduce the more common XML schema concepts that
you will need. There are numerous tutorials available on the Internet. A good
starting point is the following Web site:
http://www.w3.org/XML/Schema
As a first example, we use the simpleType element to define and name a new
simple type:
<?xml version="1.0"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://www.ibm.com"
xmlns:TestSchema="http://www.ibm.com">
<simpleType name="ZipCodeType">
<restriction base="integer">
<minInclusive value="10000"/>
<maxInclusive value="99999"/>
</restriction>
</simpleType>
The restriction element indicates the existing base type and specifies two facets,
minInclusive and maxInclusive. These facets constrain the permitted value range
of the new type.
Note that we have defined the default namespace for our schema as the
standard XML schema namespace http://www.w3.org/2001/XMLSchema; we
have also defined our own schema-specific namespace, http://www.ibm.com.
<element name="addressList">
<complexType>
<sequence minOccurs="0" maxOccurs="unbounded">
<element ref="TestSchema:address"/>
</sequence>
</complexType>
</element>
The type attribute is optional; it contains a reference to the type definition, which
is either defined in an XSD file such as ours (for example,
TestSchema:ZipCodeType) or a predefined standard data type (for example,
string in the default XSD namespace).
Note that the XSD file has to be accessible through HTTP. In the example,
file:///C:/temp/TestSchema.xsd is a true URL pointing to a location. Namespaces
such as http://www.ibm.com, on the other hand, just use the URI notation to be
globally unique. Assuming that noProtocol://www.ibm.com is globally unique, it
would be a valid namespace name as well.
The syntax of the schema location attribute defined by XML standards is:
xsi:schemaLocation="targetnamespaceURI locationURI">
This is a quite tricky notation because it is not obvious that two different entities
with a similar syntax but different semantics appear in the same attribute. Even
worse, the locationURI is often not a full network address, but a simple local file
name.
Target namespace
Several of the XSD elements introduced above can define a target namespace,
which is either absent or a namespace name.
The target namespace serves to identify the namespace within which the
association between the element and its name exists. In the case of declarations,
this association determines the namespace of the elements in XML files
conforming to the schema. An XML file importing a schema must reference its
target namespace in the schemaLocation attribute. Any mismatches between the
target and the actual namespace of an element are reported as schema
validation errors.
XSL uses an XML notation and works on two principles: pattern matching and
templates. It operates on an XML source document and parses it into a source
tree; it applies the transformation of the source tree to a result tree, then outputs
the result tree to a specified format. In constructing the result tree, the elements
can be reordered or filtered, and other structures can be added also. The result
tree can be completely different from the source tree.
10.1.8 XPath
The XML path language (XPath) is used to address parts of an XML document.
An XPath expression can be used to search through an XML document, and
extract information from the nodes (any part of the document, such as an
element or attribute) in it. There are four different kinds of XPath expressions:
Boolean: Expression type with two possible values
Node set: Collection of nodes that match an expression's criteria, usually
derived with a location path
Number: Numeric value, useful for counting nodes and for performing simple
arithmetic
String: Text fragment that may come from the input tree, processed or
augmented with general text
This expression selects any elements named ACCID (account ID), which are
children of ACCOUNT elements, which are children of ACCOUNT_TABLE elements,
which are children of the document root.
Note: Studio Site Developer provides tools for creating and working with
XPath files, but they are not covered in the following section. Please refer to
the product help for more information.
XML options are available from the context menus of the appropriate files types
in the navigators, wizards, and the XML perspective.
Important: This chapter does not go into detail for every tool listed above. For
detailed information, see The XML Files: Development of XML/XSL
Applications Using WebSphere Studio Version 5, SG24-6586 or refer to the
product help.
This chapter covers only a few XML tools of Studio Site Developer. The following
topics are discussed:
XML perspective
Creating a new XML file
Note: Open the XML perspective by selecting Window -> Open Perspective
-> XML from the workbench main menu.
Figure 10-3 on page 322 shows the default layout for the XML perspective and
some of the tools available for XML development. The XML editor is specifically
designed for working with XML files. As with other editors you have both a Design
view and a Source view. The Outline view contains a hierarchical view of the XML
tags in the document. You can also see the options in the XML toolbar
drop-down.
Editor
Outline view
10.2.2 Wizards
Several wizards are provided for you for the creation of XML-related files. In this
section, we will look at the XML, XML Schema, DTD, and XSL wizards. For
information on the additional XML wizards provided in Studio Site Developer,
please see the product help.
XML wizard
Studio Site Developer provides the Create XML File wizard to take you through
the process of creating a new XML file. This can be invoked in either of the
following ways:
Select File -> New -> Other -> XML -> XML File (or use the icon).
From the context menu of a DTD (.dtd) file or an XML schema (.xsd) file in the
Navigator, select Generate -> XML file.
The wizard gives you the following options for creating the XML file:
– From scratch
– From a DTD
– From an XML schema
From within an XML file open in the editor, select XML -> Generate XML
Schema.
DTD wizard
A Document Type Definition (DTD) has two purposes:
To serve as a framework and provide a set of elements and attributes that will
be used in the XML “templates” used by the application to generate XML
documents from raw data retrieved from the back end.
To validate incoming XML documents sent by the supplier in reply to outgoing
purchase orders generated by the customer application.
Studio Site Developer provides the Create DTD wizard to take you through the
process of creating a new DTD file.
Once you have created your query, you can also start the wizard from any
perspective. Follow these steps to start the XML from SQL query wizard:
1. Select File -> New -> Other -> XML -> XML and SQL Query, then click
Next.
2. Select the Create XML from SQL query radio button, then click Next.
3. On the Select SQL Statements page, expand your project and select your
SQL statement. Click Next.
4. Complete the wizard using the options described below.
5. When you have finished selecting your options, click Finish to run the XML
from SQL query wizard.
The presence of foreign keys specifies a relationship between two tables. When
generating XML files from a table that has a foreign key, there are two options
that you can choose from:
Select Foreign keys as links only. If you select this option, the tool will map
all the foreign key relationships into a single XML document. This will create a
hierarchical document that reflects the foreign key relationship.
10.2.3 Editors
Studio Site Developer provides you with numerous XML editors for working with
XML-related files. This section will look at XML, XML schema, DTD, and XSL
editors.
Important: This section simply describes the different editors. For detailed
information on how to use the different editors, please refer to the product
help.
XML editor
The XML editor is a tool for creating and viewing XML files. You can use it to
create new XML files, either from scratch or from existing DTDs or XML
schemas. You can also use it to edit XML files, associate them with DTDs or
schemas, and validate them.
The XML editor can be opened by double-clicking an XML file (*.xml). The XML
editor provides two views for editing:
Source view: Enables you to view and work directly with the source code file.
Many of the XML editing features in the XML editor Source view are very
similar to those available in the Source view of Page Designer.
The Source view has several text editing features, such as syntax
highlighting, unlimited undo/redo, and user-defined macros. Another helpful
feature is content assist, which uses the information in a DTD or schema
content model to provide a list of acceptable continuations, depending on
where the cursor is located in an XML file, or what has just been typed.
The XML editor Source view also includes a “smart” double-clicking behavior.
If your cursor is placed in an attribute value, one double-click selects that
value, another double-click selects the attribute-value pair, and a third
double-click selects the entire tag. This makes it easier to copy and paste
commonly used pieces of XML.
This makes navigation and editing easier for you. Content and attribute
values can be edited directly in the table cells, while pop-up menus on the
tree nodes give alternatives that are valid for that location. For example, the
Add Child menu item will list only those elements from a DTD or XML schema
that would be valid children at a given point.
The Design view is especially helpful if you are new to XML, or need to do
form-oriented editing. For example, you could use the Create XML File wizard
to create a template XML file for a job description form from a job description
DTD. After those steps are completed, you would only have to fill in the form
data using the Design view.
Design view
The XML schema editor can be opened by double-clicking an XML schema file
(*xsd). The XML schema editor has three main views:
Graph view: You can use the Graph view to add, remove, or rearrange
components in your schema.
Design view: When you select an object in the Graph view, the Design view
will display the properties that are associated with that schema component
object. You can use the Design view to enter values for the selected object.
Tip: By default, the Design view is combined with the Source and Graph
views. This can be changed by editing the XML Schema attributes in the
Preferences dialog. To open the dialog, select Window -> Preferences
from the main menu and then expand the XML option in the left pane and
select XML Schema.
Source view: You can switch to the Source view to edit the schema source
directly. The XML schema editor uses the Task view for error reporting.
The content assist (available in the Source view) will use associated XML
schema, DTD, or content model information to provide intelligent assistance.
DTD editor
The DTD editor is a tool for creating and viewing DTDs. Using the DTD editor,
you can create DTDs, generate XML schema files, and generate JavaBeans for
creating XML instances of an XML schema. You can also use the DTD editor to
generate default HTML forms based on the DTDs you create. The DTD editor
can be opened by double-clicking a DTD file (*.dtd).
DTD toolbar
Validating DTDs
A DTD open in the editor can be validated using the DTD drop-down menu. You
can also validate a DTD file (open or not) using the context menu of the .dtd file
in the Navigator view.
XSL editor
The XSL editor provides a text editor to handle the source code of the XSL file. It
has several text editing features, such as content assist and syntax highlighting.
The content assist feature helps you in writing your XSL code, since it is aware of
the proper XSL grammar rules. When editing the XSL document, content assist
can be invoked to prompt you with a list of possible XSL constructs to use.
Concerning the syntax highlighting feature, you will notice that whenever you
select any of the XSL file components listed in the Outline view, the
corresponding XSL code for that component will be selected, and vice versa.
You can import the samples to your workspace with the New File wizard. Simply
select New -> File -> Other -> Examples. Select the XML folder on the left and
choose one of the samples.
The XML and SQL Query wizard results in a single execution of the database
query with the results stored in a static HTML page. This example will illustrate
the use of the SQLtoXML Java class shipped with Studio Site Developer in a
servlet to create dynamic content that is executed upon user request. The XML
and SQL Query wizard is used first to generate the XSL and XST files used by
the servlet.
To create the featured item page, we will step through the following process:
1. Create an SQL statement.
2. Generate XSL and XST (query template) files using the SQL to XML wizard.
3. Set the classpath variables for the project.
4. Add the required libraries to the project build path.
5. Create a servlet that will be used to dynamically create our page content.
6. Add a page to the Web site diagram.
When everything is complete, the user will simply click a link on the index.html
page that will open the Featured Item page and display all the featured items in
our database. The diagram below illustrates the flow of the different components
in this process.
requests queries
calls creates
transforms
home page Servlet
XML and XSL strings HTML string
(output to user)
Note: These instructions assume that you have connected to the SALESAPP
database from Studio Site Developer and have imported the design to the
project. This was done in Chapter 6, “Accessing databases” on page 153. If
you have not made this connection yet, you can still go through the example,
though the step-by-step instructions will not match exactly.
If your project doesn’t have a database folder yet (no database connection has
been made), you can right-click the Web project and select New -> Other ->
Data -> SQL Statement. This wizard will also give you the option to create the
database connection. When asked for a folder for the statement, browse to the
WEB-INF folder. The databases folder will be created under this folder for you.
The method to build the statement will vary somewhat from these instructions,
but the wizards make it easy to follow.
SELECT
DB2ADMIN.ITEM.ITEM_SHORT_DESC AS NAME,
DB2ADMIN.ITEM.ITEM_LONG_DESC AS DESCRIPTION,
DB2ADMIN.ITEM.PRICE AS PRICE
FROM
DB2ADMIN.ITEM
WHERE
DB2ADMIN.ITEM.SOTD_FLAG = 'Y'
ORDER BY
PRICE ASC
9. Click Next.
10.On the next page:
– Verify that the Elements radio button has been selected as the Show table
columns as option.
– Verify that the None radio button has been selected as the Generate
schema definition as option.
– Ensure the Generate query template file check box is selected and the
output folder is set to /OnlineCatalog/WebContent/featured_item.
4. Click Next.
6. Click Next.
7. Select the Add to web.xml check box and verify that the URL Mapping value
is set to /FeaturedItemXMLServlet.
8. Click Finish. The FeaturedItemXMLServlet.java file will be opened in the Java
editor.
Notice that the featureditem package has been added to the JavaSource
folder for the project and that the FeaturedItemXMLServlet has been added to
the package.
We are now ready to add some logic to our servlet to enable it to retrieve the
database connect and SQL query information from the FeaturedItem.xst file, and
also add the logic to dynamically create an XML and XSL string, then transform
the content of these two strings into an HTML string which will eventually be
displayed to the user.
1. With the FeaturedItemXMLServlet.java file still opened in the Java editor,
copy the code from the example below into the servlet. There are comments
throughout the code, so please read through it to get a better understanding
of what is being done. Note that you will need to modify the code that points to
the .xst file to reflect the location of your workspace.
Example 10-4 FeaturedItemXMLServlet.java
package featureditem;
import javax.servlet.http.*;
import java.io.*;
/*
* Sample servlet to show a typical use of SQLToXML runtime library.
* 1. Retrieves query file name (.xst) and optional where clause parameters.
* 2. Builds XML and default XSL streams from the query result.
* 3. Generates HTML response to the client.
*
* In case where the format option is GENERATE_ID_AND_IDREF and RECURSE
* is true, this servlet does some interesting thing so explore.
*
* If you want to use your own connection, then you can create your own
* (possible from a connection pool) and provide it to SQLToXML. As an
* example, see XMLConnectionPoolServlet.java.
*/
public class FeaturedItemXMLServlet extends HttpServlet
{
private String SERVLET = null;
/*
* This method will be called by the servlet engine. It is quite long so
* be prepared but the logic is pretty simple. I could have used instance
variables
* instead to reduce the lines but then I did not what to put too much time
on
* dealing with the thread-safe issues on this sample program.
*/
public void service(HttpServletRequest req, HttpServletResponse res)
throws IOException
{
if (SERVLET == null)
{
String contextPath = req.getContextPath();
SERVLET = contextPath + "/servlet/FeaturedItemXMLServlet";
}
res.setContentType("text/html");
PrintWriter response = res.getWriter();
/*
* Getting the parameters from the request:
* xstFile : Query file name (.xst).
//Sets the location of the xst file - the directory path will need to be
changed for you system
String xstFile = "/Documents and Settings/bogers/My
Documents/IBM/wasexpress51/workspace/OnlineCatalog/WebContent/featured_item/Fea
turedItem.xst";
if (xstFile == null)
error(response, new Exception("xstFile parameter is not specfied."));
/*
* Generate XML and XSL streams from the query
*/
try
{
QueryProperties prop = new QueryProperties();
prop.load(xstFile);
Connection conn =
getConnection(prop.getLoginId(),prop.getPassword(),response);
if (conn != null)
sql2xml.setConnection(conn); // You are using your own connection
/*
* Interesting part begins:
* if we are in Recursive & ID_AND_IDREF query mode, the result html
* string contains one XSLWriter.TITLE_HREF and many
XSLWriter.CONTENT_HREF
* depending on the number of rows found. We need to replace these
strings
* with the actual queries to be used before sending the html to the
client.
*/
if (prop.getRecurse() &&
prop.getFormat().equals(SQLGenerateOptions.GENERATE_ID_AND_IDREF))
{
String base = SERVLET + "?"; // servlet url
base += "xstFile=" + xstFile; // query file
base += "&query="; // query to override in the query file
xmlWriter.close();
//xslWriter.close(); //Not used in our sample
}
catch (Exception e)
{
error(response, e);
}
}
paramValues = req.getParameterValues(param);
return paramValue;
}
// This method can be overriden if you want to use your own connection.
protected Connection getConnection(String uid, String password, PrintWriter
pw)
{
return null; // Let SQLToXML generate one for us.
}
// Take XML and XSL string to transform and return the result HTML string.
private String genHTML(String xml, String xsl)
throws Exception
{
ByteArrayOutputStream baosHTML = new ByteArrayOutputStream();
return html;
}
}
2. After you enter the code above into the servlet, you will notice that there is an
error on the page indicating that the variable xslContent cannot be resolved.
This brings us to our next step. We need to insert some code into the servlet
that sets the value of xslContent. This string variable will contain the code
If you open the FeaturedItem.xsl file we created earlier, you will notice that the
code above and the XSL code are very similar. We added a link to a CSS file,
a few CSS class references, table enhancements, and text additions
(indicated in bold).
6. Close the Web site diagram editor and save your changes.
Summary
Now you are ready to run the application. When the Featured Item link is
selected from the navigation bar, the FeaturedItemXMLServlet will be executed
and you will see a display of the featured items in the item table. The figure below
shows a screenshot of the output with the template applied to it.
Important: This chapter address the topic of Web service consumption. If you
are looking for information on Web service development, please see the
redbook WebSphere Studio Application Developer V5 Programming Guide,
SG24-6957.
On the server side, a Web server and a servlet engine are required. It is possible
to Web service enable an existing application without writing a single line of
code.
The definition of the message format travels with the message; no external
metadata repositories or code generation tools are required.
Let us now introduce the overall architecture of the Web services technology
framework.
2 1
Service Internet Service
Requestor Provider
3
Service
Broker
1. The service provider creates a Web service and possibly publishes its
interface and access information to the service registry.
Each provider must decide which services to expose, how to make trade-offs
between security and easy availability, and how to price the services (or, if
they are free, how to exploit them for some other value). The provider also has
to decide what category the service should be listed in for a given broker
service and what sort of trading partner agreements are required to use the
service.
2. The service broker (also known as the service registry) is responsible for
making the Web service interface and implementation access information
available to any potential service requestor.
The implementers of a broker have to make a decision about the scope of the
broker. Public brokers are available all over the Internet, while private brokers
are only accessible to a limited audience, for example, users of a
company-wide intranet. Furthermore, the width and breadth of the information
offered has to be decided. Some brokers will specialize in breadth of listings.
Others will offer high levels of trust in the listed services. Some will cover a
broad landscape of services and others will focus on a given industry. Brokers
These services can be new applications or just wrapped around existing legacy
systems to make them network-enabled. Services can rely on other services to
achieve their goals.
Figure 11-2 provides a first glance at the relationship between the core elements
of the SOA.
UDDI
(Broker)
HTTP
Runtime
transports
SOAP other
Requestor Provider
SOA Runtime
J2EE other
Implementation
Figure 11-2 Main building blocks in a SOA approach based on Web services
All elements use XML, including XML namespaces and XML schemas.
The service requestor and provider communicate with each other.
WSDL is one alternative to make service interfaces and implementations
available in the UDDI registry.
WSDL is the base for SOAP server deployment and SOAP client generation.
Overview
Historically, SOAP was meant to be a network and transport neutral protocol to
carry XML messages. SOAP over HTTP became the premier way of
implementing this protocol, to the point that the latest SOAP specification
mandates HTTP support.
SOAP remote procedure call (RPC) is the latest stage in the evolution of SOAP;
the body of a SOAP message contains a call to a remote procedure (expressed
in XML) and the parameters to pass in (again, expressed in XML).
RPC representation
The RPC representation is a convention suited to represent remote procedure
calls and the related response messages.
The usage of this convention is optional. If the RPC convention is not used, the
communication style is purely message oriented. When working with the
message oriented style, also called document-oriented communication, almost
any XML document can be exchanged.
Overview
WSDL allows a service provider to specify the following characteristics of a Web
service:
Name of the Web service and addressing information
Protocol and encoding style to be used when accessing the public operations
of the Web service
Type information: Operations, parameters, and data types comprising the
interface of the Web service, plus a name for this interface
A WSDL specification uses XML syntax, therefore, there is an XML schema for it.
WSIF is transport agnostic, thus a single WSIF client can support multiple
runtime protocols simultaneously, such as SOAP, a direct HTTP connection, and
a local Java call. For more information on WSIF see:
http://www-106.ibm.com/developerworks/webservices/library/ws-wsif.html
UDDI overview
UDDI stands for universal description, discovery, and integration. UDDI is a
technical discovery layer. It defines:
The structure for a registry of service providers and services
The API that can be used to access registries with this structure
The organization and project defining this registry structure and its API
UDDI is a search engine for application clients rather than human beings;
however, there is a browser interface for human users as well.
Figure 11-3 displays this data model with the entities introduced above. It also
shows their relationships and the link to the WSDL level.
1 Business
Entity
UDDI n
Business
Service
1 m tModel
contains n find
(ServiceType)
points to Binding n n
1
Template
1
0..1 0..1
Implementation n 1 Interface
WSDL
Document import Document
The business entity tops the containment hierarchy, containing one or more
business service entities and in turn binding template entities. The tModel
instances (service types) are not contained by the business entity, but referenced
by the binding template entities.
There are find_xxx and get_xxx methods for business, service, binding template,
and service type (tModel).
There are save_xxx and delete_xxx methods for the elements of the UDDI object
model (business, service, binding, tModel).
It is worth noting that these registries use a slightly different terminology than the
UDDI object model exposed to API programmers:
Business service instances are called businesses.
Business services are called services.
Binding templates are called access locators.
tModel instances are called service types.
Backward Compatibility
The Backward Compatibility preferences enable you to use options that are
compatible with previous WebSphere Studio releases. This preference only
applies if you are using Web services that use the IBM SOAP runtime.
This preference only applies if you are using Web services that use the IBM
SOAP runtime.
Dialogs
The Dialogs preferences enable you to determine which dialog boxes you want to
see when creating your Web service.
JDBC Drivers
The JDBC Drivers preferences enables you to add JAR files for additional JDBC
drivers. This is used only by the DADX validation code on Linux.
Resource Management
The Resource Management preferences enable you to determine the defaults
that you want to use when creating your Web service.
Scenario Defaults
The Scenario Defaults preferences enable you to determine the defaults that you
want to use when creating your Web service.
SOAP Transports
Select your default transport: SOAP over HTTP or SOAP over JMS. This
preference only applies if you are using Web services that use the WebSphere
5.0.2 runtime.
WS-I Compliance
The WS-I Compliance preferences allow you to select your level of compliance
with the WS-I Basic Protocol. This preference only applies if you are using Web
services that use the WebSphere 5.0.2 runtime.
WSDL editor
The Web Services Explorer is accessed by selecting Run -> Launch Web
Services Explorer from the main menu of the workbench.
12.The Service Details page opens and displays information about the
Currency Exchange Rate service.
a. Scroll to the bottom of the page and click Launch Web Service Wizard.
This opens the Launch Web Service Wizard page.
b. Verify that the Web Service Client radio button is selected and click Go.
13.The Web Services Client wizard opens.
a. Verify that the Client proxy type drop-down value is set to Java proxy.
b. Select Test the generated proxy. This creates a sample that will use the
Web service. The sample can be a starting point for the code in your
application.
c. Select Create folders when necessary. The wizard will be creating files
and folders during the Web services client generation. This allows the
folders to be created as you go.
d. Click Next.
14.On the Client Environment Configuration page you are required to select a
runtime protocol and server for the client environment. In the Client-Side
Environment Selection area select the Choose Web service runtime
protocal first radio button. Two windows will be displayed in the lower part of
the page.
a. From the Web service runtime window select IBM SOAP and from the
Server window, expand Server Types, WebSphere V 5.0, and select
WebSphere Express V5.0 Test Environment.
b. Verify that the Client Web Project value is set to OnlineCatalog and click
Next.
15.The Web Service Selection page is displayed and prompts for the WSDL file
location. This is where we enter the URL of the WSDL. This will be filled in for
us since we invoked this wizard from the Web Services Explorer.
16.Click Next. The wizard will attempt to access the WSDL file at the URL
entered, analyze the information in the file, and then present the Web Service
Binding Proxy Generation page.
a. This page allows you to select the type of binding (SOAP, httpget, httpost)
that you want to use. The options are based on the binding information
found in the WSDL file. In this example, only one type of binding, SOAP,
was defined. However, you may find that multiple types have been defined
that you can select.
For this example, we can leave the defaults for all fields.
b. Click Next.
17.The Web Service Test page lets you generate a sample Web application to
use the Web service. Change the Folder field to currency_conversion.
18.Click Finish. The wizard automatically launches the TestClient.jsp in the Web
browser.
19. The wizard also copies the files needed and generates the sample client. The
JavaBean proxy files are placed in the JavaSource directory and sample
JSPs under the folder specified in the wizard (currency_conversion). The
wizard produces the following files:
– To test the generated proxy, the following files are created in the
currency_conversion folder:
• TestClient.jsp: this is basically the parent of a frameset. The frameset
consists of the next three JSPs. This is what is created and launched to
test the Web service.
• Method.jsp: this contains a list of the methods available in the Web
service to test.
• Input.jsp: this displays a form customized to the method to allow the
user to enter input and submit the test.
• Result.jsp: this invokes the proxy class as a useBean and shows the
results produced by the Web service.
The finished result now looks like Figure 11-14 on page 381.
The Struts framework has gained considerable attention because of its ease of
use and ability to fit the needs of today’s developers in building applications fast.
Struts combines servlets, JSPs, custom tags and message resources into a
unified infrastructure and saves the developer the time it takes to code an entire
MVC model, which is a considerable task.
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? You could buy a new TV, which does these things internally in a
completely different way, and you could still change channels.
The action object can handle the request and respond to the client (usually a
Web browser), or indicate that control should be forwarded to another action. For
example, if a login succeeds, a loginAction object may want to forward control to
a mainMenu action.
Action objects are linked to the application controller, and so have access to the
methods of the servlet. When forwarding control, an object can indirectly forward
one or more shared objects, including Java beans, by placing them in one of the
standard collections shared by servlets.
An action object can, for instance, create a shopping cart bean, add an item to
the cart, place the bean in the session collection, and then forward control to
another action, which may use a JSP to display the contents of the user's cart.
Because each client has its own session, each also has its own shopping cart.
The view in a Struts application is made up of various components. JSPs are the
main component. JSPs, of course, are not Struts components. However, Struts
provides additional components that can be used by or with JSPs:
Form beans
Custom tags
HTML documents
Form beans
A form bean is an instance of the org.apache.struts.action.ActionForm class
subclass that stores HTML or JSP form data from a submitted client request or
input data from a link that a user has clicked. A form bean is a type of Java bean.
An HTML or JSP form comprises fields in which the user can enter information.
The form bean can be used to collect data from the user, to validate what the
user entered, and by the JSP to repopulate the form fields
In the case of validation errors, Struts has a shared mechanism for raising and
displaying error messages. It automatically invokes the ActionForm.validate
method whenever the JSP page containing the form corresponding to this
ActionForm submits the form. Any type of validation can be performed in this
method. The only requirement is that it return a set of ActionError objects in the
return value. Each ActionError corresponds to a single validation failure, which
maps to a specific error message. These error messages are held in a properties
file to which the Struts application refers.
Custom tags
There are four tag libraries included in Struts:
1. The HTML tag library, which includes tags for describing dynamic pages,
especially forms.
2. The beans tag library, which provides additional tags for improved access to
Java beans and additional support for internationalization.
3. The logic tag library, which provides tags that support conditional execution
and looping.
4. The template tag library for producing and using common JSP templates in
multiple pages.
Using these custom tags, the Struts framework can automatically populate fields
to and from a form bean, providing two advantages:
The only thing most JSPs need to know about the rest of the framework is the
proper field names and where to submit the form. The associated form bean
automatically receives the corresponding value.
If a bean is present in the appropriate scope, for instance after an input
validation routine, the form fields will be automatically initialized with the
matching property values.
with no need to explicitly refer to the Java bean from which the initial value is
retrieved. That is handled automatically by the JSP tag, using facilities provided
by the framework.
HTML documents
Although HTML documents generate only static content, you can use standard
HTML documents within your Struts application. Of course, they will not be able
to render any dynamic data, but they are still valid to use whenever the view is
static.
For example, a login page may just be an ordinary HTML document that invokes
a Strut login action.
In the Struts framework, several components are responsible for the controller
duties and they can be classified in two parts: the action servlet and action
classes.
Action servlet
The Struts framework provides the org.apache.struts.action.ActionServlet class
for servlets. The action servlet bundles and routes HTTP requests from the client
(typically a user running a Web browser) to action classes and corresponding
extended objects, deciding what business logic function is to be performed, then
delegates responsibility for producing the next phase of the user interface to an
appropriate view component such as a JSP.
Each mapping defines a path that is matched against the request URI of the
incoming request, and the fully qualified class name of an action class.
Action class
An action class is one that extends org.apache.struts.action.Action. The action
classes interface with the application’s business logic. Based on the results of the
processing, the action class determines how control should proceed. The action
class specifies which JSP or servlet control should be forwarded to.
Note: The action class can contain the actual business logic, in which case it
would be considered the model and not the controller. However, this practice is
not recommended, since the application’s business logic woold then be mixed
with the Struts framework code: this would limit the ability to reuse the
business logic. The advised practice is to use the action class as an interface
to the business logic, and allow it to share in the controller role, guiding the
flow of the application.
As you continue through the wizard, you will notice that a new page is available
for configuring. The Struts Settings page allows you to override the default Struts
settings.
Click the Override default settings box and specify the changes:
To specify a different version of Struts, select from the Struts version
drop-down menu.
To change the default Java package prefix, edit the Default Java package
prefix field.
To create a resource bundle for your Struts project, make sure that the Create
a Resource Bundle for the Struts Project box is selected and that a Java
package name and a resource bundle name are specified.
Clicking Finish will create the project and you will now be ready for Struts
application development.
4. Click Apply.
5. The Struts Settings page is displayed. This page allows you to override the
default Struts settings.
Note: For more information on how to create a Web diagram, see “Web
diagram wizard” on page 420. After a Web diagram file (*.gph) is created, you
can double-click the file to open the Web diagram editor.
Context menu
In the Web diagram editor, the context menu displays an appropriate list of
possible actions. The context menu can be accessed by right-clicking anywhere
on the free-form surface or on an object within the free-form surface.
The content of the list depends on which object on the free-form surface is
selected. Listed below are the context menu actions built into the diagram editor.
Table 12-1 Context menu actions
Item Parent Function Icon
Connection Draws a
connection from
the selected node
to a target.
Note: Unrealized connections are indicated in the Web diagram editor with a
dashed line. As soon as the connection is realized, the line becomes solid.
For a detailed explanation of the wizards, see 12.2.5, “Wizards” on page 405..
12.2.5 Wizards
Studio Site Developer also provides you with the following wizards to aid in the
creation of a Struts-based application. These wizards can be found by selecting
File -> New -> Other -> Web -> Struts from the workbench main menu.
In addition, some of the wizards can be accessed through the Web diagram
editor and/or the Struts explorer.
Action wizard
To create an action and optionally create an action mapping, complete the
following steps:
1. In the Project Navigator of the Web perspective, right-click the name of a
project.
2. Left-click New -> Other -> Web -> Struts -> Action Class -> Next.
3. On the New Action Class page, complete the following steps:
– In the Action class name field, type the name of the new action.
– In the Folder field, specify the name of the folder in which the new class is
to be created.
– In the Java package field, specify the name of the Java package in which
the class is to be created.
– If you want to specify modifiers that apply to the new class, select one or
more of the following boxes: public, abstract, final.
– Make sure that a value is supplied in the Superclass field.
– For each interface that you want to create, click Add and type the interface
name, the names of matching types, and any qualifiers.
– If you want to create method stubs, click the check boxes to select the
ones you want.
– For the code generation model, select Generic Action Class.
4. Click Finish.
Note: There are four other ways to invoke the Module wizard.
– Double-clicking an unrealized action mapping node in the Web diagram
editor.
– Right-clicking the project in the Struts Explorer view and selecting
New -> Action Mapping from the context menu.
– Expanding the project directory in the Struts Explorer view, right-clicking
the module, and selecting New -> Action Mapping from the context
menu.
– Expanding the module folder in the Struts Explorer view, right-clicking
the Actions folder, and selecting Add Action Mapping... from the
context menu.
a. In the Action class name field, type the name of the new action.
b. In the Folder field, specify the name of the folder in which the new class is
to be created.
c. In the Java package field, specify the name of the Java package in which
the class is to be created.
d. If you want to specify modifiers that apply to the new class, select one or
more of the following boxes: public, abstract, final.
e. Make sure that a value is supplied in the Superclass field.
f. For each interface that you want to create, click Add and type the interface
name, the names of matching types, and any qualifiers.
ActionForm wizard
To create a Struts form bean and optionally create a form bean mapping,
complete the following steps:
1. In the Project Navigator of the Web perspective, right-click the name of a
project or artifact within a project.
2. Click New -> Other -> Web -> Struts -> ActionForm Class -> Next.
3. On the New ActionForm Class page in the ActionForm class name field, type
the name of the ActionForm subclass that you are creating.
4. Fill out the other fields as appropriate for the subclass you are creating, and
click Next.
5. On the Choose new fields for your ActionForm class page, click the check box
beside the name of each node for which you want a get and a set method
created. Check boxes exist for every node in the following hierarchy:
– Project
– Module
– Folder
– Web page
– Form
– Form field (leaf)
If you click the check box beside the name of a form field, you will generate a
corresponding field, get method, and set method in your form bean. If you
click the check box beside the name of a parent, you will generate a
corresponding field, get, and set for every leaf underneath that parent. Click
Next.
6. On the Create new fields for your ActionForm class page, click Add and type
the field name and type for each field you want to create. If you want to create
a form-bean mapping, click Next. Otherwise click Finish and skip the final
step.
7. On the Create a mapping for your ActionForm class page, make sure that the
Add new mapping box is selected and that the correct configuration file
name and mapping name are specified. Then click Finish.
Note: There are three other ways to invoke the Form bean mapping wizard.
– Double-clicking an unrealized form bean node in the Web diagram
editor.
– Expanding the project directory in the Struts Explorer view, right-clicking
the module, and selecting New -> Form Bean from the context menu.
– Expanding the module folder in the Struts Explorer view, right-clicking
the Form Beans folder, and selecting Add Form Bean... from the
context menu.
JSP wizard
A Struts JSP file is a JSP file that uses Struts tag libraries. If you select Struts
support in the JSP wizard as described below, you can (optionally) create a form
in the new JSP file that contains fields from a user-specified form bean.
Note: There are two other ways to invoke the JSP wizard.
– Double-clicking an unrealized Web Page node in the Web diagram
editor.
– Expanding the module folder in the Struts Explorer view, right-clicking
the Web Pages folder, and selecting Add JSP File... from the context
menu.
3. Fill out fields on the first New JSP File page, making sure that Struts JSP is
specified in the Model field.
5. Type the name of the new Struts configuration file and click Finish.
Exception wizard
To create a Struts exception, complete the following steps:
1. In the Project Navigator of the Web perspective (Window -> Open
Perspective -> Web), right-click the name of a project.
2. Click New -> Other -> Web -> Struts -> Struts Exception -> Next.
Module wizard
A Struts module is created automatically when you create a Struts project. To
create an additional Struts module, complete the following steps:
1. In the Project Navigator of the Web perspective (Window -> Open
Perspective -> Web), select the name of a project.
2. On the main menu bar, click File -> New -> Other.
3. Select Web and then Struts in the left pane and Struts Module in the right
pane.
Note: There are two other ways to invoke the Module wizard. Double-clicking
an unrealized Module node in the Web diagram editor will invoke the Module
wizard; right-clicking the project in the Struts Explorer view and selecting
New -> Module from the context menu will also invoke the Module wizard.
Note: When the Create a Resource Bundle for the Struts Project
option is selected, a properties file called
ApplicationResources.properties is created and placed in the Web
Content/WEB-INF/classes/<module name>/resources directory. This
file is read by the Struts framework at runtime.
3. Click Next. The Create a Web diagram page appears with a default parent
folder name provided.
a. If you want to specify a different parent folder, type the name or select it
from the choices in the box beneath the Enter or select the parent folder
field.
b. In the File name field, type the name of the Web diagram file that is to be
created.
c. If you want to associate the Web diagram with a module other than the
default Struts module, select a module from the Module drop-down menu.
The struts-config.xml file is located in the WEB-INF folder of the Web project.
Double-clicking the file opens the Struts configuration file editor. Once you have
completed making your changes to the configuration file, you must save it to
apply your changes.
Objects contained in the Struts explorer view can be dragged and dropped onto
the free-form surface of the Web diagram editor.
To view the organization of a Struts project in the Struts Explorer, complete the
following steps:
1. In the Web perspective, click Window -> Show View -> Struts Explorer. The
Struts Explorer view lists the names of the J2EE Web projects that exist in
your workspace.
2. In the Struts Explorer, you can click the + signs to expand the list into a tree
that lists the Web pages contained in a project. If the project is a Struts Web
application, you can also get a list of Struts artifacts that are associated with
the project.
3. You can expand each Web page to see the links that the page contains.
4. You can follow a link to the next page or action to see how the Web
application flows from the initial page.
This viewer takes selections from Struts Explorer and Web diagram editor as the
context, and if the selection is valid, the Data Mappings Viewer refreshes with the
new input.
When a valid input is selected, a table with two columns appears. The columns
contain the following information:
A list of all the fields that this form link contains, including the hidden fields
A list of properties in the form bean that can be set
Let’s assume that up to this point in our application, we have created all the
front-end content for our Web site. We now need to add the back-end content
and the administrative login will be the entry point.
Depending on the user name and password submitted, the user will see a
different administrative maintenance page. The “read access” administrator
(admin1) will see options to view customers and orders. The “write access”
administrator (admin2) will see the options to view, edit, and delete products.
Struts will be used to first validate the user name and password entries and then,
depending on the submitted values, the action will forward the user to the
appropriate page. A Struts action will also be used to log the user out of the
administrative section of the site.
The following JSPs and Java classes are created in this sample:
login.jsp - provides the interface to log in to the administration page
LoginForm.java - an instance of this class is used to validate the user input
parameters from the login.jsp page
LoginAction.java - an instance of this class is used to authenticate the user
admin1.jsp - displays the options to view a customer or an order
admin2.jsp - displays the options to view, edit, and delete products
LogoutAction.java - an instance of this class is used to log the user out of the
administration page and redirect the user to the login page.
The following diagram illustrates the sequence of events that occur when a user
attempts to log in to the administrative function of the site as a “write access”
administrator.
4
ActionServlet LoginAction
6
1
3 5
Web Browser 7
2
LoginForm
8 admin2.jsp
The steps in this sample will follow the same flow as outlined in 12.2.1, “Struts
development process” on page 389. The only difference is that after the Struts
components have been created, we will integrated the login.jsp page with the
rest of the application by adding a hyperlink to all of the pages.
The login function in the sample will use a JSP to verify that the user name
and password submitted are valid by referencing a table in the SALESAPP
database.
2. Right-click the folder and select New -> Other from the context menu.
3. In the New dialog, select Web -> Struts in the left pane and Web Diagram in
the right pane.
4. Click Next. The Web diagram wizard opens.
5. In the Create a Web Diagram window, accept the defaults and enter
LoginProcess in the File name field.
6. Click Finish. This creates a new Web diagram file, LoginProcess.gph, under
the WEB-INF folder and opens it in the Web diagram editor.
logout.label = Logout
logout.submitlabel = Logout
Tip: When you cursor over a node on the free-form surface of the Web
diagram editor, the name or path of the node is given. It also tells you if the
node is unrealized or realized.
Login page
To realize the login Web page node:
1. From the LoginProcess Web diagram, double-click the login.jsp Web page
node to invoke the JSP wizard.
2. Verify that the File Name field value is login.jsp and that the Model
drop-down has Struts JSP selected.
3. Click Finish. The login.jsp page is created and opened in Page Designer.
4. View the source of the page using the Source tab. Note that the taglib
directives are automatically added into the JSP. Also, a Struts-html form tag is
inserted with action /login.
Example 12-2 login.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html>
<HEAD>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" %>
<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<META name="GENERATOR" content="IBM WebSphere Studio">
<TITLE></TITLE>
</HEAD>
<BODY>
<html:form action="/login">
</html:form>
</BODY>
</html:html>
5. Right after the <BODY> tag, add a bean message tag by selecting
JSP -> Insert Custom from the main menu. An alternative way to do this is to
drag and drop the Custom icon from the toolbar on the right to the desired
location in the editing area. Both methods will cause the Insert Custom Tag
dialog to open.
6. Select the tag library with the prefix bean from the left pane and select the
message tag from the right pane.
7. Click Insert. You will notice that a <bean:message> tag has been added.
</BODY>
8. Click Close.
9. Add the key attribute to the bean message tag and set the value to
login.title.
<bean:message key=”login.title”></bean:message>
This value corresponds to a property set in the
ApplicationResources.properties file. At runtime, the Struts framework reads
the value of the property and the bean message tag displays it.
10.Click a spot inside the <html:form action=”/login”></html:form> tags and
add another bean message tag.
11.Add the key attribute to the bean message tag and set the value to
login.username.
<bean:message key=”login.username”></bean:message>
12.Add a <br> tag after the closing tag of the bean message.
13.Add another bean message after the <br> tag and set the key attribute to
login.password.
Example 12-4 Adding a second bean message tag
<bean:message key="login.title"></bean:message>
<html:form action="/login">
<bean:message key="login.username"></bean:message><br>
<bean:message key="login.password"></bean:message>
</html:form>
14.Click a spot after the username bean message tag and before the <br> tag;
add a custom HTML text tag and set the property attribute to username. This is
done in the same way as adding a custom bean tag, except that this time, you
must select the tag library with the html prefix (see Figure 12-27 on
page 434).
15.Click a spot after the password bean message tag and add a custom HTML
password tag.
16.Set the property attribute to password.
<html:password property=”password”></html:password>
17.Add a <br> tag after the closing tag of the HTML password tag.
18.Insert an HTML submit tag after the <br> tag.
Example 12-6 Adding a html submit tag
<bean:message key="login.title"></bean:message>
<html:form action="/login">
<bean:message key="login.username"></bean:message>
<html:text property="username"></html:text>
<br>
<bean:message key="login.password"></bean:message>
<html:password property="password"></html:password><br>
<html:submit></html:submit>
</html:form>
19.Click a spot between the opening and closing HTML submit tags and insert a
bean message tag; set the key attribute to login.submitlabel.
Example 12-7 Adding a bean message tag
<bean:message key="login.title"></bean:message>
<html:form action="/login">
<bean:message key="login.username"></bean:message>
<html:text property=""></html:text>
<br>
<bean:message key="login.password"></bean:message>
<html:password property="password"></html:password><br>
<html:submit>
<bean:message key="login.submitlabel"></bean:message>
</html:submit>
</html:form>
22.While in the Preview page of Page designer, the login.jsp page should look
similar to Figure 12-28.
Admin1 page
To realize the admin1 Web page node, follow these steps.
1. Realize the admin1.jsp page node in the same fashion that the login.jsp page
node was realized.
2. Once the admin1.jsp page is created and opened in Page designer, click the
Source tab. Note that the Struts HTML form tag is automatically inserted into
the JSP withthe action set to /logout.
3. Since the admin1 page does not contain any input parameters, we do not
need an HTML form tag. Remove the code associated with the HTML form
tag.
4. Add a message bean tag after the <BODY> tag and set the key attribute to
admin1.title.
<bean:message key=”admin1.title”></bean:message>
5. After the message bean title tag, insert the code shown in the following
example.
Example 12-9 Menu for admin1.jsp
<p></p>
<ol>
<li><html:link href="/OnlineCatalog/customerforward.do">View
Customers</html:link></li>
<li><html:link href="/OnlineCatalog/orderforward.do">View
Orders</html:link></li>
<li></li>
</ol>
Ignore the two warnings indicating the broken links. We are not concerned at
this point with what the menu system does, rather we simply wish to get the
login function working for our site.
6. Between the third set of <li></li> tags, add an HTML link tag and set the
href attribute to /OnlineCatalog/logout.do. This inserts a link to the Logout
action which redirects the administrator to the login page. As was the case in
the login.jsp page, a warning is displayed indicating that the target logout.do
cannot be resolved. This will be created later in the sample.
7. Between the HTML link tags, add a message bean tag and set the key
attribute to logout.label.
8. Verify that the code is similar to the following example.
9. While in the Preview page of Page designer, the admin1.jsp page should look
similar to the following diagram.
5. Click Next.
6. On the next page, navigate to the Web Pages folder and select the box beside
the login.jsp page.
7. Click Next.
8. On the next page, you will notice that the password and username fields have
been created.
9. Click Next.
10.Leave the defaults on the Create a mapping for your ActionForm class page
and click Finish.
This generates the template code for the LoginForm class and opens the
corresponding file in the Java editor.
return
errors;
3. Click Finish. This generates the template code for the LoginAction class and
opens the corresponding file in the Java editor. Replace the code for the
LoginAction class with the code from the following example.
//return value
ActionForward forward = new ActionForward();
forward = mapping.findForward("failure");
}
//END LOGIN LOGIC
if(!errors.isEmpty())
//Finish with
return (forward);
}
}
Note: For simplicity, the logic of authenticating the administrator has been
implemented within the action class itself. In a practical Web application,
the action class should invoke model objects which implement the
business logic.
8. Select the Action Mappings tab at the top of the page and verify that the
Form Bean Name field value is set to loginForm.
9. In the Action Mapping attributes area of the page, enter /login.jsp in the
Input field.
3. Replace the code for the LogoutAction class with the code from the following
example.
// return value
ActionForward forward = new ActionForward();
// Finish with
return (forward);
}
}
The final step in this process is to integrate the login.jsp page with the
application. To do so, we will add the page to the Web site diagram. This will
automatically add a hyperlink to all the pages in the application using the
predefined template we originally selected when we created the project.
For example, you cannot hyperlink the menu functions of either the admin1.jsp
or admin2.jsp pages to other pages. You would have to create an action for
each forward. If you are forwarding for forms, you would be required to create
form beans to capture the data and then create an action to perform any logic.
This would be done in the same fashion as was illustrated above.
1. From the Project Navigator view of the Web perspective, navigate to Web Site
Configuration and double-click it to open the Web site diagram for the
application.
2. With the diagram open, locate the login.jsp page, drag it from the Project
Navigator view and drop it behind the index.html page to create a child of the
index.html page.
3. To apply the template, select Page Template -> Apply Template... from the
context menu.
4. Disable the Navigation Candidate property by right-clicking the pages and
selecting Navigation -> Navigation Candidate from the context menu. If you
do not do this, all of the pages will appear in the site navigation.
5. Add admin1.jsp and admin2.jsp. to the Web Site Configuration and apply the
template.
6. Save the Web site diagram.
During runtime, when the user enters the username and password in the
login.jsp page and submits it, the following occurs:
1. The ActionServlet forwards the user input to the form class represented by
loginForm to validate the user input. The loginForm class and login.jsp should
For example, if the user authentication fails, the perform method returns an
ActionForward object corresponding to failure.
5. The ActionServlet then reads the ActionForward object and performs the
specified action. For example, if ActionForward to admin1page is returned,
the ActionServlet redirects the user to the admin1.jsp page.
In our sample, the admin1.jsp and admin2.jsp pages consist of the following lines
of code to insert a link to logout of the menu page.
<html:link href=”/OnlineCatalog/logout.do”>
<bean:message key=”logout.label”></bean:message>
</html:link>
The primary component of the Express Application Server is the Web container.
It provides the runtime environment for JSPs and servlets. It also contains an
embedded HTTP server capable of serving static HTML Web pages.
In this redbook, we will discuss using the Server tools to manage application
servers and deploy applications to them. Information about the administrative
console and commands can be found in the WebSphere Application Server -
Express V5.0.1 Administrator Handbook, SG24-6976.
Agent
Windows
Controller
Internet
user
Multiple servers, both local and remote, can be managed from Studio Site
Developer. Each server is a separate entity, meaning no workload management
is implied.
The IBM Agent Controller (installed with the Express Application Server)
provides the mechanism for communication between the Server tools and the
application server.
An FTP server is used on the remote systems to receive the application files to
be deployed.
Let us take a look at some of the views (as seen in Figure 13-2).
The Server Configuration view (bottom left) enables you to define or modify
server instances and configurations, and bind them to a project. When you
double-click the server in the Server Configuration view, the Server
Configuration editor opens.
The Servers view (bottom right) lists all the currently defined server instances.
Here you can start or stop their execution, or assign another server
configuration to a server instance.
The Console view (currently hidden by the Servers view) shows all the output
listed by a running server instance.
The default options are shown in Figure 13-3. Among the options, we
recommend paying attention to the following:
– Automatically publish before starting servers
Specifies that all the files should automatically be published before starting
the server.
The server definition defines the host where the server resides and the directory
information needed to locate the application server. Each server definition has an
associated server configuration that contains the information needed to set up
the runtime environment, such as port information, data sources, MIME types,
and session management information.
Server configuration a
Data sources
Class paths
Security settings
Host alias
Ports application 1
Server 1 Session management application 2
Host name: server1.ibm.com Class loader policy
WebSphere installation directory or
WebSphere deployment directory
DB2 driver location
Server configuration b
Remote file transfer definitions
Operating system
application 3
application 4
Server 2
Host: server2.ibm.com
WebSphere installation directory Server configuration c
WebSphere deployment directory
DB2 driver location application 1
Remote file transfer definitions
Platform application 2
Server and server configuration definitions are usually created at the same time
and for all practical purposes look like the same thing. They are represented by
one entry in the standard Server Configuration view. To view both the server and
server configurations, you will need to change the Server Configurations view to
its advanced setting.
When you open a server, the editor will show the information in a series of tabs.
The server definition consists of the items you see on the server tab when you
open it. The remaining tabs contain the server configuration information. You can
see this for yourself by opening a server that has no configuration associated
with it (you will only see the Server tab) or by opening a configuration that isn’t
associated with a server (you will see all the tabs but the Server tab).
Other types
J2EE Publishing server Used for publishing static Web and J2EE projects to
a remote location or a J2EE application server
(assumes port 80). This just copies the application
to the specified directory. It does not update
httpd.conf, nor does it allow you to start or stop the
server. It is always “started.” There is no stop option.
Static Web publishing server Used for publishing Web projects to an HTTP server.
TCP/IP monitoring server Allows you to monitor TCP/IP activity between the
Web browser and application server (does not
publish or run applications).
We will focus on the Express server and Express test environment. For
information on the others, please refer to the help contents in Studio Site
Developer.
Tip: If you are doing Web application development, you can create and use
the server environment directly from the Web perspective, as we are doing
here. You do not need to open the Server perspective.
2. Enter a server name and select the Express Test Environment option under
WebSphere Version 5.0.
3. Click Next.
4. Leave the default (7080) for the HTTP port. This option allows you to specify a
unique port for the server to avoid conflicts with other processes on the
system or with other servers. If you define multiple servers, setting this port to
a unique number for each server is not enough to allow you to run the servers
simultaneously. Servers actually use several port numbers in addition to this.
When the server configuration is complete, you can open it to the Ports tab to
view or change the ports.
5. Click Finish.
The new server environment will be configured and you will see it in the Server
Configuration view.
2. Select the enterprise application from the Available Projects list and click
Add.
3. The application will be deployed to the test environment and you will see an
entry for the application appear under the server.
You can create an enterprise application by selecting File -> New ->
Project. Select J2EE and Enterprise Application Project. Once you have
created the enterprise application, open the application deployment
descriptor (application.xml), switch to the Modules tab, and add the Web
module.
4. In the Servers view, you will see the server listed. The Server State column
indicates that the server needs to be republished. Although we have
associated an application with the server configuration, we have not actually
put the application on the server.
5. Select the server in the Servers view, right-click, and select Publish.
Once the publish is complete, the server state should indicate that the server
is synchronized.
2. The Console view will open automatically, showing you the server runtime
messages. Monitor the console for error messages as the server starts. If you
see problems or if the server doesn’t start, review the console messages,
correct the problem, and try again.
The message you need to see is the last one shown in Figure 13-13, Server
server1 open for e-business. This indicates that the server started
successfully.
Note that in this case, we tested the application by selecting the Web project.
You could also test segments of the application by selecting a specific file.
Obviously, the file you select needs to be a logical starting point in the
application.
2. You will be asked to select a server. Select the test environment server that
you just created and continue.
When you run the application, it will run on the server set in the
preferences. If the server is stopped, Studio Site Developer will attempt to
start it. This can be confusing if you have multiple servers and have not set
the ports for each server to be unique. If another server is running, you will
see port conflicts when the second server is started.
3. The application will open in a Web browser. You can exercise the application
code from there.
Be sure to keep an eye on the Console view to see if any error messages are
generated.
Tip: If you select Run on Server for an application that has not been
published you will be given the opportunity to create a new server or to run on
an existing server. This is a shortcut to the steps we have just been through;
however, we found that it did not save us any time and we liked controlling the
server creation and publishing process ourselves.
As we have seen from using the test environment, the first step to deployment is
to define the server to Studio Site Developer. Defining a remote server (remote to
Studio Site Developer, not necessarily on a remote system) is a little more
involved than defining the test environment. Additional information, such as the
location of the server, the remote server installation path, how to transfer the
application and deployment information to the server, and how to access the
HTTP port, is needed in order for Studio Site Developer to operate the server and
to deploy applications to it.
Click Next.
3. Enter the IP address or host name of the remote server. If the server is on the
same machine, enter 127.0.0.1 or localhost and click Next.
4. If the IBM Agent Controller is working properly, the directory location for the
WebSphere installation should be filled in for you. If you are going to use a
DB2 server for application data, enter the location of the DB2 driver on the
server system.
Click Next.
5. When an application is published from Studio Site Developer to the server,
the application files must be copied to the server. In this panel, you select the
file transfer mechanism to use when publishing applications to the server.
Because we are defining a server on the local machine, the copy mechanism
makes the most sense. This is also a good choice if you are copying files to
another Windows system and have a network mapping to the application
server’s local disk.
If you select the FTP file transfer mechanism, make sure that you have an
FTP server on the target system.
Click Next.
6. The next panel will differ depending on the file transfer mechanism you
selected. It allows you to enter the information necessary for the transfer to
take place, including the target directory (the server home directory).
Figure 13-20 on page 480 shows the window for the copy file option.
The definitions you enter will be stored for future use in other server
configurations. The Project folder and Remote file transfer name fields are
used to determine where this definition will be stored.
Tip: The remote file transfer settings are stored with a file type of .rft. You
can see these under the Servers folder in the Navigator view of the Server
perspective.
4. Select the server in the Servers view, right-click, and select Publish.
5. If the application will require any server definitions (for example, class path or
data source information), see 13.6, “Working with server configurations” on
page 483 for information on how to make these configuration changes.
You can see the new folders in two places on the server:
<server_install>/installedApps/DefaultNode/<ear_name>.ear
<server_install>/config/cells/DefaultNode/applications/<ear_name>.ear
The message you want to see is Server server1 open for e-business.
Note: If you have installed the Express Application Server on the same
machine as your Studio Site Developer system, there will be port conflicts
between the Express Application Server and the test environment. You will
need to stop one server in order to run the other. To run both at the same time,
you will need to alter the port numbers (for example, advance the number by
1) for one of the servers. The port numbers are defined on the Server
Configuration Ports page.
Note: The context root is defined when you create the Web project (see
Figure 4-4 on page 68). To see the context root, open the EAR deployment
descriptor to the Module page and select the module.
Note: You will notice as you go through the server configuration options, many
of the pages will give you the choice of entering information at the cell, server,
or node level. For WebSphere Application Server - Express, this does not
mean much since it is a single cell/node/server environment. Just follow the
lead of the examples. It is best to be consistent. If you define things at the
node level, then try to define everything at the node level.
At runtime the server will need to be able to load the classes and JAR files used
by the application. Classloaders are part of the JVM code and are responsible for
finding and loading these files.
The key to success is to understand how files are loaded and where to locate
them for proper loading. In order to understand this, we suggest that you read
J2EE Class Loading Demystified at:
http://www7b.boulder.ibm.com/wsdd/library/techarticles/0112_deboer/
deboer.html
For now, take the default classloader settings in the server configuration and use
the following guidelines taken from this article:
If your JAR file is only used in a single Web application, always put the JAR
file in the Web project's Web Content/WEB-INF/lib folder. JAR files in this
folder are automatically added to the Java build path, and will not require any
further setup when moving to a different server.
If the JAR file is used by multiple modules within the same application, put the
JAR file in the enterprise application. You will need to use the Edit Module
Dependencies feature to set up the manifest files and the Java build class
paths.
You can also put the JAR on one of the global class paths (using the Paths
servlet configuration page), but we don't recommend this. It complicates your
deployment and leaves your application vulnerable to incompatibility problems
if those JARs are later upgraded.
If you still want to put the JAR file on the global class path, you must decide
whether it should go on the class path or ws.ext.dirs. If the JAR file needs to
access any J2EE or WebSphere classes, or any other JARs that have been
added to ws.ext.dirs, it must also be placed on the ws.ext.dirs property.
Otherwise, you are free to use either property.
If you have dependencies on the JAR file, update the Java build path of each
project that uses the JAR file. Adding it to the global class path or ws.ext.dirs
4. Make sure that the three options are deselected. Because the EAR file will be
used in a production system, we do not want to include the source files or the
meta-data.
5. Click Finish to export the EAR file. The EAR file will be copied to the new
directory. Notify the administrator of the application’s location and provide any
information needed to install, for example, the name and location of
databases used.
</AgentControllerEnvironment>
Messages relating to the remote server operations can be seen in the IBM Agent
Controller log. The log is located on the server machine at
<express_install>/RAC/config/servicelog.log.
404 error
The 404 error page is displayed when a page being requested is non-existent.
This error could be the result of several problems:
The requested page has been moved or is named incorrectly.
The requesting page may be pointing to the incorrect URL for the requested
page.
To address the error, verify first that the page being requested is in the correct
location and is named correctly and then verify that the link that is requesting the
page is correct. For a 404 error, your best bet is to look at the Project navigator
and Tasks views for answers. For more information about these views, see
14.1.3, “Tasks view” on page 497 and 14.1.2, “Project navigator view” on
page 496.
500 error
The 500 error page is displayed when an internal server error has occurred.
With Java development, this is most likely the result of an error occurring when a
class or JSP was compiled.
These error pages do not really provide you with any significant information, but
they do point you in the correct direction. 500 errors can also be located using
the Project navigator or Tasks views, but the Console view may be of more help.
For more information about the Console view, see 14.1.5, “Console view” on
page 499.
You can navigate to the resource using the Project navigator view and then
double-click it to open it in its default editor. The editor can then be used to
correct the warning or error.
14.1.4 Editors
The Page Designer and Java editors are used to correct the conditions that
caused the warnings or errors. Two common ways of opening the offending file
and finding the errors are:
Double-click an entry in the Tasks view. The file with the error will be opened
using its default editor and the current line will be the line where the warning
or error exists.
Double-click a file with an error or warning icon in the Project Navigator view.
The file will be opened using its default editor, however the current line will not
be set to the line with the error (there may be more than one). You will need to
scan down the editor marker bar for the error or warning icons.
If an error is indicated with then the Quick Fix feature may be used to assist
in fixing it. This is only available in the Java editor. For more information on using
Quick Fix, please see “Quick Fix” on page 227.
The Console view shows errors that happen at runtime. When you test an
application by running it on a server controlled through Studio Site Developer,
this view will display server console messages.
The console shows three different kinds of text, each in a different color. You can
choose the different colors for these kinds of text on the preferences pages
(Window -> Preferences -> Debug -> Console).
When an error has occurred in a process, the Console view will display a
message similar to the figure below. The Console view is a good starting point
when a 500 error is received. The console messages may not give you the exact
location of the error, but they will give you the resource name where the error
occurred. This will allow you to debug the resource and locate the error.
You can open the Debug perspective by selecting Window -> Open Perspective
-> Debug from the main menu of the workbench.
Breakpoint view
The 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 new
ones.
Debug view
This view allows you to manage the debugging or running of a program in the
workbench. It displays the stack frame (it holds the return address, local
variables used, and procedure parameters within a thread) for the suspended
threads for each target you are debugging. Each thread (a single sequential flow
of control within a program) in your program appears as a node in the tree. It
displays the process for each target you are running. If the thread is suspended,
the stack frames are shown as child elements.
Threads
Stack frame
Variables view
This view displays information about the variables in the currently-selected stack
frame. If you look at Figure 14-10, you will notice that the view has been divided
into two areas. The upper area is a list of all the variables that have been used in
the corresponding file. Selecting a variable displays the variable value in the
lower area of the view.
Setting breakpoints
Breakpoints are indicators to the debugger that it should stop execution at
specific places in the code, and let you step through it. Breakpoints can be set to
trigger always or when a certain condition has been met.
In the editor area, open the file where you want to add the breakpoint. Directly to
the left of the line where you want to add the breakpoint, open the marker bar
(vertical ruler) pop-up menu and select Add Breakpoint. You can also
double-click the editor marker bar next to the source code line. A new breakpoint
marker appears on the marker bar, directly to the left of the line where you added
the breakpoint. Also, the new breakpoint appears in the Breakpoints view list.
Note: Enabled breakpoints are indicated with a blue circle. If the enabled
breakpoint is successfully installed in a class in the JVM at runtime, it is
indicated with a check mark overlay.
Breakpoint properties
Right-click the breakpoint in the breakpoint view, and select Breakpoint
Properties from the context menu. A window opens where more detailed options
about the breakpoint are displayed (Figure 14-12 on page 506).
The Enable Hit Count property, when set, causes the breakpoint to be triggered
only when the lines has been executed as many times as the hit count specified.
Once triggered, the breakpoint is disabled.
The other property of interest here is Enable Condition. If set, then the
breakpoint is reached only when the condition specified in the entry field
evaluates to true. This condition is a Java expression.
The Restrict to Selected Thread(s) list is only filled if a server is running in debug
mode already; otherwise the list in empty.
Studio Site Developer has extensive help information on this topic, including
debugging Java, JavaScript, stored procedures, and compiled language
applications. This section will take you through a common debug scenario and
point out the highlights of the debugger.
Let’s assume for this sample that we want to verify that the xslFile variable of the
FeaturedItemXMLServlet servlet is being set to the correct value. To do this, we
are going to set a breakpoint in the servlet, run the application in debug mode,
and then check the variable value using the Variables view.
Important: The server used for testing must be either stopped or already
started in debug mode. Otherwise, an error message will be displayed.
Breakpoint
Breakpoints view
Click the Breakpoints tab in the upper right window of the perspective to see the
Breakpoints view. Notice that the breakpoint that we set earlier is listed. If we had
additional breakpoints set in the current servlet or in other resources within the
OnlineCatalog project, they would be listed here as well. Double-clicking the
breakpoint will open the associated resource in its default editor and highlight the
breakpoint line in the source code.
Click xstFile and notice the value beside it and in the lower view area. The value
displayed is /Documents and Settings/bogers/My
Documents/IBM/wasexpress51/workspace/OnlineCatalog/WebContent/featured_
item/FeaturedItem.xst, which is what we are required to have for the
application. Had this been the incorrect value, we could have right-clicked xstFile
and selected Change Variable Value from the context menu to open the Set
Variable Value dialog and entered a different value with which to test.
You can continue to step through the application by clicking Resume in the
Debug view. You will again be prompted to skip or step into the next method. If
you wish to end the debug session, stop the application server from the Servers
view.
Unlike some other repositories, the Studio Site Developer does not have any
notion of object ownership. Write access is controlled only by the write
permission to the directory that holds the resource. Anyone who is authorized to
access the resource can create, edit, or delete it.
Every repository has at least one branch. Under certain conditions, more than
one branch can exist in a repository.
CVS records all changes to a given project in a directory tree called a repository.
CVS does not work with ordinary directory trees; you need to work within a
directory that CVS created for you. Just as you check out a book from a library
before taking it home to read it, you use the cvs checkout command to get a
directory tree from CVS before working on it.
Conflicts arise when you have modified a resource for which a more recent
version is available in the branch. In this situation, you can do one of three things:
Update the resource from the branch, commit your version of the resource to the
branch, or merge your work and the branch resource.
It is important to realize what CVS does and does not consider a conflict. CVS's
understanding of conflicts is strictly textual and it does not understand the
semantics of your program. From its perspective your source code is simply a
tree of text files.
The Studio Site Developer team environment works under the assumption that
the division of labor among the developers reduces the likelihood of true conflicts
(two developers altering the same resource).
4. Click Finish.
The repository will be added to the CVS Repositories view and, assuming the
connection information is correct, you can browse the repository contents.
Important: As you work with the CVS repository, keep in mind that the files
you are seeing are outside of Studio Site Developer. When updates are made
to the repository, whether you make them or someone else does, you may
need to use the refresh button ( ) to see the updates.
The first time you want to share a project by putting it in the team repository, do
the following:
1. From the Project Navigator view in the Web perspective (or any Navigator
view) select the Web project, right-click, and select Team -> Share Project
from the context menu.
2. The Share Project wizard will open and you will have a chance to choose an
existing repository location or to add a new one.
3. The next screen gives you a chance to specify a different module name. The
default is to use the project name as the module name. Click Next.
4. The final screen is informational so click Finish.
At this point three things have happened as a result of the wizard processing:
The information you have entered is stored as a Web project property. A new
folder called CVS and two new files under it called Root and Repository are
created in the workspace under the Web project folder to hold this
Note: When you disconnect a project from the repository you have the
option to delete these files. If you keep them, the next time you share the
project it will use these files for the connection. If you are changing
repositories, you should delete them when you disconnect.
A folder is created on the CVS server in the repository. The folder is empty
since nothing has been committed to it yet.
The Synchronize window opens in the workbench to show you the
discrepancies between the project in your workspace and the project in the
repository. Since nothing has been put in the repository yet, you will see all
the resources of the project listed in the Outgoing view. The resources will
have a gray arrow with a + in them, indicating they are new changes to be
sent to the repository.
Each time you commit a resource a new revision tag is associated with it.
Note: When you initially commit a Web project, a revision tag is associated
with each resource in the project because each resource is new to the
repository. This initial revision tag is 1.1.
Each time you commit a resource the revision tag is changed to the next level
(1.2, 1.3, etc.). If you commit at the Web project level, only changed resources
get a new revision tag, and that revision tag will be the next number in the
sequence for that resource.
In Figure 15-4 on page 523, you see the Synchronize view with the project
showing in the Outgoing Mode view. To commit you do the following:
1. Switch to the Outgoing Mode view in the Synchronize view, select the project
at the top, right-click, and select Commit.
Or select the project in the Project Navigator view, right-click the Web project,
and select Team -> Commit.
You will know that you need to do this because the option to commit will be
grayed out in the menu. In addition, a reminder is added to the Tasks view
when you add a resource.
It does not hurt to spot check the CVS repository to make sure you are
copying all the resources you intend to. If they are missing from the
repository, go back and add them to version control.
2. Enter a comment and click OK. If asked if you want to add the resources to
version control, click Yes.
The comment will be shown when you view the history of resources
committed with this action. If, for example, you are committing a project, you
might want to add a comment like Bug 0010 fixed in HTML files. If you are
committing an individual HTML or JSP file, you might want to add a comment
like Changed to use session attributes vs request parameters. The
comment should give you an idea of what happened in the revision.
If you are using the Synchronize view, you will notice that the entries in the
Outgoing view will disappear since they are no longer conflicting with the
repository.
3. Close the Synchronize view and switch to the CVS Repository Exploring
perspective to view the repository. You should now be able to see the Web
project and its resources under the HEAD branch. You may need to use the
refresh button ( ) to see the updates
Note: Versions are a snapshot of the state of a project at a given time. They
are not modifiable but are used as a reference point when comparing code or
as a starting point for development.
Note: You should not version your projects from the branch if you are not sure
what is currently committed in the branch.
In order to version a project it must be associated with a branch. If this is not the
case, you must first associate it.
Note: As you will see later, you should always synchronize with the
repository before committing changes so that you do not overlay changes
made by others. For simplicity we will assume you have done this.
4. Select the Web project Project Navigator view, right-click, and select Team ->
Tag as Version.
5. Enter a comment and click OK.
Once again, the comment should be meaningful, for example, BaseVersion,
Version1, etc. It will appear as a comment in the resource history in the Tag
column and beside the version in the CVS Repositories view.
A look at the new version in the CVS Repository Exploring perspective will show
you the resources that make up the version and their revision tags. Figure 15-5
on page 528 shows a version that has resources at two different revision levels.
The index.jsp resource is at revision 1.3. The Master.css resource is at revision
1.1.
To change the information click the Change Sharing button. You will be given a
list of repository locations that you can switch to. The only change allowed is to
another user ID on the same repository. In other words, the only repository
locations you can switch to must have the same server and repository.
If you want to send the project to a different repository you will need to
disconnect the project (Team -> Disconnect) from the current repository. This
does not affect the CVS server, but it erases the association between the project
and that repository. Then you follow the steps for adding an application to a
repository to put it on the other one.
Getting a copy of the current project is easy. The project should be available
under the HEAD branch.
1. Expand the HEAD branch in the CVS Repositories view and select the
project.
2. Right-click and select Check Out As Project from the context menu.
The project will be copied into your local workspace and you can switch to the
Web perspective to begin work.
Note: The local history of a resource will be reset every time you synchronize
with the branch.
To synchronize:
1. Select the project that you want to synchronize with the branch from the
Project Navigator view.
2. From the context menu of resource, select Team -> Synchronize with
Repository.
The project in your workspace will be compared to the branch. If there are
differences you will see them in the Synchronize view. There are three modes
in which resources are synchronized in the view:
– Incoming mode: Shows incoming changes only (resources in the steam
that differ from what is in the workbench).
– Outgoing mode: Shows outgoing changes only (resources that have been
modified in the workbench only).
– Incoming/Outgoing mode: Shows both incoming and outgoing changes.
You can switch to any of these three modes by using the view’s toolbar
buttons.
To see the difference in a workspace resource and the same resource in the
repository, double-click the resource in the Structure Compare area and both
versions will be opened in the Text Compare area. The workbench file is on
the left side and the repository file is on the right side.
To see true conflicts, click the Show only conflicts button on the Structure
Compare toolbar. Conflicts are indicated by a red arrow in the view.
If you find that you have a conflict, you can choose to do one of the following:
You can take the change from the branch (update to it) and discard your local
changes.
This could be the right action to take if you have made unintended changes
locally, or if you realize that the version in the branch is “better” than yours.
Overwriting your local changes should be done with caution since you are in
essence throwing work out.
You can commit your change, overwriting the copy in the branch.
Note: This should be done only with great caution and, if possible, after
consulting with the other developer(s). In essence you are throwing away
someone else's work. The change you are overwriting may have other
dependencies in the branch.
You can resolve the conflicts manually and mark the resource in your
workspace as “merged”. You may then later choose to commit this merged
result.
For example, let us assume that both you and another team member have
modified the same HTML page. Selecting that resource in the Synchronize view
will display a comparison of the local resource and the branch version. By cycling
through and resolving the individual conflicts by manually updating the code, you
can decide for each change whether to accept the incoming change, reject it, or
merge it with your local changes. When you are finished resolving the conflicts,
you save your changes in your workspace. You can subsequently commit this
merged resource.
You can resolve conflicts in the Incoming/Outgoing view in the following ways.
Whole document: In the Structure Compare editor, select the resource that
you want to merge so that the resource is displayed in the Text Compare
editor. In the Text Compare editor, click the Copy all from right to left button
to entirely replace the text in your local editor with the contents of the
repository copy.
Note: You will see more on comparing two files in 15.9.4, “Working with the
comparison” on page 547.
When you are done, you can save your local version by selecting Save in the
context menu of the text compare area for the local copy.
This will prompt you to save your changes. If you have updated your working
copy you will be reminded to mark the new file as merged when you are done.
This flags the resource as an outgoing change.
To mark the resource as merged, select it in the Structure Compare area, and
select Mark as Merged in the context menu.
Updating is the act of taking changes committed by others to the branch and
copying to your workspace, replacing your copy.
You can update your workspace with the work that has been done by other team
members and committed to the branch since you last synchronized. To update
workbench resources:
1. Select the resource or project in the navigator view you want to update.
2. From the context menu, select Team -> Synchronize with Repository.
3. In the Synchronize view, select the Incoming mode button on the view’s
toolbar. The resources that are different in the respository will be flagged. If
you want to see the actual differences you can double-click the resource and
the two versions will open in the Text Compare area.
4. Click the Show only conflicts icon to see a list of resources that have true
conflicts. If there are no conflicts (no red arrows), you can update the
resources in the workbench without losing any changes you have made.
Note: The branch itself is not changed when you update. When you accept
incoming changes, these changes are applied to your workspace. The branch
is only changed when you commit or merge your outgoing changes.
Note: Update first! You should update your local copy from the current branch
before committing your changes. This ensures that you have the very latest
work from the other team members.
To commit a resource:
1. Select the resource you want to commit from the Project Navigator view.
2. From the resource’s context menu, select Team -> Synchronize with
Repository.
3. In the Synchronize view, select the Outgoing mode button on the view’s
toolbar. You can see the outgoing changes in the Text Compare area.
4. If there are no conflicts, you can commit the resource, creating a new revision
of the resource in the branch.
If there is a conflict, use the Text Compare area to resolve your conflicts first.
Once all the conflicts have been resolved, you are ready to commit.
5. In the Structure Compare area, select the top-most resource in the hierarchy
and select Commit from the context menu.
When you have accomplished your task in the secondary branch you can merge
the relevant changes back into the HEAD branch.
Note: You need to be careful when using alternate branches. Adding a project
from the branch to the workspace via the CVS Repositories view or
associating it with another branch in another repository deletes all existing
synchronization information currently managed for the given project and
reinitializes with the new information for the newly added/reassigned project.
Using another branch in the same repository does not change the
synchronization information.
The new branch exists in your workspace and you can continue working with the
project. Any commits you perform will be done to the new branch.
If you want multiple projects associated with this branch, simply repeat these
steps and enter the same branch name for each project.
In the CVS Repositories view, expand Branches and observe that it now
contains the new branch.
To begin working with a project in the new branch, you will need to do one of two
things:
If you do not already have the project in your workbench, choose the project
under the new branch and select Check Out As Project from the context
menu. Switch to the Web perspective and you will see the new project.
If you do have the project in your workspace and want to associate it with the
new branch:
a. Switch to the Web perspective and select the project in the Project
Navigator view. From the context menu, select Team -> Branch.
b. Enter the new branch name. If you need a reminder of the branch names,
click Details. Click OK.
If the above operation does not result in the discovery of any tags, it is probable
that the folder in the repository does not have a .project file in it. The .project file
is the default file used by the tag discovery process. The file can be changed for
individual projects using Configure Branches and Versions.
To discover existing branch and version tags for a single project folder:
1. Switch to the CVS Repository Exploring perspective or add the CVS
Repositories view to the current perspective.
2. In the CVS Repositories view, expand the repository location.
3. Expand HEAD and select the root folder whose tags are to be discovered.
4. From the pop-up menu for the CVS Repositories view, select Configure
Branches and Versions. The Tag Configuration dialog will open.
5. In the top pane on the left (titled Browse files for tags), expand one or more
projects to find a file that is known to have tags that should be added to the
CVS Repositories view.
6. Select a file in the top left pane. If the file selected has tags defined on it, they
will be displayed in the right top pane (titled New tags found in selected files).
7. Select or deselect the tags in the right pane as desired.
8. Click Add Checked Tags to add the checked tags to the list of remembered
tags.
Note: It is important to realize that the destination of the merge is always the
project in your workspace. After the merge has completed, you should first test
the changes locally and only then commit them to the new branch.
The following is a scenario for working with multiple branches. It assumes that a
new branch was created to add maintenance fixes. Once the maintenance is
complete, the new branch is merged back into the HEAD branch.
Table 15-1 Working with multiple branches
Developer 1 (maintenance developer) Developer 2
Checks out the project from the HEAD Checks out the project from the HEAD
branch branch
Adds & changes files in the BeginMaint Adds and changes files in the HEAD
branch branch
To see the CVS server history for a resource select Team -> Show in Resource
History from the context menu of the resource in the navigator view. If you are in
the CVS Repository Exploring this is simply Show in Resource History.
You might need to maximize this view in your perspective to be able to see the
complete information. Each column can be sorted in ascending order by clicking
the column heading.
Tip: You can compare two revision levels of the resource in this view by
selecting both entries (Ctrl+click each) and select Compare from the context
menu.
Note: If you have not added the resource to version control then you will
only see the option to compare to local history.
2. In the compare dialog that will be opened, you can now browse to select the
version with which you want to compare the workbench resource. Notice you
can see the differences between the version and the workbench resource in
the text compare area.
The differences that will be highlighted show you what has been changed in the
workbench resource as compared to the common ancestor, and what has been
changed in the branch resource as compared to the common ancestor.
4. Select the Show Ancestor button to have the original file come up.
There are two parts in the compare editor's local toolbar. The right group of local
toolbar buttons allows you to move to the next or previous change:
Click the Select Next Change button to select the next change.
Click the Select Previous Change button to move to the previous change.
The left group of local toolbar buttons allows you to merge changes from the left
file to the right file and vice versa. There are four types of merges you can
perform:
Copy whole document from left to right.
Copy whole document from right to left.
Copy current change from left to right.
Copy current change from right to left.
Typically the copy whole document actions are used when you are sure that the
entire file on either the left or right can just be replaced by the contents of the
other file. The Copy current change button allows you to merge the single
changes one by one.
You can close and save the workspace copy by selecting Save from the context
menu of the left comparison window.
When you first commit a project, you are given the opportunity to add the
resources currently in the project to version control. If you select this option all
files will be included.
However, there may be some files that you never want to send to the repository,
for example, .class files. You can automatically exclude these from any commits
by doing one of the following:
Use the global ignore facility to specify file names or patterns that apply to all
projects in the workbench.
To add a global ignore pattern for the workbench, simply select Window ->
Preferences to open the Workbench preferences dialog and select the Team
-> Ignored Resources category. Click Add to add the pattern to ignore.
Use the CVS Ignore facility to specify file names or patterns that apply to a
specific project directory.
Note: The ignore file only relates to the files and folders contained in that
directory, so you may require many .cvsignore files throughout the project.
For example, if you want to create a .cvsignore file that will keep anything in
the classes folder from being sent to the repository:
a. Select the WEB-INF/classes folder, and select Team -> Add to
.cvsignore from the context menu.
b. Select the wildcard extension option. This will create an entry in .cvsignore
to exclude all files with an extension like the one you selected, or if you
selected a folder, all files in the folder.
c. Click OK.
To work with the .cvsignore file you will need to switch to the Resource
perspective. You will not see it in the Project Navigator view. When using this
method, it is a good idea to:
a. Create the .cvsignore files before you commit for the first time.
b. Add the .cvsignore files to version control so they are copied to the
repository and others pick them up with the project.
Physical security is the most basic type of security, providing protection against
physical access to the computers. Logical security involves protecting the
applications and network from unauthorized access or harm. This normally
involves the use of firewalls and other security products that filter out unwanted
network traffic and ensure that only valid users can access the applications and
resources that constitute the business.
Note: For any type of authentication to take place, you must have enabled
WebSphere security and secured at least one resource.
Note: The j_security_check servlet will not work when global security is
disabled; the application server will return a page not found error. See
“Enable WebSphere global security” on page 566.
2. Open the Web deployment descriptor (web.xml) for the project and select the
Pages tab.
a. Enter a realm name.
b. Click the drop-down list and select FORM as the authentication method.
c. In the Login page click Browse and select login.html.
d. In the Error page click Browse and select loginerror.html. (We have used
the same page for log in and error. You can define a custom error.jsp page
that will present an actual error code and error message.)
3. Save and close the deployment descriptor.
At application development time, these sets of users, or security roles, are not
tied to any real users or groups of users. Instead, they are placeholders that are
later mapped to real users and groups at application deployment time, during a
process called security role mapping.
Security Roles
Principals and Groups
Servlets
Consultant
Static Content
Iza
Security Role
Mapping
Accountant
Department XYZ
Staff
With programmatic security, you can go further by checking the roles before
allowing certain actions to take place. For example, if a customer tried to transfer
over 50 percent of her balance from one account to another, the servlet could
check to see if the customer had the GoldenClub role and only allow the transfer
if true.
Servlets can be protected at the method level by naming roles that are
authorized to use the method. The key here is to remember that when it comes to
running a JSP on a server, the JSP is actually executed as a servlet. So when we
talk about securing servlets, you can mentally include JSPs in the discussion.
Protecting servlet methods using J2EE security involves the following steps:
1. Define users and groups to the server operating system. Express Application
Server will use the security system of the server’s local operating system to
authenticate users and groups.
Note: In this example we are actually adding a second layer to the our
application security. The first layer is programmed using the login servlet. To
get past that checkpoint, they need to know the user ID and password stored
in the application database (admin/admin). This method was used to illustrate
a simple login procedure based on information stored in a user database and
is not related to WebSphere security.
In the second layer of security we are going to ignore this first login and secure
the application at the JSP level using J2EE role-based security.
Figure 16-3 on page 559 shows an overview of the security settings for an
application and their relation to each other.
Authorized roles
web.xml (servlets tab) CatalogAdmin
OrderDept Security constraint (2)
servlets Methods
MasterCatalogView (optional) Get method
URLs Put method
/MasterCatalogView
/Administration/MasterCatalogView Authorized roles URLs
CatalogAdmin /Administration/OrderCatalogView
OrderCatalogView OrderDept
URLs
/Administration/OrderCatalogView (optional - can be used
for programmatic
security)
Note: You may notice the Security Role References box on the servlets
page. This is used with programmatic security. It allows the developer to
hardcode roles in the application that may not match the roles defined to
the Web module. The role used in the application are linked to real roles in
the deployment descriptor. For this exercise you will not use this. At this
level of Studio Site Developer, this feature is not very useful. As you
migrate up to more complex levels of WebSphere Studio and WebSphere
Application Server, you will most likely implement this, if necessary, in the
AAT tool provided with the higher level servers.
2. Switch back to the Security tab, select the Security Constraints tab, and
click Add below the window. A new Security Constraint entry will appear in
the box and a new New Web Resource Collection entry in the panel beside it.
3. Select the New Web Resource Collection entry and click Edit. This allows
you to enter the URL(s) or URL patterns for the Web resources you want to
protect. Enter the patterns and select the HTTP methods you want to protect.
In this case it is sufficient to select the GET and POST methods, but it does
not hurt to specify all of them.
Click OK.
Note: You also have a user data constraint option on the Security page. The
user data constraint options allow you to chose a transport guarantee, which
defines how the communication between the client and the server is to be
protected. There are three options to choose from:
None
No constraint indicates that the application does not require any transport
guarantee.
Integral
This ensures that data cannot be changed in transit. In practice, this means
that a request must be transmitted over an SSL-encrypted channel.
Confidential
This ensures that data cannot be changed or viewed in transit. In practice,
this means that the request must be transmitted over an SSL-encrypted
channel.
2. Click Gather to collect the roles defined in the Web modules. Note that this
allows you to define the roles in multiple Web modules that belong to this
enterprise application and easily collect all roles with the click of a single
button.
3. Assign users to the roles. If you want to select individual users or groups
select the Users/Groups box. Two other special categories are available,
Everyone and All authenticated users. Selecting Everyone is effectively the
same as not securing the resource. Selecting All authenticated users has the
effect of allowing anyone who successfully logged in to access the resource.
Note: The “Security Role Run as Bindings” settings only apply to EJBs.
You will need to republish the application and restart the server for all changes to
take effect. The next time you attempt to execute the JSP, you will be challenged
for a user ID and password. The user ID you enter must be assigned the
CatalogAdmin role.
With form-based authentication, the user has the option to log out of one user
ID and log in with another.
Having said that, when developing servlets there are a few security calls
available if the developer wants greater control of what the end user is allowed to
do than is provided by the infrastructure. Programmatic security can be used as
an extension of declarative security.
The Servlet 2.3 specification defines three methods that allow programmatic
access to the caller’s security information of the HttpServletRequest interface:
String getRemoteUser()
The getRemoteUser method returns the user name that the client used to log
in.
String user = request.getRemoteUser()
Boolean isUserInRole(String roleName)
The isUserInRole method allows the developer to perform additional checks
on the authorization rights of a user, which is not possible (or is more difficult)
to perform through the deployment descriptor of the servlet.
if (request.isUserInRole("Manager")) {
// the user is in the manager role
// ...
}
If you opt to program J2EE calls into your application, you need to do the
following:
1. Define users and groups to the Express Application Server operating system.
2. Define roles for the application in the Web module deployment descriptor.
3. Define constraints (optional).
4. Assign users or groups to roles in the Web module deployment descriptor.
5. Define the authentication method.
6. Code the servlets to retrieve and check the user role.
7. Enable global security on the Express Application Server.
Note that the first four steps are the same as those needed to implement
declarative security. The difference is that you do not need to enable WebSphere
global security and you must add code into your application to provide
authorization.
To illustrated this type of security, let us take an example from the Online Catalog
sample. As supplied with this publication, the sample uses two different methods
of authenticating to the SALESAPP database.
In the first method, the user ID and password required to access the database
are coded within the Web module. The JSPs generated by the Database Web
Pages wizard use this method. The wizard registers each JSP as a servlet in the
Web deployment descriptor and defines three initialization parameters to hold
values for accessing the database: The data source name, the user ID, and
password.
When the JSP connects to the database, the user ID and password are retrieved
from the initialization parameters and used by the jspsql taglib to authenticate to
the database. This method is a little awkward in larger applications because
every JSP that accesses the database need to have the user name and
password initialization parameters defined in the deployment descriptor. The
wizard does this for you automatically, but if you ever need to change the values
you have to update every servlet. Secondly, the password is stored in the clear.
In the second method, JAAS security is used for authentication. This is shown in
Figure 16-12 on page 571. In this case, you do not supply the user ID or
password for database authentication in the application. They are stored under
an alias in the server configuration, and a pointer to that alias is put in the data
source. Whenever the database is accessed, the user ID and password
information in the alias is used for authentication. The advantage is that the user
ID and password are stored in one place and the password is encrypted.
Server configuration
Name: SALESAPP
Data source JNDI name: jdbc/SALESAPP
Component-managed authentication alias: salesAlias
6. Save your changes and close the editor. A JAAS authentication alias has
been added to the server.
This configuration will allow access from all machines in the 192.168.0.0 C-class
network except 192.168.0.1. It will also allow access from the host “steamboat”.
All other requests are denied.
RAC security now on, only users of this computer may access RAC
Once security is turned on and RAC has been restarted, you will receive a logon
prompt when you attempt to access the server. RAC authenticates against the
operating system security so the user must be a valid user on the server
operating system. On Windows, domain name passwords will not be
authenticated. You must provide local user name and password pairs. An internal
certificate is used so there is no need to obtain one.
The user definition elements define a single user with ANY being a wildcard for
any user with a user ID on the host system. If you want to restrict access to
specific users, you would need to define a <UserDefinition name="ANY" ..../>
element for each user (see Example 16-4).
Example 16-4 Restricting access to specific users
<Security configuration="default" library="GSK_SSL"
clientAuthenticate="FALSE" aclEnabled="TRUE"
keyDB="d:\progra~1\ibm\websphere\express\RAC\security\ibmrac.kdb"
keyDBPasswordStashFile="d:\progra~1\ibm\websphere\express\RAC\security\ibmrac.s
th">
<UserDefinition name="wasadmin" authenticationType="OS"/>
<UserDefinition name="mark" authenticationType="OS"/>
</Security>
After you have enabled (or disabled) the security, you can continue with the
installation process.
3. To add a certificate, click Add and then locate the Security Certificate and
specify an Alias name in the Add Certificate window. You may create more
than one if required.
To enable SSL:
1. Select the Sever perspective and open the server configuration.
2. Select the Ports tab.
3. Click Add next to the HTTP transport list in the Server Settings section.
4. Enter the port number and select the Enable SSL check box.
5. Click OK.
This will add a new port to your server. If the Enable SSL check box is checked,
then this port will be used in a secure environment. Now the applications that are
running on this port will be accessible using SSL only.
At the time of writing, Studio Site Developer V5.1 included four solution
templates, two IT templates, and one tutorial template. Aside from these seven
templates, the wizard also enables you to download additional templates from:
http://www7b.software.ibm.com/wsdd/zones/studio/rad/
After the Template application wizard has been used, a Web project is added to
the workbench that includes all the necessary JSPs, HTML pages, Java Beans,
etc. to form a viable end-to-end Web application. All of the resources related to
the project can be modified and deleted in the same manner as they would in a
new Web project. You can also expand on the foundation of the Web project and
added resources were required.
Content area
Roadmap
The roadmap provides visual cues as to your progress through the wizard. You
can use the roadmap icons to see which tasks you have completed and what
remains to be done. An arrow indicates your current position in the task
sequence. You can return to a previously completed task of the roadmap by
Below is a table describing the task icons that appear in the Template Application
Wizard roadmap.
Table A-1 Template application wizard icons
Icon Name Description
4. Select the Solution Templates folder and then select the Resource
Reservation template option.
5. Click Next.
6. On the Application Information page, specify the Project name or keep the
default. You can also specify a Description and/or Author for the project. For
this tutorial, we keep the default values. Notice the roadmap on the left side of
the wizard. An arrow is placed beside your current location in the roadmap.
If there are no conflicts, the pages in the roadmap will be visually marked with
a checkmark symbol once they are completed.
Note: At any point during the wizard, click Preview Application... to view the
current look of the application. The preview will reflect the wizard
customizations that have been specified.
7. On the Application Properties page, you can specify the type of application
generated. If the template has defined these features as adjustable, you can
also choose a style and a logo that will determine the application's
appearance. We keep the defaults for this tutorial.
8. Click Next.
9. The Application Features page allows you to select the features that affect the
structure and flow of the generated application.You can check any feature to
see its description at the bottom of the page, and to see how it affects the
structure of the application, as reflected in the roadmap at left. Check those
features that you want to include in your application. This page will be slightly
different for each template. We keep the defaults for this tutorial.
10.Click Next.
11.The Database Connection page allows you to define the database to which
your application is connected. Verify whether the database that is specified is
the one you want to use. If you need to change the database connection, click
Set Database... and define the connection parameters. To see the structure
of the database click Database Requirements.... A window will open that
displays a list of the tables and columns for the database. Click OK to close
the window. We keep the defaults for this tutorial.
12.Click Next.
13.The Menu Configuration page presents the menu (navigation bar) of the
application and allows you to edit the labels of the menus presented on the
various pages of the generated application. To edit the menu labels select the
menu item and click Rename.... Enter in the label name and click OK. We
keep the defaults for this tutorial.
Note: Aside from being able to preview the application you can also preview
the individual web pages. To do this, click Preview Page... and then select the
page that you wish to view. This option is only available in the Menu
Configuration page and each of the Web Page Content pages.
14.Click Next.
15.The Web Page Content page allows you to edit adjustable data for the Web
pages of your application. If adjustable, you can modify the title of the Web
pages and the title of the Web pages' views. You can also edit the label, type,
and order of the widgets in the Web page, as well as the mapping of the
widgets to the tables and columns in your database. The various buttons are
enabled only if that function is available for the selected Web page object.
– Use Add to place additional widgets in your application.
– Use Edit to change the settings for the type, label, table or column of each
field. When editing the field properties, remember to replace items only
with other compatible items.
– Use Remove to remove a custom data element from the Web page
(widgets predefined by the template cannot be removed).
16.Click Next for each of the Web Page Content page as we are keeping the
defaults for this tutorial.
17.The Additional Data page allows you to map data fields that are used for the
internal logic of the application, and are not displayed in the application's
interface for user input or information. Depending on the features and
properties you selected in previous tasks, these fields may or may not require
configuration. To configure the fields click Edit.... We keep the defaults for this
tutorial.
18.Click Finish. This saves your template customizations and then generates the
code for the application. A notification window will be displayed indicating to
you that the code was generated successfully. The window will ask if you
would like to run the application on the server. Click Yes to run the application
in a test server or click No to close the wizard. The Web project will be added
to the workspace and will be displayed in any navigator view.
This site will provide a listing of PTFs available for download. Follow the
installation instructions provided with the PTF.
You can launch the update manager by selecting Help -> Software Updates ->
Update Manager from the menu bar. This opens the Install/Update Perspective.
Note that you can also open the perspective Install/Update directly.
Install configuration
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
This view allows you to locate and install new features and feature updates.
Selected Updates
This view displays a list of all selected updates. Updates are added and removed
from this list by checking or unchecking the Install by adding to the Selected
Updates check box on the update preview pages.
If you right-click an update you can install it by selecting Process from the
context menu. If you wish to install all of the updates in the view right-click inside
the view and select Process All from the context menu.
Preview
This view displays detailed information about the current active selection. Its
content changes according to your selection.
External preview
The External Preview view, which is part of the Install/Update perspective, is an
embedded browser used to display HTML information. This view is available only
on Windows systems. In general, the External Preview is used when links are
followed to HTML pages.
Updating features
There are two ways to update features using WebSphere Application Server -
Express:
New updates feature
Feature updates view
Tip: When an update feature is displayed in the Preview view you can check
the Install by adding to the Selected Updates check box to add the update
to the Selected Updates view.
To check to see whether there are updates for a product's existing features
(requires Internet access):
1. Expand a site bookmark to locate feature updates.
2. Click an update to open it in the Preview view
3. Click Install Now to install the update. The Feature Install wizard opens.
4. The Feature Install wizard confirms the details of the feature you are about to
install. Click Next.
5. Carefully review the license agreements for the upgraded features. If the
terms of all these licenses are acceptable, check “I accept the terms in the
license agreements”. Do not proceed to download the features if the license
terms are not acceptable.
6. If a feature selected for install include optional features, a page will show up
allowing you to select whether you want them installed or not. Optional
features typically carry functionality that is not essential for proper functioning
of the main feature.
7. The Install Location page controls where the new feature's files are to be
installed on the local computer. Select the directory into which the product is
installed and click Next (If the product is installed in a directory to which you
do not have write access, you should contact your system administrator and
get them to install this feature so that it will be generally available. The other
option is to click Add and point to a directory to which you do have write
access; however, features installed there are only available when using the
current workspace.).
8. Feature versions can be digitally signed by the company that provides them.
This allows you to verify more easily that the features and plug-ins that are
about to be downloaded and installed are coming from a trusted supplier.
9. Click Install to allow the downloading and installing to proceed.
10.Once the new feature and plug-ins have been downloaded successfully and
their files installed into the product on the local computer, a new configuration
that incorporates these features and plug-ins will be formulated. Click Yes
when asked to exit and restart the workbench for the changes to take effect.
To add other new features at the same time before restarting, click No and
repeat.
You can also add site bookmarks by right-clicking the Site to visit folder and
selecting New -> Site Bookmark.... This opens the New Site Bookmark dialog.
Specify the Name and URL for the bookmark. You can also specify the type of
bookmark as an Eclipse update site or a Web site. Lastly, you can specify which
folder to add the bookmark to. If no value is entered the bookmark will be added
to the root of the Feature updates view.
My computer folder
This folder is a file explorer that can be used to navigate to updates located in the
file system. This method is used if you previously dowloaded updates from the
WebSphere Application Server - Express and/or WebSphere Studio Site
Developer support Web sites:
http://www-3.ibm.com/software/webservers/appserv/express/support/
http://www-3.ibm.com/software/awdtools/studiositedev/support/
Once you have download the update file(s), you receive a ZIP file. To install this
update, you have to extract the ZIP file.
Expand the My Computer tree to the folder where you have unzipped the
package and click Install Now in the Preview view to open the Feature Install
wizard. Follow steps 4 to 10 from “Site to visit folder” on page 602 to install the
update.
From a lower-level perspective, we can outline the list of components that provide
the aforementioned functionality:
A main application menu, which lists the options available to the user
A registration process where new users enter their details
A search mechanism, which provides shoppers with a fast means to find
items of interest, based on a keyword description
A shopping cart, which lists the items currently selected by the user, and also
provides editing functionality for the user to modify his choices
An order completion mechanism
Database architecture
Persistent data from our sample application is maintained in database tables. In
keeping with our intent to keep things simple, the tables were designed with a
basic approach in mind, with columns clearly labeled and constraints kept to a
minimum. One may notice that, in some places, the use of constraints and
triggers might have been justified. However, in cases where implementing these
features might have complicated the issue and distracted us from our initial
purpose, we took a conscious decision to do away with them.
User information was not stored directly in our application database. Since
WebSphere provides functionality to store user profiles in a predesigned
SALESAPP database, we decided to make use of this feature to simplify the
implementation of an authentication mechanism and storage of user-related
data.
ITEM_NUMBER character 5 N Y
ITEM_SHORT_DESC varchar 50 Y N
QUANTITY integer Y N
SOTD_FLAG character 1 Y N
CUSTOMER table
The CUSTOMER table contains information about registered customers.
Table C-2 CuSTOMER table
Column type Length Nullable Key
CUSTOMER_ID character 10 N Y
CUSTOMER_NAME varchar 40 Y N
ADDRESS varchar 40 Y N
CITY varchar 40 Y N
STATE character 2 Y N
EMAIL_ADDRESS varchar 20 Y N
PHONE character 10 Y N
CC_TYPE character 2 Y N
CC_NUMBER varchar 20 Y N
ZIP character 5 Y N
INTEREST1 character 1 Y N
INTEREST2 character 1 Y N
PASSWORD character 10 N N
ORDER_NUMBER integer N Y
CUSTOMER_ID character 10 N N
ITEM_NUMBER character 5 N N
QUANTITY smallint Y N
ORDER_DATE date Y N
STATUS character 1 Y
USERS table
The USERS table contains users with administrative capabilities.
Table C-4 USERS table
Column type Length Nullable Key
USERNAME character 8 N Y
PASSWORD character 8 N N
Application components
The following sections give an overview of the Online Catalog application
components.
Application root
The index.html page is the entry point of the application and it is located in the
WebContent folder. This page contains links to the other main components of the
site. For additional information about this component please see “Adding HTML
pages to the Online Catalog sample” on page 135.
Featured item
The Featured item component of the application is comprised of a servlet and
XST file. The servlet takes information from the XST file and creates HTML
output for the user. The output is a table that lists the feature items as indicated
by the SOTD_FLAG field of the ITEMS table. The diagram below illustrates the
flow of the different components in this process.
requests queries
calls creates
transforms
Homepage Servlet
XML and XSL strings HTML string
(output to user)
The table below lists the main files involved in this portion of the application.
Table C-5 Featured item items
Item Folder/Package Description
Site administration
Administrators can update the catalog by going through the Site administration
option. This prompts a login. By default the application uses a simple login
mechanism that requests the user ID and password, then compares that to
entries in the SALESAPP database.
The table below lists the main files involved in this portion of the application.
Table C-6 Site administration items
Item Folder/Package Description
Catalog
Users of the site can display the entire catalog or search for items in the catalog.
If the user sees an item of interest, she can display the details of the item and
then add it to a wishlist, if desired.
The table below lists the main files involved in this portion of the application.
Wishlist
Once the user has added items to the wishlist, this list can be sent to the
company by adding it to the Orders table in the SALESAPP database. In order to
do this, the customer must be a registered user. Being registered means that an
entry with customer information has been stored in the Customers table of the
SALESAPP database.
The table below lists the main files involved in this portion of the application.
Table C-8 Wishlist items
Item Folder/Package Description
HttpSession
The HttpSession class supports built-in session tracking between the client and
the server, by user. The Web container provides an implementation of the
HTTPSession interface giving the application’s Web components access to the
methods of the HTTPSession interface.
Every time the client makes a request, the servlet gets the session object
associated to him or her through the identifier (a new session is created if the
user does not have any) and performs operations on it.
The session identifiers are managed by the container which ensures that there is
one session for each user. The API provides methods to destroy a session,
typically used when a user logs out.
The following shows an example of handling the HttpSession objects; this code
can be included in the service method of a servlet.
Example: C-1 Using the HttpSession interface
HttpSession session = request.getSession(true);
if (session.isNew()) {
}
else {
// perform actions for a user identified
...
...
}
There are two getSession methods in the HttpServletRequest interface which can
provide the session to the servlet:
public HttpSession getSession(): This method returns the session associated
with the request and creates one if there is not one already.
public HttpSession getSession(boolean create): This method does the same
thing unless create is set to false. In that case, the method returns null if there
is no session associated with the request.
Session objects are stored on the server and provide the standard interface to
manage sessions in applications. Session data objects (that is to say, the objects
stored in the sessions) must implement the Serializable interface and they are
stored on the server (within the HttpSession instances).
The Java Servlet API supports two ways to associate multiple requests with a
session: cookies and URL rewriting. In either case, the implementation details in
the servlet are the same. The unique session ID is used to track multiple
requests from the same client to the server, and this is what is passed as the
URL or cookie parameter. The actual session object that we are tracking is
maintained on the server.
Information request
Customers can request additional information by sending an e-mail to the
company.
The table below lists the main files involved in this portion of the application.
Table C-9 Information request items
Item Folder/Package Description
Note: For additional information about this component please see “Using a
tag library in the Online Catalog sample” on page 301.
Currency conversion
The currency exchange option uses a Web service to convert amounts from one
country’s currency to another’s.
The table below lists the main files involved in this portion of the application.
Table C-10 Currency conversion items
Item Folder/Package Description
Note: For additional information about this component please see “Using Web
services in the Online Catalog sample” on page 372.
Deployment descriptor
Numerous URL mappings have been set in the Web deployment descriptor. Click
the entries of the Servlets and JSPs page to see the mappings. If these
mappings are not set, you will see warnings in the Tasks view indicating that
broken links exist. All of the database driven JSPs also have an initialization
parameter set for the data source. The action entry also has initialization
parameters set that are required for the Struts login component.
Servlet login
The first step in the login process is login.html. This page collects the user name
and password from the user and passes control to LoginServlet. LoginServlet
captures the user name and password from the login.html form, verifies them
using additional database connection wizards, and then forwards the user to the
site administration selection page; admin.html.
The table below lists the main files involved in this portion of the application.
Note: For additional information about this component please see “Using
servlets in the Online Catalog sample” on page 232.
Struts will be used to first validate the user name and password entries and then,
depending on the submitted values, the action will forward the user to the
appropriate page. A Struts action will also be used to log the user out of the
administrative section of the site.
LoginAction.java LogoutAction.java
LoginForm.java
The table below lists the main files involved in this portion of the application.
Table C-12 Struts login items
Item Folder/Package Description
Note: For additional information about this component please see “Using
Struts in a sample” on page 425.
Select Additional materials and open the directory that corresponds with the
redbook form number, SG24-6555.
Important: This sample was created during the redbook project as a way of
discovering things about the product. It is provided for your convenience in
case you want to browse through the code. It is a “living” sample, which means
it may change over time. What you see in the downloaded sample may or may
not be exactly the same as you see in the book. We can also almost
guarantee that you will find bugs in the code that were not fixed during the
project.
After you have installed the Studio Site Developer component of WebSphere
Application Server - Express, perform the steps described in the following
section.
Note: If you use a user ID and password other than db2admin, you may
run into problems. These are assumed several places in the application. If
you use something else, be sure to change the dbconn.jspinc,
FeaturedItem.xst, and db.properties files in the application.
By default, the db2java.zip file does not support the JDBC 2.0 specification.
You need to open the sqllib\java12 folder and execute usejdbc2.bat to copy
the correct drivers to the zip file.
2. Open a command window and change to the directory where you unzipped
the additional materials file.
3. Execute Step 1-RunCreateDB.cmd.
4. Open the DB2 Control Center. Right click the SALESAPP database and
select Authorities.
5. Click Add User.
6. Select the DB2ADMIN user and click OK.
7. Select (highlight) DB2ADMIN in the list of users and click Grant All.
8. Close the Control Center.
4. Select the server in the Server view, right-click, and select Control ->
Publish.
The publications listed in this section are considered particularly suitable for a
more detailed discussion of the topics covered in this redbook.
IBM Redbooks
For information on ordering these publications, see “How to get IBM Redbooks”
on page 645.
WebSphere Application Server - Express: A Development Example for New
Developers, SG24-6301
WebSphere Application Server - Express V5.0.1 Administrator Handbook,
SG24-6976
Migrating Applications from IBM WebSphere Application Server Standard
Edition to WebSphere Application Server - Express Version 5, REDP3618
Migrating to WebSphere Version 5.0: An End-to-End Migration Guide,
SG24-6910
IBM WebSphere Application Server V5.0 System Management and
Configuration, SG24-6195
IBM Framework for e-Business: Technology, Solution, and Design Overview
SG24-6248
IBM WebSphere Version 5.0 Security WebSphere Handbook Series,
SG24-6573
Servlet and JSP Programming with IBM WebSphere Studio and VisualAge for
Java, SG24-5755
The XML Files: Development of XML/XSL Applications Using WebSphere
Studio Version 5, SG24-6586
WebSphere Version 5 Web Services Handbook, SG24-6891
WebSphere Studio Application Developer Version 5 Programming Guide,
SG24-6957
Index 649
host variable 184, 187 JDBC overview 154
HTML 60 JDBC provider 156, 196, 200–202
creating pages 135 JNDI 62, 155, 196, 206, 278–279, 485
HTTP 1.0 218 JNDI name 185, 207
HTTP request 216 JSP
HttpServletRequest 254, 568 actions 246
HTTPSession 623 directives 246, 248
HttpSession 298, 623–624 elements 246
expressions 253
forward 254
I getProperty 254
IBM Agent Controller 476–477, 491, 573
include 254
image 60, 122, 127
include directive 251
adding 118
overview 242
adding to animated GIF 131
page directive 250
building with WebArt Designer 124
param 254
map 118
plugin 254
implicit object variables 254
request phase 243–244
import attribute 249
root 245
include directive 250
scripting elements 246, 252
include tag 255
setProperty 254
index 38
syntax 244
info attribute 249
tags 250
input field 119
translation phase 243, 250
installableApps 490
useBean 254
interface 362
XML syntax 252
isErrorPage attribute 249
JVM 486
isThreadSafe attribute 249
JVM arguments 485
J
j_password 555 K
key
j_security_check 554–555
foreign 169
j_username 555
primary 168
J2EE Publishing server 465
JAAS 207, 470, 482, 570
JAR 60 L
Java build path 486 language attribute 248
Java Native Directory Interface (see JNDI) lib directory 61, 74
Java package 176 Libraries directory 74
Java scriptlets 34 link
Java Source directory 73, 233 adding 117
java.lang.* 249 image 118
JavaScript 32, 242 text 117
javax.servlet.* 249 local history 45–46
javax.servlet.http.* 249 comparing with 45
javax.servlet.jsp.* 249 log file 219
JDBC 2.0 Standard Extension API 154 logos 124
JDBC driver 483
JDBC driver class 161, 196–197
Index 651
460, 466, 522, 527, 529, 540–541 rtexprvalue 285
XML 49, 320
photo frames 124
plug-in 423
S
SAX2 320
port 467, 476, 481, 483, 485
schema 163–164, 166, 169
POST 555, 563
schemaLocation 318
preferences
scope
file associations 50
application 247
HTML files 149
page 247
Server perspective 460
request 247
validation 92
session 247
principal 552, 569
scripting elements 252
processing instructions 311
scriptlet 252–253, 276–277, 299
profiling mode 489
sequence 317
programmatic security 557, 561, 568
server
Project Navigator 66
defining 462
provider 357
starting 471, 482, 487
proxy 374, 379–380
state 469
publish 460–461, 470–471, 475, 478, 481, 483,
stopping 488
487
server configuration 459, 461–462, 469, 484–486,
488
Q server-side Java 215
Quick Fix 499 server-side logic 34
service
broker 358
R provider 358
readme file 11
registry 358
realm 552, 555, 558, 565
requestor 359
Redbooks Web site 645
servlet 195, 215, 243–244, 246, 557–558, 563,
Contact us xvii
568–569
redirection 563
configuration 219
remote procedure call (see RPC)
context 219
repository 516–531, 533, 535–537, 539, 542–545,
initialization parameters 197, 269
549
life cycle 216
request 33, 186
overview 216
object variable 246
servlet container 59, 217–219
scope 247
servlet context 62
requestor 357
servlet path 64
resource 420
ServletContext 297
resource bundle 420
servlets
resource reference 198, 211
initialization parameter 206
response 33
session 33, 186
object variable 246
object variable 246
revision tag 524, 527
scope 247
Rhino ECMAScript 32
session attribute
role 552, 556, 558, 560, 564, 566–567
attributes
security 59, 556
session 249
root element 311
session management 462, 485
RPC 356, 361–362
Index 653
Session 297–298, 300–301 utility classes 60
Sslext 300
String 297, 299–300
tag libraries for accessing JSP objects 297
V
validation
tag libraries for database access 297
DTDs 330
tag libraries for internationalization 297
XML 314, 320, 327
Utility 297, 299–300
XML schema 329
utility tag libraries 297
validators 92
tags 544
variable 209–210, 485, 503, 512
tasks
version 515, 517–519, 521, 524–528, 532–534,
adding to Tasks view 84
537–539, 541–542, 544–546, 549
TCP/IP monitoring server 465
version control 525, 527
TEI 283
version from stream 526
template 71, 74
versioning 518
application 75
video 60
page 96, 105–106, 135
view
page templates 94, 109–110
adding 53
template gallery 123
Attributes 80, 116–118
text
Breakpoint 501–502
bold 116
Breakpoints 506, 511
working with 116
Colors 83
theme
Console 459, 471, 475, 483, 487, 501
directory 74
CVS Repositories 520, 526–527, 529,
thin client 19
537–539, 542, 545
thread 503, 506, 510
CVS Resource History 544
tier 19–20
Data Definition 157
TLD 279–280, 283–286, 294
Data Mapping 424
tModel 364, 366
Data Mappings 424
tools drawer 403
DB Servers 157, 159
trace 486
Debug 501, 503
transport guarantee 564
Design 81, 116, 321, 327–328
fast 50–52
U floating 53
UDDI 356–357, 360 Gallery 81
API 365 icons 53
organization 366 Incoming/Outgoing 533
overview 363 J2EE Navigator 175
registry structure 363 Java Hierarchy 50
universal test client 485 Links 82
Universal Unique Identifier MVC 31
see UUID 365 Outgoing 523, 525
update 517, 519, 530, 532, 536, 542 Outgoing Mode 524
URI 65, 250, 284 Outline 81, 157, 261, 321, 501
taglib 285–286, 293 Palette 104, 403
URL pattern 562 Project Navigator 79–80, 122, 135, 233, 266,
URL rewriting 485 522, 524, 526–527, 530, 536, 538, 549
use case 39 Properties 51
usejdbc2.bat 203, 636 Repositories 519
Index 655
XML schema editor
graph view 328
xmlns 314–315
XPath 319
XSD 315, 317–318, 321, 323, 329, 362
XSL 318, 320
transformation 318
XSLT 318
XSLT script 320
This publication is applicable to the Linux and Windows IBM Redbooks are developed by
platforms. the IBM International Technical
Support Organization. Experts
from IBM, Customers and
Partners from around the world
create timely technical
information based on realistic
scenarios. Specific
recommendations are provided
to help you implement IT
solutions more effectively in
your environment.