By the end of the tour, you’ll be able to use IBM WebSphere Studio to build your own applications, and you’ll understand why JavaBeans are so useful for application programming.. This bo
Trang 1Building Applications with IBM WebSphere Studio and
JavaBeans: A Guided Tour
by Colette Burrus and Stephanie Parkin
ISBN:1931182140
MC Press © 2003 (444 pages)
This book is the definitive guided tour through learning how to
develop applications using IBM WebSphere Studio and JavaBeans, with a clear and understandable explanation of XML and database programming.
Trang 3Don’t be overwhelmed with programming
gobbledygook This book is the definitive guided tour through learning how to develop applications using IBM WebSphere Studio and JavaBeans, with a clear and
understandable explanation of XML and database
programming In the simplest way possible, you’ll learn reusable concepts, not just product.
Along the way, you’ll learn the basics of how to develop Java applets and applications, as well as more
advanced topics, such as using relational databases and eXtensible Markup Language (XML) documents to store your application data By the end of the tour,
you’ll be able to use IBM WebSphere Studio to build your own applications, and you’ll understand why
JavaBeans are so useful for application programming.
This book assumes you have some basic knowledge of the Java programming language, but you certainly
don’t need to be an expert to follow the tour You do need to be running one of the Windows operating
systems, and as long as you’re comfortable with
Windows, the Internet, and Web browsers, you’re
ready to learn Java Experts will benefit from the tour, because it will teach you many of the IBM WebSphere Studio features that will let you build your Java
applications easier and faster.
This book uses the “show and tell” approach If you flip through the pages, you’ll notice that they are loaded with pictures showing you how your applications
Trang 4corresponding Web-based tutorial series.
Stephanie Parkin is an information architect for the
IBM WebSphere Developer Domain Web site In her career at IBM she has been managing editor of the
WebSphere and VisualAge Developer Domains, and has created and edited documents for various
programming languages, including VisualAge for Basic.
Trang 5She also was the Editor-in-Chief of the WebSphere Developer Technical Journal Stephanie also
coauthored the previous book and tutorial series, and
has published an article on Designing Beans in Java Developer’s Journal.
Trang 6Building Applications with WebSphere Studio and JavaBeans—A Guided Tour
Copyright © 2003 International Business Machines Corporation
Portions © 2003 by MC Press
Every attempt has been made to provide correct information in this book.However, the publisher, the editors, and the authors do not guarantee theaccuracy of the book and do not assume responsibility for information
Trang 7The following are trademarks of International Business Machines
Corporation in the United States, other countries, or both: IBM, the IBMlogo, IBM Press, the IBM Press logo The e-business logo nad
developers who worked on the "JavaBeans Around the World" Project.Their beans provided the core technology that let us build the
applications in this book
Second, we'd like to thank our technical reviewers at IBM: Joe
Winchester reviewed the entire book and gave excellent feedback, andJim Mann also provided valuable comments Thanks to Ernest Mah and
Dr Gili Mendel for answering product questions and to Lynn Jonas, MarkEdwards, John Botsford, Nak Paik, and Jeff Turnham for getting us earlyaccess to product drivers Thanks to Merrikay Lee for her editing
expertise Finally, a warm thanks to Tara Woodman for a very smoothbook-publishing process and equipment to help develop the book
Trang 8This book takes you on a guided tour to building applications with theWebSphere Studio Visual Editor for Java and JavaBeans Along the way,you'll learn the basics of how to develop Java applets and applications,
as well as more advanced topics such as using relational databases andeXtensible Markup Language (XML) documents to store your applicationdata By the end of the tour you'll be able to use WebSphere Studio tobuild your own applications and you'll understand why JavaBeans are souseful for application programming
If you're new to Java and Java development environments, that's OK.This book assumes you have some basic knowledge of the Java
programming language, but you certainly don't need to be an expert tofollow the tour You do need to be running one of the Windows operatingsystems, and as long as you're comfortable with Windows, the Internet,and Web browsers, you're ready to learn Java
If you are already familiar with Java and Java development
environments, that's OK, too You'll still benefit from going through thetour, because it will teach you many of the WebSphere Studio featuresthat will let you build your Java applications easier and faster
This book uses the "show and tell" approach If you flip through the
pages, you'll notice that they are loaded with pictures showing how yourapplications should look at each step along the way In addition, we'veincluded two CDs that contain all the tools you'll need to follow along withthe lessons
Trang 9Java is considered the language of the Internet It combines two
important advances in computer science: object orientation and platformindependence Object orientation means that the programming languagemodels real-world components and behavior You organize your
programs into objects with certain properties and define the activities thatthe objects can perform Complex behavior is hidden in the
implementation of the object, letting you just connect the object to otherobjects Secondly, Java is platform-independent, which means that youcan create programs on a Windows machine and be confident that theprogram will work in any environment that Java runs in
In the past few years the use of Java has exploded It has expanded wellbeyond its original main purpose of providing dynamic Web pages, to afull server-side programming language It enables the development ofcomplex Internet functionality, such as querying legacy databases,
enabling business-to-business Web commerce, and providing interactiveWeb communications Because it's based on open standards, all Javaprograms use a common API This means that you can reuse other Javacomponents and easily snap them into your programs
Trang 10WebSphere Studio Site Developer 5.0 is the development tool that you'lluse during the guided tour As you'll see, WebSphere Studio is a full-function integrated development environment that contains everythingyou need to create, test, and maintain your Java applications The VisualEditor for Java, new with WebSphere Studio 5.0, makes development ofJava applications even easier and faster—you just drag and drop theelements you want to use for your application and customize them to setthe properties you want, and it generates the underlying code for you
Trang 11JavaBeans are the Java components that you'll use to build applicationsduring the guided tour You'll use the standard user interface elements(visual beans such as buttons and text fields) that come with the VisualEditor, as well as non-visual beans to perform complex functions such assorting data, working with databases, and working with XML documents
As you'll see, JavaBeans simplify the work of application programmingbecause they provide prebuilt components with simple interfaces thatyou'll use to customize their functions and wire them into your
applications
Trang 12This book shows you how easy it is to create applications with the VisualEditor and JavaBeans It provides all the tools and components you'llneed, and explains how to use them together to create simple yet usefulprograms
And, as an additional benefit for readers of this book, we've established
an email contact where you can send your comments and questionsabout beans and programming with them We will monitor this ID andanswer any questions you send in E-mail your questions and comments
to beans@pobox.com
Trang 13This "guided tour" is organized as a series of hands-on tutorials Thesetutorials originally appeared online at the WebSphere Developer DomainWeb site, at http://www.ibm.com/websphere/developer
Each chapter of this book contains a tutorial that teaches a particularJava concept In each chapter you'll create a new running program, test
it, and optionally, export it to run independently from WebSphere Studio.Chapter 1 Creating your first applet: Introduces you to the Visual
Editor for Java and JavaBeans and teaches you how to build your firstapplet, a simple To Do list
Chapter 2 Extending your first applet: Teaches how to expand yourapplet with more functionality and teaches how to publish your applet torun it in a Web browser
Chapter 3 Creating your first application: Shows how to build the
ToDoList program as a Java application with the capability to save the list
in a file so that you don't lose your data each time you close the program.Chapter 4 Creating a file-manipulation subcomponent: Teaches how
to create a subcomponent (a.k.a bean) that extends your ToDoList
application by adding a reusable FileManipulationPanel component Youwill add standard file dialog windows for loading and saving files and hideall the complex wiring inside your own visual bean
Chapter 5 Using layout managers: Gives an overview of the layoutmanagers that the Java platform provides, rules for using them, and
some examples of usage Layout managers let you align, space, and sizethe objects that make up your user interface
Chapter 6 Using Swing components: Teaches how to use components
of the Swing class library, which provides a customizable look and feel foryour applications These components also provide built-in functions such
as icons, roll-over buttons, and help text
Chapter 7 When something goes wrong: Debugging: Teaches how to
Trang 14debugger We'll create a "buggy" application and then walk you throughthe steps of finding and correcting the problems
Chapter 8 Advanced applet development: Discusses advanced topics,such as security issues, customizing your applets "on the fly", and using
<param> tags, as well as controlling the browser that hosts your applet.Also discusses how to implement "drag and drop" functionality, as well assome security issues for browsers and when to save your applets asseparate class files, versus saving them as JAR packages
Chapter 9 Working with databases: Teaches the basics of storing yourdata in a relational database, including manipulating that data from yourvisual programs You'll create a Friends database that lets you store
information on your friends, including digital photos
Chapter 10 Working with XML data: Looks at several features in
WebSphere Studio that you can use to build Java applications that workwith XML data You'll use the XML perspective to create XML and DTDfiles and to generate JavaBeans that you'll use to build an XML
Trang 15In each chapter of this book you'll create at least one complete applet orapplication Each chapter provides certain key elements:
Time Required: This item tells you approximately how long each lesson
should take to complete Lessons generally take one to four hours
Files Required: This list tells you which files you need from the CD to
complete the lesson We've provided components you'll need in eachchapter, plus solution files that show the end result of each exercise Ifyou ever get lost, you can check the solution file to get you back on track.All of the required files are in the solutions subdirectory of the secondCD
Screen captures: Throughout the chapter, screen captures show you
how to complete each step of the lesson
Text conventions: Interface elements that you select, as well as text
strings that you need to enter, appear in boldface Icons are shown in themargins of the text Code samples appear in monospace font
Trang 16your Web site team, including content authors, graphic artists,
programmers, and Webmasters, into a common interface This integratedtool makes it easy to collaboratively create, assemble, publish, deploy,
and maintain dynamic, interactive Web applications designed to meet therequirements of today's open technology standards It is the latest
application development tool built on IBM's WebSphere Studio
Workbench WebSphere Studio Site Developer seamlessly interacts withmost third party tools and the WebSphere Application Server to publish
Trang 17in the exercises.
Trang 18The following Web sites provide information on obtaining and using
WebSphere and DB2 products:
http://www.ibm.com/university: If you're a faculty member of anaccredited higher education institution, you can join the IBMScholars Program The IBM Scholars Program provides you withaccess to IBM software and hardware, tutorials and other
training, course materials, certification, technical support, andmore
http://www.ibm.com/partnerworld: If you are an IBM BusinessPartner, you can download software or request software on CDfor long term use
http://www.ibm.com/developerworks: If you're interested in
several IBM products, consider subscribing to the
developerWorks Toolbox to receive expanded licensing, customCDs, and technical support
http://www.ibm.com/websphere/developer and
http://www.ibm.com/software/data/developer: WebSphere
Developer Domain and DB2 Developer Domain provide access
to the latest product downloads, tutorials, technical articles, andproduct support They also tell you how to purchase WebSphereand DB2 products
Trang 19Download CD Content
Trang 20We begin the tour with a simple example of how to build a Java™ applet
Applets are downloadable programs that run in a Web browser and that
have restricted access to the client system for security reasons Theapplet you'll build in this chapter is the ToDoList tracking applet shown inFigure 1.1
Figure 1.1: The applet you'll create
Java and all Java-based marks are trademarks or registered trademarks
of Sun Microsystems, Inc., in the United States and other countries.The ToDoList applet includes visual controls to let you add entries to thelist, clear all entries, and remove a selected entry In the process of
building this applet, you'll learn how to use the Visual Editor for Java andJavaBeans™ to add complex functions to your applet with just a fewsimple steps
Trang 21To follow along with the steps in this chapter, yu need the following:
IBM WebSphere Studio Site Developer 5.0: Install this programfrom the CD included with this book See Appendix A for
WebSphere Studio
What's a JAR file?
JAR (Java archive) files are a convenient way to group other files
together They are typically stored in a compressed format for efficientstorage and transfer across the Internet In this book, JAR files containall the files required for a particular set of JavaBeans (code, text, andimage files)
Trang 22Before you can build your first applet, you need to do some setup work inWebSphere Studio to specify where your applet will be saved, and tospecify the JAR file for beans you'll use to build your applet
WebSphere Studio is organized into a variety of perspectives, which are
just different ways of looking at a development project based on your role
on the development team In this book, you'll mainly use the Java
perspective, and within the Java perspective, your applications will beorganized into projects and packages You can switch perspectives
whenever you need to Within a particular perspective, you'll also see avariety of different editors and views that are applicable to the work donewithin that perspective For example, within the Java perspective, you'lluse the Visual Editor for Java, the Package Explorer, the Properties view,and the Java Beans view, but don't worry—we'll explain how each ofthese works as we go along
Starting WebSphere Studio
1 To start WebSphere Studio, click Start → Programs → IBM WebSphere Application Server - Express v5.0 → Studio Site Developer When you start WebSphere Studio the first
time, a window appears asking which directory you want to usefor your workspace (the place where WebSphere Studio savesyour work), as shown in Figure 1.2
Figure 1.2: Workspace directory selection
window
2 Leave the directory name with the WebSphere Studio default,check the check box to not show the dialog box again, and click
Trang 23setworkspace
entering the following command: wasexpress -The Workbench initially opens in the Web perspective, which isthe perspective for working with Web projects (applications thatrun on Web servers) To close the Web perspective, right-click
Trang 24Figure 1.4: The Java perspective in the WebSphere Studio
Workbench
Notice that a Java Perspective icon now appears in the verticaltoolbar You can have multiple perspectives open at any giventime; the way to switch from one to another is just to select theicon for the perspective you want in the vertical toolbar
Also notice that different options now appear in the horizontal toolbaralong the top of the window This toolbar contains icons for all the
common actions you need when working within the Java perspective It's
a subset of the actions available from the pull-down menus, and you cancustomize it to add, reorder, or remove toolbar actions to suit your
2 Enter ToDoList as the project name, as shown in Figure 1.5.
Trang 25Browse to the location on your machine where you copied the chap01.jar file (for example, C:/beans), select the file, and click
Open, so that the Libraries tab looks like Figure 1.6.
Trang 26Figure 1.6: Specifying bean JAR files for the Java
project
The Libraries tab now shows the standard Java classes (thedefault Java Runtime Environment (JRE) that's automaticallysupplied by WebSphere Studio) and the bean JAR file for thischapter
Java Build Paths
You can think of the Libraries in the Java build path as theentries in a traditional CLASSPATH setting When a program
is compiled or executed within a WebSphere Studio project,any classes it requires must be available within the project'sbuild path This situation is different from VisualAge for Java,where all classes were available at all times for compilation,and where each individual program specified its own
classpath In WebSphere Studio a project's build path
defines the available classes for all programs within theproject
Trang 275 Click Finish.
Your ToDoList project now appears as an entry in the Package Explorer.Click on the + sign to expand the project contents, and you'll see the list
of Java classes that can be used by Java programs within this project: allthe standard Java classes and the special bean JAR file for this chapter,which you just added to your project's build path
Creating the package
Every Java program exists within a Java package This can be the
default package (what you get when you don't explicitly specify a
package name for your program) or a specific package name, such ascom.ibm.uicontrols You use packages to organize Java programs intological groupings They define the scope for a particular program andprovide unique names for programs You'll use simple, descriptive
package names for the programs in this book Package names should beunique to avoid collision with other classes, so the convention is to take acompany's Internet domain name, reverse it, and then add a suffix that isunique within the organization For example, IBM's Internet domain isibm.com, so the package name com.ibm.uicontrols can be used
1 To create the package, right-click on the ToDoList project in the Package Explorer and choose New → Package from the pop-
up menu
2 In the New Java Package window that appears, enter
toDoListPackage as the package name, as shown in Figure
1.7
Trang 28Figure 1.7: Creating a new Java package
3 Click Finish.
The Package Explorer now appears with toDoListPackage as an entryunder the ToDoList project This is where you'll place the Java programfor your applet
Creating the applet
After you have created the project and package, the next step is to createthe Java class for your applet
What's a class?
A class is a set or group made up of members that share the samebehavior and the same kinds of state information Each Java program
is a class, and each class has a superclass that defines where theclass fits into the object hierarchy Just as you may have inheritedcertain traits from your parents, a Java class can inherit state andbehavior from its superclass For more information on classes andobjects, see Appendix B
Trang 291 To create the class for your applet, right-click on
toDoListPackage in the Package Explorer, and choose New → Visual Class from the pop-up menu.
Tip If you don't see Visual Class listed in the menu, select
New → Other…, then select Java, and then Visual Class.
2 Enter ToDoList as the class name.
3 Leave the default for Modifiers set to public (this makes your
class accessible by other programs, such as a Web browser)
4 Select Applet as the visual class to extend, and uncheck the Swing check box By choosing these two options, you're telling
WebSphere Studio that you want your new visual class to havejava.applet.Applet as its superclass, which is the standard
superclass for Java applets
5 Uncheck any check boxes to create method stubs (we'll explainthese in later chapters), so that the Create a new Java Classusing the Visual Editor window looks like Figure 1.8
Trang 30Figure 1.8: Creating an applet
6 Click Finish.
Your new ToDoList class opens in the center of the Workbench using theVisual Editor for Java Notice that views have also been added to theWorkbench for Java Beans and Properties You use these views to workwith beans that you add to your visual classes The Java Beans viewshows a hierarchy of all beans in your visual composition, and the
Properties view shows the property values for the currently selectedbean When you first open your applet, the only bean is the applet itself(called "this") The Properties view is empty at this point, because nobean has been selected yet
Trang 31This section shows you how to start building your applet by adding beans
to the design surface of the Visual Editor, customizing their properties inthe Properties view, and writing the necessary code to connect the beanstogether
To create a program visually in the Visual Editor, you select the bean youwant from the palette and drop it on the design surface When you drop abean on the design surface, its properties appear in the Properties view(along the right edge of the Workbench window), where you can
Trang 32Properties view
The design surface can contain both visual and non-visual beans For theToDoList applet, you will add visual beans, such as buttons and text
fields, to the visual surface of the applet When you extend the applet inChapter 2 to add logic to sort the list, you'll add a non-visual bean to thefree-form portion of the design surface Nonvisual beans are componentsthat provide processing functions for your program but don't have anyvisual elements associated with them A class is considered visual ornon-visual based on whether the class inherits from java.awt.Component.All visual classes, such as buttons or text fields, inherit from
java.awt.Component, and all other classes are non-visual Visual classesare shown on the design surface as they appear at run time, while non-visual classes are shown with an icon and name
VisualAge for Java users
If you ever used the Visual Composition Editor in VisualAge for Java,you'll notice many similarities between that editor and the Visual Editorfor Java in WebSphere Studio In both cases you select the beans youwant from the palette, drop them on the design surface, and customizetheir properties The main difference comes in how you connect beanstogether With the Visual Composition Editor you wired beans togethervisually With the Visual Editor for Java you'll have to write code toconnect beans, but don't worry—you'll find it's not really that painful Ifyou're new to Java programming or just need a refresher on basics ofthe Java programming language, see Appendix B
Before you begin adding elements to the design surface, notice that thesource pane already contains a stub for your program, as shown in
Trang 33to the design surface, customize their properties, and see how the sourcechanges
Laying out the interface and customizing properties
1 Select the small rectangle in the Visual Editor's design surface.This is the visual surface for your applet, where you'll placeelements such as buttons and text fields, so grab one corner ofthe rectangle and drag it to increase its size When you selectthe rectangle, the applet's properties are presented in the
Properties view When you drag it to increase its size, the sizeproperty is updated to reflect the new size Also notice that adefault constructor and an init() method are added to your
source code, along with code to initialize the applet's size Theinit() method is a special method that gets called when an
applet is first started, so this is where the Visual Editor placesyour initialization logic, such as the statement it just created toset your applet's initial size
2 In the Properties view, select the current value for the layoutproperty and click the down arrow next to it to show the list of
possible layout values Select the null value, as shown in
Figure 1.11 (we'll cover layouts in more detail in Chapter 5; nulllayout means that your visual elements will appear exactly
Trang 343 Now you're ready to start adding beans to the applet's surface.The bean palette displays vertically on the left side of the VisualEditor window, separated into categories for all the standardJava visual elements Standard Java currently provides twomajor sets of visual elements: Swing and the Abstract WindowToolkit (AWT) We'll go over the differences in detail later in thisbook You'll see these basic categories in the bean palette:
Swing Containers, Swing Components, Swing Menus, and AWTControls, as shown in Figure 1.12
Trang 35changes to an arrow with a plus sign Click the mouse again toplace the button on the applet surface, as shown in Figure 1.13.
Trang 374 Now you can customize the button's properties On the designsurface, use the mouse to resize the button to make it larger,and in the Properties view, change the button's label property to
Add Notice that as you make changes in one pane, the
corresponding updates are reflected in the other panes
Tip There are actually two ways in which you can drop acomponent onto the design surface The first way is topress and release mouse button 1 as you just did, inwhich case the component is dropped with its top leftcorner at the mouse position For null layout, the size isexplicitly set to the preferred size of the component(what the component thinks is its best size—notsomething that you set) The other way is to pressmouse button 1 and then drag out a rectangle for theinitial size When you release mouse button 1, thecomponent is created with its size set to the dragrectangle Setting the initial size on drop avoids having
to drop and then select and resize the component,since these actions are done in a single gesture
Setting the initial size on drop is applicable only for thenull layout manager For other layout managers, thelayout manager sets the component's size based on itspreferred size and other parameters
5 Next, place a text field on the visual surface to the right of thebutton, by selecting the TextField icon from the palette of AWTControls Resize the text field so that your applet's surface
looks like Figure 1.15
Trang 38Figure 1.15: Placing a text field on your
applet
Scroll through the source pane to see the code that was addedfor the new textField variable (a declaration for the variable,initialization in the init() method, and a new getTextField()
method for initializing and accessing the text field)
6 Finally, your applet needs to show the list of items to do Forthis purpose, add a BoundList bean from the JAR file for thischapter to the applet surface This bean isn't in the Visual
Editor's standard bean palette, so the way you select it is by
using the Choose Bean option Click on Choose Bean at the
top of the bean palette, and a window appears with a list of allpossible classes that are available in your project's build
settings Enter BoundList in the class name field, as shown in
Figure 1.16, and click OK
Trang 39Figure 1.16: The Choose a Bean window
7 Move the cursor over the design surface in the Visual Editorand drop the BoundList bean on the applet's surface, as shown
in Figure 1.17 Resize the BoundList bean so that it matchesthe width of the text field, and scroll through the source pane tosee the code that was added for the new boundList variable (adeclaration for the variable, initialization in the init() method, and
a new getBoundList() method for initializing and accessing thelist)
Figure 1.17: Adding a BoundList bean to your
applet
Tip For an easy way to align, resize, or reposition a group of visual
Trang 40the elements you want to work with The last one you select isthe anchor control—that is, the one that the others will be made
to match Then click on the Alignment icon in the toolbar Thealignment window shown in Figure 1.18 appears with icons toalign, match sizes, or distribute the selected elements on thevisual surface
Figure 1.18: Alignment icons for making your visual elements
tidy
You've now created the initial visual elements for your applet The nextstep is to add the code to connect these elements together to make them
do what you want
What's in a name?
Visual beans that you drop on the design surface are given variablenames that begin with the name of the bean, followed by an optionalsequence number So, for example, Button beans that you drop on thedesign surface are given variable names of button, button1, button2,and so on As you'll see in later chapters, you can rename variablesfor visual beans that you drop on the design surface, to make themmore meaningful to your program