Web Enabling AS/400 Applications with IBM...

434
Web Enabling AS/400 Applications with IBM WebSphere Studio Fernando Zuliani, Bob Maatta, Igor Gershfang, Robert Hare, Biswanath Panigrahi International Technical Support Organization SG24-5634-00 www.redbooks.ibm.com

Transcript of Web Enabling AS/400 Applications with IBM...

Web Enabling AS/400 Applications withIBM WebSphere Studio

Fernando Zuliani, Bob Maatta, Igor Gershfang, Robert Hare, Biswanath Panigrahi

International Technical Support Organization

SG24-5634-00

www.redbooks.ibm.com

International Technical Support Organization SG24-5634-00

Web Enabling AS/400 Applications withIBM WebSphere Studio

April 2000

© Copyright International Business Machines Corporation 2000. All rights reserved.Note to U.S Government Users - Documentation related to restricted rights - Use, duplication or disclosure is subject to restrictionsset forth in GSA ADP Schedule Contract with IBM Corp.

First Edition (April 2000)

This edition applies to the IBM WebSphere Studio Version 3.0 and the IBM WebSphere Application Server, StandardEdition, Version 2.0 for use with OS/400 V4R4.

Comments may be addressed to:IBM Corporation, International Technical Support OrganizationDept. JLU Building 107-23605 Highway 52NRochester, Minnesota 55901-7829

When you send information to IBM, you grant IBM a non-exclusive right to use or distribute the information in anyway it believes appropriate without incurring any obligation to you.

Before using this information and the product it supports, be sure to read the general information in Appendix B,“Special notices” on page 407.

Take Note!

Contents

Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viiThe team that wrote this redbook . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viiComments welcome . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . viii

Chapter 1. Introduction to the IBM WebSphere family . . . . . . . . . . . . . . . . .11.1 The IBM WebSphere Application Server . . . . . . . . . . . . . . . . . . . . . . . . . . .11.2 WebSphere Studio . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21.3 WebSphere Performance Pack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31.4 WebSphere Site Analyzer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41.5 Putting it all together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4

Chapter 2. Installation and configuration . . . . . . . . . . . . . . . . . . . . . . . . . . .72.1 Introduction to WebSphere Application Server for AS/400. . . . . . . . . . . . . .72.2 Installation considerations. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7

2.2.1 Installing IBM WebSphere Application Server (V4R4) . . . . . . . . . . . . .82.2.2 Installing IBM WebSphere Application Server (V4R3) . . . . . . . . . . . . .82.2.3 Considerations when upgrading from V4R3 to V4R4 . . . . . . . . . . . . . .9

2.3 Configuring the WebSphere Application Server for AS/400 . . . . . . . . . . . . .92.3.1 Adding directives. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .162.3.2 Testing your HTTP server configuration . . . . . . . . . . . . . . . . . . . . . .182.3.3 Configuring the AS/400 Toolbox for Java . . . . . . . . . . . . . . . . . . . . .202.3.4 Troubleshooting the WebSphere Application Server . . . . . . . . . . . . .202.3.5 Installation and configuration on other platforms . . . . . . . . . . . . . . . .20

2.4 WebSphere Application Server Administration . . . . . . . . . . . . . . . . . . . . .20

Chapter 3. WebSphere Studio tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .233.1 Studio WorkBench . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24

3.1.1 Creating a new project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .243.2 Studio Wizards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28

3.2.1 Importing an existing Web site . . . . . . . . . . . . . . . . . . . . . . . . . . . . .293.2.2 Database Wizard. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .303.2.3 Publishing the Web site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .443.2.4 Publishing to the AS/400 system . . . . . . . . . . . . . . . . . . . . . . . . . . . .463.2.5 Previewing the Demo Company Web site . . . . . . . . . . . . . . . . . . . . .503.2.6 More WebSphere Studio Wizard examples . . . . . . . . . . . . . . . . . . . .52

3.3 Page Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .883.3.1 Using WebArt Designer and AnimatedGif Designer to add enhancedgraphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .883.3.2 Constructing the Logon page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .973.3.3 Creating a page template . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1023.3.4 Working with style sheets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1033.3.5 Using Page Designer with JavaBeans . . . . . . . . . . . . . . . . . . . . . . .1063.3.6 Modifying the Studio Wizards generated result page . . . . . . . . . . . .109

3.4 Applet Designer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1123.4.1 Creating an applet with Applet Designer . . . . . . . . . . . . . . . . . . . . .1123.4.2 Placing a Rollover button on the applet and connecting it to a URL .1163.4.3 Creating nervous text on the applet . . . . . . . . . . . . . . . . . . . . . . . . .118

3.5 Net Objects ScriptBuilder 3.0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1193.6 VisualAge for Java 3.0 Professional Edition . . . . . . . . . . . . . . . . . . . . . .120

© Copyright IBM Corp. 2000 iii

Chapter 4. Restoring the ABC Company Web site sample project . . . . . 1214.1 Installing the download files. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1214.2 Creating the WebSphere Studio project using the archive file . . . . . . . . 121

4.2.1 Restoring the project archive file . . . . . . . . . . . . . . . . . . . . . . . . . . 1224.2.2 Updating the ABC Company project files to use your AS/400 server1234.2.3 Creating an AS/400 user profile . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

4.3 Setting up the AS/400 system to run the ABC Company Web site . . . . . 1254.3.1 Publishing to the AS/400 system . . . . . . . . . . . . . . . . . . . . . . . . . . 1254.3.2 Packaging the WebSphere Studio application . . . . . . . . . . . . . . . . 1304.3.3 ABC Company Web site configuration . . . . . . . . . . . . . . . . . . . . . . 132

Chapter 5. Order Entry application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1375.1 Overview of the Order Entry application. . . . . . . . . . . . . . . . . . . . . . . . . 137

5.1.1 The ABC Company . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1375.1.2 The ABC Company database. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1375.1.3 A customer transaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1385.1.4 Application flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1385.1.5 Customer transaction flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1395.1.6 Database table structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1455.1.7 Order Entry application database layout . . . . . . . . . . . . . . . . . . . . 1455.1.8 Database terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

Chapter 6. Enabling the Order Entry application: Methodology . . . . . . . 1516.1 Identifying the AS/400 application to Web-enable . . . . . . . . . . . . . . . . . 151

6.1.1 Primary users of the Web application. . . . . . . . . . . . . . . . . . . . . . . 1516.1.2 Identifying issues and assumptions . . . . . . . . . . . . . . . . . . . . . . . . 1516.1.3 Analysis of the AS/400 application: Business and presentation logic152

6.2 Web-site design. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1526.2.1 Dividing the Web site into subsites based on functionality . . . . . . . 1536.2.2 Subsite development and unit testing. . . . . . . . . . . . . . . . . . . . . . . 1556.2.3 Tying it all together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1566.2.4 Integration testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

6.3 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156

Chapter 7. ABC Company Web site design and development . . . . . . . . 1577.1 Login and session management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158

7.1.1 Creating the login servlet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1587.1.2 Building the custID bean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1627.1.3 Building a session management servlet . . . . . . . . . . . . . . . . . . . . . 162

7.2 Creating the new users subsite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1647.2.1 New users: Development on the AS/400 server . . . . . . . . . . . . . . . 1647.2.2 New users: Development using WebSphere Studio tools . . . . . . . . 1667.2.3 Input data validation. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2037.2.4 New user creation summary and final testing . . . . . . . . . . . . . . . . . 215

7.3 Creating the catalog subsite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2157.3.1 Creating the catalog project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2157.3.2 Creating the SQL queries for the catalog subsite . . . . . . . . . . . . . . 2157.3.3 Creating the Web pages for the catalog subsite . . . . . . . . . . . . . . . 2237.3.4 Testing the catalog pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2317.3.5 Creating the general catalog area . . . . . . . . . . . . . . . . . . . . . . . . . 2367.3.6 Linking the catalog pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

7.4 Shopping cart subsite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2467.4.1 Creating the shopping cart project . . . . . . . . . . . . . . . . . . . . . . . . . 2467.4.2 Creating the SQL queries for the shopping cart subsite . . . . . . . . . 247

iv Web Enabling AS/400 Applications with IBM WebSphere Studio

7.4.3 Creating Web pages for the shopping cart subsite . . . . . . . . . . . . .2547.4.4 Testing the shopping cart pages . . . . . . . . . . . . . . . . . . . . . . . . . . .2627.4.5 Modifying the shopping cart bean to display item totals . . . . . . . . . .2677.4.6 Linking the shopping cart pages . . . . . . . . . . . . . . . . . . . . . . . . . . .2717.4.7 Changing the quantities of the items in the shopping cart . . . . . . . .2787.4.8 Testing the updated shopping cart for changing item quantities . . .2857.4.9 Deleting items from the shopping cart . . . . . . . . . . . . . . . . . . . . . . .2877.4.10 Testing the updated shopping cart for deleting items. . . . . . . . . . .290

7.5 Creating the order purchase subsite . . . . . . . . . . . . . . . . . . . . . . . . . . . .2917.5.1 Creating the order purchase project . . . . . . . . . . . . . . . . . . . . . . . .2927.5.2 Creating SELECT SQL for the SHPCART table. . . . . . . . . . . . . . . .2937.5.3 Creating servlet and DB access bean for SHPCART select query . .2957.5.4 Modifying the resulting page of the shopping cart selection . . . . . . .2977.5.5 Creating the servlet, DB access bean, and JSPs to submit the order2997.5.6 Developing Java code to package and submit the order to the AS/400server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3017.5.7 Calling the AS/400 server program to submit the order . . . . . . . . . .3107.5.8 Order confirmation: Creating SELECT SQL for the ORDERS table .3207.5.9 Creating servlet and DB access bean for the ORDERS select query3227.5.10 Creating the DELETE SQL for the SHPCART table . . . . . . . . . . . .3267.5.11 Creating the servlet and DB access bean for the SHPCART delete3287.5.12 Error handling on order submission to the AS/400 server . . . . . . .3347.5.13 Creating a self-contained order purchase subsite . . . . . . . . . . . . .3367.5.14 Order purchase subsite: Final testing . . . . . . . . . . . . . . . . . . . . . .342

7.6 Changes to the Host Order Entry application . . . . . . . . . . . . . . . . . . . . .3437.6.1 Processing the submitted order . . . . . . . . . . . . . . . . . . . . . . . . . . . .3437.6.2 Summary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .345

7.7 Creating the order status subsite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3467.7.1 Creating the order status project . . . . . . . . . . . . . . . . . . . . . . . . . . .3467.7.2 Building the SQL queries for the order status subsite . . . . . . . . . . .3467.7.3 Using the SQL queries in the Database Wizard . . . . . . . . . . . . . . . .3507.7.4 Testing the Order Status pages. . . . . . . . . . . . . . . . . . . . . . . . . . . .3547.7.5 Joining the order status with the order line . . . . . . . . . . . . . . . . . . .3567.7.6 Testing the order status subsite . . . . . . . . . . . . . . . . . . . . . . . . . . .358

Chapter 8. Creating the complete ABC Company Web site . . . . . . . . . . .3618.1 Web site development: Issues and pitfalls. . . . . . . . . . . . . . . . . . . . . . . .361

8.1.1 Design objectives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3618.1.2 Production. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3638.1.3 Publicizing. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3648.1.4 Evaluating the Web site. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .364

8.2 Creating static pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3658.2.1 Content of static HTML pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3658.2.2 Working with existing pages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3658.2.3 Creating images for all links . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .370

8.3 Creating the normal and registered user templates . . . . . . . . . . . . . . . . .3748.3.1 Normal page templates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3748.3.2 Registered user templates. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3778.3.3 Session management servlet, login servlet, and custID bean . . . . .381

8.4 Assembling the ABC Company Web site . . . . . . . . . . . . . . . . . . . . . . . . .3828.4.1 Adjusting the links on the static pages. . . . . . . . . . . . . . . . . . . . . . .3848.4.2 Modifying the Welcome page . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3878.4.3 Modifying the About Us page . . . . . . . . . . . . . . . . . . . . . . . . . . . . .388

v

8.4.4 Modifying the History page . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3898.4.5 Modifying the Logout page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 389

8.5 Tying it all together . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3898.5.1 Importing the subsites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3908.5.2 Cleaning up subsites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3918.5.3 Organizing the servlet folders . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3928.5.4 Fixing broken references . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3928.5.5 Adding registered user templates. . . . . . . . . . . . . . . . . . . . . . . . . . 3938.5.6 Restructuring directories . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3948.5.7 Login page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3958.5.8 The Welcome Registered User page . . . . . . . . . . . . . . . . . . . . . . . 3968.5.9 Linking the Login page. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3978.5.10 Linking the Registered User pages together . . . . . . . . . . . . . . . . 3978.5.11 Final touches . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4008.5.12 Publishing the Web site . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400

8.6 Heading towards e-commerce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4008.7 Task summary and integration testing . . . . . . . . . . . . . . . . . . . . . . . . . . 402

8.7.1 Integration testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4038.7.2 Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4038.7.3 Known problems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 404

Appendix A. Example programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .405A.1 Downloading the files from the Internet . . . . . . . . . . . . . . . . . . . . . . . . . . . . .405A.2 ReadMe file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .405

Appendix B. Special notices . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .407

Appendix C. Related publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .411C.1 IBM Redbooks publications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .411C.2 IBM Redbooks collections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .411C.3 Other resources . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .411C.4 Referenced Web sites . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .413

How to get IBM Redbooks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415IBM Redbooks fax order form . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .416

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 417

IBM Redbooks review . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423

vi Web Enabling AS/400 Applications with IBM WebSphere Studio

Preface

In the past two decades, the way the world does business has changeddramatically. The Internet has played a crucial role in this development. Abusiness without some kind of presence on the Internet today would be a rareoccurrence. Historically, Web sites were static but, in the past few years, interestin taking advantage of the ability to provide interactive contents has increaseddramatically. This redbook explores some of the tools and techniques that can beused to bring the contents of an existing AS/400 application to the Web. Thevehicle used to accomplish these tasks is the IBM WebSphere Application ServerStandard Edition 2.0, which ships as part of OS/400. The tools suite used in thisredbook includes the IBM WebSphere Studio 3.0 and the AS/400 Java Toolbox.

You learn how to create Web-based applications that not only interact withtraditional DB2/400 databases, but also with RPG programs and other AS/400specific features. Prior to reading this redbook, you should be familiar with theJava programming language, Web Technologies (HTML, browsers), and Webservers.

The team that wrote this redbook

This redbook was produced by a team of specialists from around the worldworking at the International Technical Support Organization Rochester Center.

Fernando Zuliani is an IBM Certified Professional (I/T Specialist) working in theInternational Technical Support Organization (ITSO) in Rochester, USA. He hasworked at IBM for 12 years and has over 14 years of professional I/T experience. Hisareas of expertise include AS/400, client/server programming, applicationdevelopment, object-oriented technology, and performance. Currently, he is the ITSOProject Leader for WebSphere, Java, and XML. He holds a bachelor of sciencedegree in mathematics from the University of Sao Paulo, Brazil.

Bob Maatta is a Senior Software Engineer from the United States at the IBMInternational Technical Support Organization, Rochester Location. He is the ITSOtechnical leader for AS/400 e-business application development. He writesextensively and teaches IBM classes worldwide on all areas of AS/400 client/serverand e-business application development. Before joining the ITSO in 1995, he workedin the AS/400 National Technical Support Center as a Consulting Market SupportSpecialist. He has over 20 years of experience in the computer industry. He hasworked on numerous computer platforms including S/390, S/38, and AS/400 and hasworked with all aspects of personal computers since 1983. He is a Sun Certified JavaProgrammer and a Sun Certified Java Developer.

Igor Gershfang is an Information Technology Architect with IBM Global Services.Currently he specializes in creating e-business solutions and Web-enabling existingapplication systems using a variety of development tools. His background is inapplication development and systems integration, which has gradually evolved intoinformation technology architecture. He possesses expert-level knowledge of theAS/400 platform in terms of application development. His areas of expertise alsoinclude Java, C, C++, ILE RPG, DB2, and other RDBMSs. He is currently working inthe IBM e-business Solution Center in Chicago, Illinois, where he is mastering theWebSphere Application Server and WebSphere Studio tool set. Igor holds abachelor's degree in computer science.

© Copyright IBM Corp. 2000 vii

Robert Hare is an Internet Specialist at Mid-Comp International, anAustralian-based IBM Business Partner. He has been working in the industry forthe past two years on the Internet and AS/400-related projects. He has expertisein Java, Object Oriented design, HTML, and Internet security. He holds a degreein physics and computing from Victoria University of Technology, Australia.

Biswanath Panigrahi is a Technical Specialist working in the Partner inDevelopment (PID) in Bangalore, India. He has worked at IBM for two years and hasover three years of professional I/T experience. His area of expertise include AS/400,client/server programming, Domino, Web-based application development, andperformance. He holds a master's degree in computer applications from OrissaUniversity of Agriculture and Technology, Bhubaneswar, India.

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

Greg HesterVice President, CrossLogic Corporation, USA

Makoto NishinoIBM Japan

Brad HanksCindy McCrickardJenny SzawlewiczIBM Raleigh

Richard SalzIBM Rochester

Dave RussellOma SewhdatToronto lab, IBM Toronto

Comments welcome

Your comments are important to us!

We want our Redbooks to be as helpful as possible. Please send us yourcomments about this or other Redbooks in one of the following ways:

• Fax the evaluation form found in “IBM Redbooks review” on page 423 to thefax number shown on the form.

• Use the online evaluation form found at http://www.redbooks.ibm.com/

• Send your comments in an Internet note to [email protected]

viii Web Enabling AS/400 Applications with IBM WebSphere Studio

Chapter 1. Introduction to the IBM WebSphere family

WebSphere is a brand name for a set of IBM products designed to make it easierand more productive to build, deploy, and manage a dynamic Web site.WebSphere is architected to enable you to build business-critical applications forthe Web. The IBM WebSphere family consists of the following components:

• WebSphere Application Server• WebSphere Studio• WebSphere Performance Pack• WebSphere Site Analysis

To keep up to date on IBM WebSphere support, visit the Web site:http://www.software.ibm.com/webservers

1.1 The IBM WebSphere Application Server

As the popularity of Java continues to increase, the emerging program model thatpeople are expected to move to is the application server model. The IBM offeringfor the AS/400 system is the WebSphere Application Server. It is a Java-basedservlet engine that’s built on top of the native Java virtual machine on the AS/400system. It provides Java servlet API support, which is defined by SunMicrosystems. If you write to the Java servlet API standard, your application isportable across any operating system, and any environment that supportsservlets. This is a big reason why this is becoming a very popular interface towhich to write.

The WebSphere Application Server comes with a graphical user interface tomanage servlets and control who has access to them. Since most applicationsare going to access a database, there are many advanced database accesscapabilities available. This includes a connection manager to improveperformance when accessing remote databases and data access beans thatmakes accessing the database even easier for Java programmers.

The WebSphere Application Server also comes with JavaServer Pages (JSPs)support. The JavaServer Pages technology is a simple but powerful way todynamically generate HTML pages on the server side. With JavaServer Pagestechnology, you can quickly and easily create Web pages with dynamicallygenerated content. When you write JavaServer Pages, you call reusable servercomponents (such as JavaBeans or servlets) to automatically create data objectsfrom an HTML file. This allows you to cleanly separate the generation of dynamiccontent from its presentation.

There are three versions of the WebSphere Application Server:

• Standard Edition: The Standard Edition is intended for use by Webapplication developers who focus on the issues of presentation logic, dataaccess, and the business logic that resides in the middle tier. The focus is onservlet run times, HTML, and support for JavaServer Pages. This combinationprovides an easy-to-use set of capabilities for presentation and dataaccess-oriented Web applications.

• Advanced Edition: The Advanced Edition adds support for EnterpriseJavaBeans (EJB). The EJB support includes bean-managed andsession-managed persistence using entity beans, full support for session

© Copyright IBM Corp. 2000 1

beans, relational database connectivity using JDBC (allowing support of theJava Transaction Service, (JTS) using EJBs), and support for EJBs toMQSeries and CICS for even more robust transactional support.

• Enterprise Edition: Integrating enterprise applications is the focus of theEnterprise Edition. This edition adds to the EJB and services support of theAdvanced Edition. The ability to integrate applications across the enterpriseusing the robust architecture and services is provided as part of the CORBAstandard. The Enterprise Edition leverages the connectivity and applicationintegration capabilities of IBM Component Broker technology, which has beenincorporated into WebSphere. In addition, users can deploy EJBs either to thesame EJB container that is part of the Advanced Edition or to the ComponentBroker container.

The AS/400 system provides WebSphere Application Server support starting withV4R3. In V4R3, WebSphere Application Server 1.1 support is provided as part ofthe HTTP Server for AS/400 (5769-DG1). In V4R4, it is split out into a separateproduct called 5769-AS1, which is still at Version 1.1. For V4R4, you can upgradeto the new Standard Edition Version 2.0 via PTFs.

For more information on using WebSphere Application Server Standard Edition2.0 in an AS/400 environment, see Building AS/400 Applications for WebSphereStandard Edition 2.0, SG24-5635.

In 2000, Version 3 of the WebSphere Application Server Advanced Edition forAS/400 will be available. It provides support for Enterprise JavaBeans andEnterprise Java Services.

EJB components are reusable and portable server-side business logiccomponents. IBM has adopted the EJB model to deliver productivity and flexibilityto customers who are building sophisticated Web applications. This unifiedcomponent model, supported across the IBM product line, makes it easier forcustomers to build, run, and manage the new generation of e-businessapplications, using tools and platforms that best meet their business needs.

Enterprise Java Services are the IBM-provided functions that run and manageapplications coded to the EJB specification. The container and server providetransaction, security, and persistence support, which makes development ofserver-side business logic considerably easier.

1.2 WebSphere Studio

WebSphere Studio is a suite of tools for the development of Web applications. Itis optimized specifically for WebSphere Application Server applications.However, you can also use many of the Studio tools for the development ofapplications for other Web servers or Web application servers. You run theWebSphere Studio development tools on a Windows workstation. You can deploythe resulting application to an AS/400 system running either WebSphereApplication Server Standard Edition or Advanced Edition. WebSphere Studioprovides tools you can use for managing your Web application project and for thecreation of HTML, Java, and JSPs including graphics and database access. Thisis not an AS/400 product, but is available from the IBM Software Group.

2 Web Enabling AS/400 Applications with IBM WebSphere Studio

The following tools are included in WebSphere Studio Version 3.0:

• Studio WorkBench• Studio Wizards• Page Designer• Applet Designer

The following components are optional with WebSphere Studio Version 3.0:

• NetObjects Script Builder 3.01• VisualAge for Java 3.0 Professional Edition• Remote Debugger

1.3 WebSphere Performance Pack

WebSphere Performance Pack is a set of tools for caching, load balancing, andWeb site replication. This is not an AS/400 product, but is available from the IBMSoftware Group. It comes in two versions.

The first version is Cache Manager. It provides a proxy caching capability. TheHTTP Server for AS/400 Web server already has caching proxy built into it. Thisis an enhancement over that. It uses more sophisticated algorithms and hassome additional features. It is basically a Web server that acts as a caching proxyand does that very well. It also has a built-in PICS filtering platform, calledPlatform for Internet Content Specifications. This is a self-rating system. You canput information on your Web page that basically rates the contents of the Webpage for violence, nudity, and so on. In the caching proxy, you can filter out thosetypes of sites. Anybody using the caching proxy to access the Internet will neversee the filtered content in their browser. This is especially useful in aneducational environment where you are trying to screen out that type ofinformation from students.

Performance Pack Cache Manager running on the AS/400 system is planned tobe available during the first half of 2000. Current plans are that it will be aseparately priced offering on the AS/400 system. Performance Pack CacheManager support is currently available on other operating systems.

Availability Services provides the network dispatching capability or load balancingcapability. This is needed when you want scalability or high availability services,for example, if you want multiple AS/400 systems to serve requests.

Perhaps you have one Web address, but need more than one server to serve therequests to deliver adequate response time. You need multiple machines to looklike one machine. Usually, a load balancer does that. All the requests come intothe load balancer and are forwarded to the different Web server machines basedon their capability of handling the requests. The load balancing software does notrun on the AS/400 system. It actually runs on an external box including an IBM2216 Router, AIX, SUN, or Windows NT box. It is a front end to multiple systems,including multiple AS/400 systems. This provides for scalability and highavailability.

Introduction to the IBM WebSphere family 3

1.4 WebSphere Site Analyzer

The WebSphere Site Analyzer tools provide site administration and analysis toolsthat can be used to administer and manage the usage of a Web site. Thecollected statistics reside on the server, for example an AS/400 system. This datais downloaded to a Windows-based workstation with the site analysis toolsinstalled. The tools perform the analysis and have graphical display functions todisplay the results. This is not an AS/400 product, but is available from the IBMSoftware Group.

The Site Analyzer Tools include such functions as:

• An administration site visualizer

• A report generator and builder

• A content analyzer that scans the Web site and identifies such items asduplicates, unavailable resources, and content with excessive size

• A usage analyzer that scans the Web logs for hits, requests, paths, agents,and so on (analysis can be scheduled and results placed in a database)

1.5 Putting it all together

Figure 1 shows how the family of WebSphere products fit together.

Figure 1. The WebSphere product family

Note the following points in regard to Figure 1:

• WebSphere Studio and VisualAge for Java are used to build the applications.

• WebSphere Application Server is used to run the applications. It works inconjunction with the HTTP Server.

WebSphere Studio

WorkbenchWizardsContentAuthoringSite DevelopmentContentManagement

VisualAgeApplicationProgrammingComponentDevelopmentTeamDevelopment

Standard Edition

DatabaseConnectionManagerJava ServletRuntime andServices

Advanced EditionClustering andscalingEnterprise JavaServer (EJS)DatabaseConnectionManagerJava ServletRuntime andServices

Enterprise EditionComposedBusinessComponentsTransactionapplicationenvironment

CICSEncina

Clustering andscalingEJS/EJBDatabaseConnectionManagerJava ServletRuntime andServices

Tivoli

WebspherePerformance Pack

CachingLoad Balancing

FilteringDistributed files

Http Server

NT AIX Solaris OS/400 S/390

Build Run Manage

4 Web Enabling AS/400 Applications with IBM WebSphere Studio

• WebSphere Performance pack is used for caching, load balancing, and Website replication.

• Tivoli is used for change management.

To find more information about the WebSphere family of products, refer to theWeb site: http://www.software.ibm.com/websphere

For the latest information on WebSphere of the AS/400 system, go to the Website at: http://www.as400.ibm.com/websphere

Introduction to the IBM WebSphere family 5

6 Web Enabling AS/400 Applications with IBM WebSphere Studio

Chapter 2. Installation and configuration

This chapter covers the installation and configuration of the environment requiredto run the servlets and JavaServer Pages discussed in this redbook. Thisincludes the IBM HTTP Server for AS/400 and the IBM WebSphere ApplicationServer (WAS).

In this redbook, all references to WebSphere without other designation should beinterpreted as references to IBM WebSphere Application Server for AS/400,Standard Edition, Version 2.0.

Installing and configuring the WebSphere Application Server on the AS/400system should take a minimal amount of time and effort. Before you begin, makesure that you have met the AS/400 software prerequisites. Refer to the ReadMefile available on the redbooks Web site (http://www.redbooks.ibm.com) for moreinformation about minimum software requirements. For download information,refer to Appendix A, “Example programs” on page 405.

2.1 Introduction to WebSphere Application Server for AS/400

The IBM WebSphere Application Server is a Java servlet-based Web applicationserver that helps you deploy and manage Web applications on the AS/400system. On the AS/400 system, the WebSphere Application Server works inconjunction with the IBM HTTP Server for AS/400.

There are some basic concepts that you must understand before you use the IBMWebSphere Application Server. For example, you should understand how toconfigure the HTTP server, and start or stop the HTTP server.

The WebSphere Application Server for AS/400 is invoked through a server APIprogram on the AS/400 system. As a server API program, Java servlet requestsrun under the main HTTP server job. Therefore, the request by default will rununder the QTMHHTTP user profile.

The HTTP server has an *ADMIN server instance that provides the administrationand configuration graphical user interface (GUI) to manipulate the HTTPconfiguration. You use this GUI to enable Java servlet and JSP support.

Today, the only Web server that supports the WebSphere Application Server onthe AS/400 system is the IBM HTTP Server for AS/400.

2.2 Installation considerations

The IBM WebSphere Application Server for AS/400 software that you needcomes standard with OS/400, but is optionally installed. For OS/400 V4R4, thefollowing software should be installed on your system:

© Copyright IBM Corp. 2000 7

• IBM OS/400 (5769-SS1)• AS/400 Developer Kit for Java (5769-JV1)• IBM HTTP Server for AS/400 (5769-DG1)• IBM WebSphere Application Server for AS/400 (5769-AS1)

2.2.1 Installing IBM WebSphere Application Server (V4R4)The IBM WebSphere Application Server Standard Edition Version 1.1 for AS/400support is provided by installing the 5769-AS1 product (already pre-loaded onyour system) on your AS/400 system. The AS/400 version has the sameinstallation structure as other platforms. The only difference is the installation rootdirectory. On the AS/400 system, it is installed in the Integrated File System(IFS). The installation root directory is /QIBM/ProdData/IBMWebAS/.

The WebSphere Application Server PTFs are the latest that are available. Theother PTFs that impact WebSphere may have been superseded by differentPTFs. You should always load the latest PTFs. You can obtain this list of PTFsfrom the WebSphere Application Server Group PTF SF99027. The group PTF isnormally refreshed every month. The group PTF number does not change but isreused and updated with any additional WebSphere PTFs. It also contains thelatest HTTP Server, database, and Java group PTFs.

At the time of writing this redbook, the current version of the WepSphere groupPTF (SF99027) upgraded the WebSphere Application Server to Version 2.02 forV4R4. The group PTF status can be displayed on the AS/400 system by runningthe following command:

DSPDTAARA QAPPSVR/SF99027

Version 2.02 is installed if the display shows either of the following messages:

Group PTF#: SF99027-03 V4R4M0 09/01/1999Group PTF#: SF99027-02 V4R4

Version 1.1 is installed, if the display shows:

Group PTF#: SF99027-01 V4R4M0 06/29/1999

2.2.2 Installing IBM WebSphere Application Server (V4R3)This redbook was written using WebSphere Application Server 2.02 installed onan AS/400 system at release level V4R4. It is possible to run the WebSphereApplication Server on a V4R3 system. At the time of writing this redbook, onlyWebSphere Application Server 1.1 was supported for V4R3. All the redbookexamples, application design, testing, and configuration were done using V4R4and WebSphere Application Server 2.02. No testing was done on V4R3.

For OS/400 V4R4, the AS/400 Developer Kit for Java (5769-JV1) supportsmultiple versions of the Java Development Kit. The versions supported areJDK 1.1.6, JDK1.1.7, and JDK 1.2. The WebSphere Application Server forAS/400 requires JDK 1.1.6 or JDK 1.1.7 to be installed. At the time thisredbook was written, it did not support JDK 1.2.

JDK support

8 Web Enabling AS/400 Applications with IBM WebSphere Studio

The IBM WebSphere Application Server Standard Edition Version 1.1 ispackaged as part of the IBM HTTP server for AS/400 (5769-DG1) in V4R3. It is ano charge, optionally installable licensed program product. WebSphereApplication Server Group PTF SF99025 must be applied.

2.2.3 Considerations when upgrading from V4R3 to V4R4In V4R4, the WebSphere Application Server for AS/400 is a separate product.There is a new product library for its program objects. The new library is namedQAPPSVR. It is named QHTTPSVR for V4R3. This change must be reflected inthe HTTP configuration when migrating from V4R3 to V4R4. You can use the*ADMIN HTTP Server GUI to re-enable the Java servlet to automatically get thecorrect directives for your WebSphere instance.

In V4R4, due to the support of multiple JDKs support on the AS/400 system, thencf.jvm.classpath no longer contains the system classpath. The shipped versionof the jvm.properties file contains only the classpath for the WebSphere objects.Also, the following flag has been set to true by default:

ncf.jvm.use.system.classpath=true

If you migrate your jvm.properties from your V4R3 system, we recommend thatyou change the flag to “true”, and remove the old system classpath informationabout the JDK from the ncf.jvm.classpath setting.

2.3 Configuring the WebSphere Application Server for AS/400

The objective of this section is to successfully configure the WebSphereApplication Server on the AS/400 system. This involves:

• Creating a new instance of the HTTP server• Enabling servlets and JavaServer Pages for this instance• Configuring the WebSphere Application Server

The following steps take you through the complete configuration of theWebSphere Application Server environment:

1. Make sure that the HTTP server ADMIN instance is up and running.

a. To check it, type WRKACTJOB on the AS/400 command line. Verify whether theADMIN instance is running in the QHTTPSVR subsystem. If the ADMINinstance is not running, follow the next step. Otherwise, proceed to step 2.

b. From the AS/400 command line, type:

STRTCPSVR SERVER(*HTTP) HTTPSVR(ADMIN)

Or, perform the task in step c.

c. Open Operations Navigator by double-clicking on the icon on your desktop.Make a connection to the AS/400 system to which you wish to configurethe WebSphere Application Server. The Operation Navigator windowappears as shown in Figure 2 on page 10.

Installation and configuration 9

Figure 2. AS/400 Operation Navigator window

d. Click on the plus sign (+) next to the system icon on the left-hand side ofthe screen. Then, click Network->Server. Double-click the TCP/IP icon toopen it. Select HTTP Administration. Right-click, and select Start fromthe pop-up menu.

2. Access the HTTP ADMIN server. This is a special server instance that iscapable of allowing administrators to modify server configuration and start,stop, and restart instances of the HTTP server remotely using a Web browser.The ADMIN server usually runs on port 2001. Open a Web browser, and enterthe URL http://hostname:2001 (hostname is the name of your AS/400 system).

3. Enter your AS/400 login and password information when prompted. You nowsee the AS/400 Tasks display that appears as shown in Figure 3.

Figure 3. AS/400 Tasks page

10 Web Enabling AS/400 Applications with IBM WebSphere Studio

4. Click IBM HTTP Server for AS/400, and click Configuration andAdministration.

5. To create a configuration for your new server instance, click Configurations,and then click Create configuration. The Create Configuration page appearsas shown in Figure 4.

Figure 4. Configuration and Administration page

6. The right panel prompts you for a configuration name. This can be anything.Enter ABCCONF as the name. You can base your configuration file on an existingconfiguration file. In this case, select Create empty configuration, and clickApply.

7. Make sure the name of your configuration is in the drop-down box at the left,and click Basic. The Basic Configuration and Administration page appears asshown in Figure 5 on page 12.

Installation and configuration 11

Figure 5. Configuration and Administration page: Basic

8. Enter 80 for the port number. This is the default port number for the HTTPserver instance. If you change this, use a port number greater than 1024.Make sure that the port you use is not already being used. To check the port,type NETSTAT on the AS/400 command line, and select option 3.

9. In the Host Name box, enter the name of the AS/400 system. If you do notenter this value, a default value is set. This value is defaulted to the value setusing the Configure TCP (CFGTCP) command option 12. Click Apply.

10.Enable the HTTP methods required, as well as server-side includes. Click onRequest Processing and then Methods. The Methods Configuration andAdministration page appears as shown in Figure 6.

12 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 6. Configuration and Administration page: Methods

11.Select the boxes for HEAD, GET, and POST. Selecting TRACE is optional.Click Apply.

12.To enable Java servlets, click Java Servlets. The Java Servlets Configurationand Administration page appears as shown in Figure 7 on page 14.

Installation and configuration 13

Figure 7. Configuration and Administration page: Java Servlets

13.Select both check boxes that appear on this page. This allows you to use Javaservlets and JavaServer Pages. Click Apply.

14.The following step is required only if your AS/400 system is at the V4R3 level.Otherwise, go to step 15.

One of the key configuration files for the WebSphere Application ServerVersion 1.1 is the jvm.properties file, which resides in the following IFSdirectory/QIBM/ProdData/IBMWebAS/properties/server/servlet/servletservice/.

Within the jvm.properties file, one of the attributes tells the WebSphereApplication Server which HTTP configuration file is being used to runWebSphere. That information needs to be updated to point to theconfiguration file you configured. The shipped default configuration file isCONFIG. An entry in the properties file using CONFIG looks like this example:

#ncf.native.httpd.cnf.path=c:\winnt\httpd.cnfncf.native.httpd.cnf.path=/QSYS.LIB/QUSRSYS.LIB/QATMHTTPC.FILE/CONFIG.MBR

In this case, use an ASCII-based text editor to change the line to point to theconfiguration file ABCCONF.MBR instead of CONFIG.MBR.

15.Create a new instance of the HTTP server that uses the configuration file thatwe just created. From the HTTP Server Configuration and Administrationpage, click Create server instance under Server Instances. The HTTPCreate server instance page appears as in shown Figure 8.

14 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 8. Configuration and Administration page: Create server instance

16.Enter ABCSERVER as the name of the instance. You should use a meaningfulname. You may want to use the same name as you did for the configurationfile.

17.Select your configuration file, ABCCONF, from the drop-down list.

18.Click Create to create the instance.

19.Directives are added to the HTTP configuration file as a result of theconfiguration work that we did. This example shows the directives as theyappear for a WebSphere Standard Edition 1.1 configuration.

This information is stored in file QUSRSYS/QATMHTTPC. The followingdirectives are added to the HTTP configuration file:

# Enable WebSphere supportService /servlet/* /QSYS.LIB/QHTTPSVR.LIB/QZHJSVLT.SRVPGM:AdapterService*Service /*.jsp /QSYS.LIB/QHTTPSVR.LIB/QZHJSVLT.SRVPGM:AdapterService*ServerInit /QSYS.LIB/QHTTPSVR.LIB/QZHJSVLT.SRVPGM:AdapterInit/QIBM/ProdData/IBMWebAS/properties/server/servlet/servletservice/jvm.propertiesServerTerm /QSYS.LIB/QHTTPSVR.LIB/QZHJSVLT.SRVPGM:AdapterExitPass /IBMWebAS/samples/* /QIBM/ProdData/IBMWebAS/samples/*Pass /IBMWebAS/doc/* /QIBM/ProdData/IBMWebAS/doc/*Pass /IBMWebAS/system/admin/* /QIBM/ProdData/IBMWebAS/system/admin/*Pass /IBMWebAS/* /QIBM/ProdData/IBMWebAS/web/*# end - WebSphere support

The following directives appear for a WebSphere Standard Edition 2.02configuration. The Information is also stored in the fileQUSRSYS/QATMHTTPC.

# Enable WebSphere supportService /servlet/* /QSYS.LIB/QAPPSVR.LIB/QZHJSVLT.SRVPGM:AdapterServiceService /*.jsp /QSYS.LIB/QAPPSVR.LIB/QZHJSVLT.SRVPGM:AdapterServiceServerInit /QSYS.LIB/QAPPSVR.LIB/QZHJSVLT.SRVPGM:AdapterInit/QIBM/ProdData/IBMWebAS/properties/bootstrap.propertiesServerTerm /QSYS.LIB/QAPPSVR.LIB/QZHJSVLT.SRVPGM:AdapterExit

Installation and configuration 15

Pass /IBMWebAS/samples/* /QIBM/ProdData/IBMWebAS/samples/*Pass /IBMWebAS/* /QIBM/ProdData/IBMWebAS/web/*# end - WebSphere support

In Version 2.02, the key properties file is a new file called bootstrap.properties.The jvm.properties file in version 1.1 is no longer used. Most of the attributesin the jvm.properties map back into the bootstrap.properties file. There is noreference back to the HTTP configuration file in the bootstrap.properties file.You do not need to update the bootstrap.properties file for your particularserver instance.

2.3.1 Adding directivesRather than using the default directories, you may want to use your owndirectories to serve HTML pages, JSPs, applets, and images. In this case, youmust add PASS directives to the HTTP configuration to allow the HTTP server toserve the files from your directories. To do this, use the HTTP ServerConfiguration and Administration page.

2.3.1.1 Adding directives for the ABC Company sample projectSection 4.3.1, “Publishing to the AS/400 system” on page 125, explains how topublish the WebSphere Studio sample project (ABC Company Web site) to theAS/400 system. In order for the WebSphere Studio application to select thecorrect AS/400 file path, which contains the application files, you need to adddirectives to your HTTP configuration.

Perform the following tasks to add directives to the ABCCONF configuration:

1. Open a Web browser, and enter the URL http://hostname:2001 (hostname isthe name of your AS/400 system).

2. Enter your AS/400 login and password information when prompted.

3. Click IBM HTTP Server for AS/400, and then click Configuration andAdministration.

4. To add directives to the ABCSERVER instance, click RequestingProcessing, and then Request routing. The Configuration andAdministration page appears as shown in Figure 9.

16 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 9. Configuration and Administration page: Adding directives

5. To add the required directives, enter the following information in thecorresponding fields:

• Action: Pass• URL template: /*

• Replacement file path: /qibm/proddata/ibmwebas/*

6. Click the Apply button.

7. Click Display Configuration to verify that the Pass directives you add areplaced after the Service directives as shown in Figure 10 on page 18. If theyare in front of the Service directives, your servlets and JSPs may not bepassed to the WebSphere service programs.

Ensure that the Index number matches the same index number in the lastrow. Verify that the Insert after radio button is selected.

Note

Installation and configuration 17

Figure 10. Configuration and Administration page: Display configuration

2.3.2 Testing your HTTP server configurationTo test the HTTP configuration (ABCCONF) that you just created, perform thefollowing tasks:

1. Start the server instance. On the IBM HTTP Server Configuration andAdministration page, click Server Instances->Work with server instance.The Work with server instances page appears as shown in Figure 11.

18 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 11. Configuration and Administration page: Server Instances

2. Select the server instance ABCSERVER from the drop-down list, and click theStart button.

3. To test if the configuration is successful, start a browser session on your client.Enter the URL:

http://hostname:port/servlet/HelloWorldServlet

Replace hostname with the name of your AS/400 system and port with theTCP/IP port that you are using.

As shown in Figure 12, if Hello World is displayed in your browser, theWebSphere Application Server is set up and ready to go.

Figure 12. HelloWorldServlet

Installation and configuration 19

To run your own servlets, place them in the \QIBM\ProdData\IBMWebAS\servletsdirectory in the AS/400 system IFS. You can place your HTML and JSP files in the\QIBM\ProdData\IBMWebAS directory.

2.3.3 Configuring the AS/400 Toolbox for JavaThe WebSphere Studio Wizards run on a client platform. To allow the WebSphereStudio Wizards to access AS/400 resources, you need to set the classpath inyour PC to point to AS/400 Toolbox for Java jt400.jar file. It is found in the/QIBM/ProdData/HTTP/Public/jt400/lib/ directory path in the AS/400 IFS.

Either copy the jt400.jar file to your PC, or map a network drive to the AS/400system to set the classpath.

2.3.4 Troubleshooting the WebSphere Application ServerTo learn more about the WebSphere Application Server, servlets, JSPs, and XML,refer to the documentation and FAQs at: http://www.as400.ibm.com/websphere

2.3.5 Installation and configuration on other platformsFor installation and configuration of the WebSphere Application Server on otherplatforms, refer to the redbook WebSphere Application Servers: Standard andAdvanced Editions, SG24-5460.

2.4 WebSphere Application Server Administration

To start the WebSphere Application Server Administration support, enter this URLfrom your Web browser:

http://hostname:administration_port

The default port is 9090 (use port 9527 for other platforms). If you configuredmultiple instances, use the administration port configured for the new instance.

The Administration support enables you to:

• Customize settings for a variety of Application Server components• Configure servlets and set up aliasing and filtering• Establish and maintain security• Collect data and monitor the Application Server

Test the administration port to make sure the WebSphere Application ServerAdministration support is running on the port you specified.

As shown in Figure 13, if the login page for the WebSphere Administration GUI isdisplayed, the administration support for your new instance is working.

20 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 13. Administration Log in page

Installation and configuration 21

22 Web Enabling AS/400 Applications with IBM WebSphere Studio

Chapter 3. WebSphere Studio tools

IBM WebSphere Studio is a suite of tools for the development of Webapplications. In this redbook, we refer to it simply as Studio. It is optimizedspecifically for building WebSphere Application Server applications, but you canalso use many of the Studio tools for development of applications for other Webservers or Web application servers. You run the WebSphere Studio developmenttools on a Windows workstation, but you can deploy the resulting application toan AS/400 system running IBM WebSphere Application Server. WebSphereStudio provides tools you can use for managing your Web application project andfor the creation of HTML, Java servlets, and JSPs.

Studio delivers a complete set of Web development tools with clear advantagesof performance, portability, and lower maintenance over other approaches suchas Common Gateway Interface (CGI) and Active Server Pages (ASP). Studiocombines graphical development wizards with tools for Web site design and Javadevelopment, with features including:

• A workbench environment that lets Web development teams organize andmanage Web development projects. This environment can be extended withsource control management (SCM) tools. Of particular interest is the ability touse Studio with the Lotus Domino Web Content Library, which, in addition toversion support, allows integration with Domino workflow.

• An industry-leading, easy-to-use, integrated visual page designer for JSPs,HTML and Dynamic HTML (DHTML) that accelerates Web page development.

• An integrated remote debugger for easy remote debug of server-side scriptsand logic (including JSP components, servlets, JavaBean components, andmore). The remote debugger requires the Standard or Advanced edition ofIBM WebSphere Application Server.

• Integrated wizards to help developers create dynamic interactive Web pages.Wizards generate JSPs, JavaBeans, SQL statements, and servlets.

• Tighter integration between IBM VisualAge for Java Professional Edition, V3.0and Studio, making it easy for teams to communicate and work together todevelop Web-based, e-business applications.

• An integrated applet designer based on the NetObjects BeanBuildertechnology.

• NetObjects ScriptBuilder allows for easier script editing of Extensible MarkupLanguage (XML) and Wireless Markup Language (WML).

• An integrated Web art designer that lets you create masthead images,buttons, and other graphics.

• An integrated animated GIF designer that makes it easier to create animatedGIFs.

• A development copy of IBM WebSphere Application Server for building andtesting Web applications.

The following tools are included in WebSphere Studio Version 3.0:

• Studio WorkBench• Studio Wizards

© Copyright IBM Corp. 2000 23

• Page Designer• Applet Designer

The following components are optional with WebSphere Studio Version 3.0:

• NetObjects Script Builder 3.01• VisualAge for Java 3.0 Professional Edition• Remote Debugger

Minimum hardware requirementsThe minimum hardware requirements are:

• Intel Pentium class PC• 180 MB of free disk space for installation• CD-ROM drive• 32 MB of memory (minimum)• VGA, or better video adapter, configured for at least 256 colors

Minimum software requirementsThe minimum software requirements are:

• Windows 95, Windows 98 or Windows NT, Version 4.0 with Service Pack 3• Microsoft Internet Explorer Version 4.0 (or higher) or Netscape Navigator

Version 4.5 (or higher)

3.1 Studio WorkBench

The Studio Workbench is the integration point for the tools suite. In this redbook,we refer to it simply as the Workbench or the Studio. You can create, open, andedit all types of files from the WorkBench. You can launch Page Designer andother tools in the suite against a particular file directly from the Workbench. Youcan also register other tools for editing a particular file type from the Workbench.

The Workbench also helps manage and maintain your Web site applications andfiles. You use projects and folders in the Workbench to group and organize files.You can create, delete, copy, and move files from the Workbench. TheWorkbench provides basic check-in and check-out capabilities to control filemanagement in a team environment and integrates with leading source controlsystems.

The Workbench also provides you a central point for managing the publication ofyour finished Web site. You define properties of the server to which you want topublish. Workbench then automatically manages the distribution of all individualfiles within a project to the selected server.

3.1.1 Creating a new projectTo work on WebSphere Studio, you first need to create a project withinWebSphere Studio. To do so, follow these steps:

1. Start WebSphere Studio if it is not already started. When Studio starts, youare immediately prompted to create a new project or open an existing one(Figure 14).

24 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 14. Studio Workbench: Welcome to IBM WebSphere Studio

2. Select the Create a new project radio button, and click OK. You are thenprompted for the necessary project information:

a. Type DemoCompany as the name of the project.

b. Enter x:\DemoCompany as the project folder.Replace “x” with the workstation drive on which you want to create theproject.

c. Leave project template as <none>.

d. Click OK. A new project is created and you go to the Studio Workbench.

In this chapter, we work with the DemoCompany project for demonstrationpurposes. At this point, your window should appear as shown in Figure 15.

Figure 15. Studio Workbench: The workbench with the new project

WebSphere Studio tools 25

3. Notice that the workbench is divided into two frames. The left-hand frame isalways the File view. The right-hand frame is either the Publishing view or theRelations view.

4. The File view represents the physical organization of your Web site sourcefiles. In the Studio main window, the File view is in the left pane, and it isalways open. It is a hierarchical tree of the selected project and its folders.This view represents the directory structure of a project as it exists in the localfile system or shared file system.

The highest level in the tree is the project. A project can contain files andfolders. Folders can contain files and other folders. This lets you organize yourfiles in any way that you like, making it easy to manage all the files for anentire Web site as a unit.

5. In the Studio Workbench, you can see the following options:

• Menu bar: Provides access to all the available functions. If you can't find afunction in a pop-up menu, look for it in the menu bar.

• Main tool bar: Gives you quick access to common functions (New, Open,Print, Cut, Copy, and Paste) and Studio-specific functions such as to InsertFolder, Insert File, Publish, Compile, and Run the selected wizard. It alsolets you toggle the between the Relations view and the Publishing view andsynchronize them with the File view.

• File filter tool bar: Lets you filter files in all the views by their file types.For example, you can use the file filters to hide image, audio, andexecutable files.

• Link filter tool bar: Lets you filter the files in the Relations view by the typeof links that they have. With large Web sites, this can help you locatespecific areas of interest, such as outside links or broken links.

• Status bar: As you move your mouse over objects in a view, the status barprovides details, such as the path or type of link and the current publishingstage. The status bar has a fixed position at the bottom of the main window.

6. Studio Workbench has visual cues, file filters, and link filters.

• Visual cues: Studio provides several visual cues so you can determine thestate of a file at a glance.

Look for these indicators next to a files icon in any of the Studio views:

The file cannot be published.

A file you checked out for editing.

A file someone else checked out for editing.

26 Web Enabling AS/400 Applications with IBM WebSphere Studio

• Link types and link filters: Your project files can contain many types oflinks.

– Links to specific places in the file– Links to embedded images in the same file– Links to other files in the same project– Links to files on other Web sites, on your Web servers, or anywhere in

the world

Studio recognizes these standard hypertext links, manages them for you,and lets you know when they are broken. It also recognizes the links to filesthat are specified as parameters in Java servlets, CGI, and Perl scripts.

The Relations view uses different images to represent each of these linktypes. It is common for the relationship between two files to be representedby more than one type of link. For example, the relationship between an.html file and a .gif image is represented by both an inside link (both filesare in the project) and an embedded link.

These icons define the links:

A file that has been published.

A file that has been modified since the last time it was published.

A link to another file in the same project.

A link to a file, such as an image or frameset, that is rendered onthe same page.

A link to a file outside the project.

A link from a file to another file in the project with an incorrect path.

A link to a file that cannot be verified using the HTTP protocol.

A link that represents a user-defined relationship.

A link from a publishable file to a source file that is used to create it.

WebSphere Studio tools 27

3.2 Studio Wizards

WebSphere Studio has several wizards that provide a quick and easy way togenerate servlets, JSPs, and JavaBeans.

Servlets and JavaBeansServlets and JavaBeans are two types of Java classes used in the WebSphereStudio Wizards. Servlets are server-side Java programs that use the Java servletApplication Programming Interface (API) and its associated classes and methods.They are similar to applets, but they run on a server rather than a client platform.Servlets run on a Java-enabled Web server, such as the WebSphere ApplicationServer, and extend the server's capabilities. When a browser sends a request tothe server, the server can send the request information to a servlet and have theservlet construct the response that is sent back to the browser.

JavaBeans are Java programs that follow the JavaBean specification from SunMicrosystems. By design, they are reusable components that can be called fromother Java programs. To accomplish this, JavaBeans have standard ways ofimplementing their properties, methods, and events, so they can be examinedand manipulated programmatically.

JavaServer Pages (JSP files)JSP files, or JavaServer Pages, are the way the WebSphere Studio implementsdynamic page content. JSPs make it possible to embed Java right into Webpages. One of the advantages of JSP technology is that it enables you toeffectively separate the HTML coding from the business logic in your Web pages.You use JSPs to access reusable components, such as servlets, JavaBeans, andJava-based Web applications. JSPs also support embedding inline Java codewithin Web pages. JSPs are similar to Microsoft's Active Server Pages (ASP).

JSP files allow the Application Server to dynamically add content to HTML pagesbefore they are sent to a requesting browser. The dynamic content can comefrom any available databases and file systems to provide Web visitors with themost timely and accurate data. JSP support for JavaBeans enables you to reusecomponents across your Web site.

The JSP files created by the Studio Wizards contain the following HTML tags andJSP tags defined by the JSP specification:

• <BEAN> to access a JavaBean when the page is processed• <INSERT> to embed variables in the page

A link to a file specified as a parameter by a user-defined rule.

A link to a specific point within the same file.

A link to the same file that contains the link.

28 Web Enabling AS/400 Applications with IBM WebSphere Studio

• HTML to format the variable data• <REPEAT> to repeat a block of HTML tagging that contains <INSERT> tags

and the HTML formatting tags

When you install the Application Server on a Web server, the Web server'sconfiguration is set to pass HTTP requests for JSP files (files with the extension.jsp) to the Application Server. The Application Server configuration is set to passJSP files to its JSP processor (pageCompile). The JSP processor creates andcompiles a servlet from each JSP file. The processor produces two files for eachJSP file:

• .java file: Contains the Java language code for the servlet• .class file: The compiled servlet

When the Application Server processes a JSP file, it does the following tasks:

• Parses the JSP file

– Strips out the Java code and creates a valid .java file (servlet)– Compiles the .java file to produce a .class file

• Executes the .class file

– Reads in the original JSP file

– Write Puts the resulting data into the output page (replacing the specialtags)

– Writes Java and HTML output to the browser

The generated .java and .class files are stored in the Web serverservlets\pagecompile directory. A timestamp is kept inside the generated .javafile. It is only recreated and recompiled if the .jsp file changes.

3.2.1 Importing an existing Web siteAn import wizard is provided from within Studio Workbench. It copies existingWeb site files from their server on the Web into a WebSphere Studio project.This is useful if you want to start your development from an existing Web site.Importing uses either the HTTP or FTP protocol to bring the files from theirexisting file location into the Studio project.

To start the Import wizard, follow these steps:

1. Select File->Import. The Import Wizard, as shown in Figure 16 on page 30 isdisplayed. It prompts you for the source URL.

2. Enter the URL from where you want to import Web site files into theWebSphere Studio.

You can now use the Studio tools to develop a Web site based on the importedsite.

WebSphere Studio tools 29

Figure 16. Studio Workbench: Import Wizard

Refer to Chapter 4, “Restoring the ABC Company Web site sample project” onpage 121, for a complete example of importing an existing Web site.

3.2.2 Database WizardSeveral wizards are provided for you from within the Studio Workbench forquickly and easily adding dynamic content from a relational database to yourWeb pages. The wizards generate the server side Java and SQL code necessaryfor retrieving and updating database information. With these wizards, you candevelop a Web application that does a simple database query without writing anyJava or SQL code.

You can use these wizards to build dynamic Web pages that access DB2 forAS/400 with either the AS/400 Developer Kit for Java JDBC driver (the nativeJDBC driver) or the AS/400 Toolbox for Java JDBC driver (the Toolbox JDBCdriver). Since the WebSphere Studio Workbench runs on a workstation, you willneed to use the Toolbox JDBC driver during your initial development. You canthen edit the wizard generated source code to use the Native JDBC driver whenyou are ready to deploy your servlet to the AS/400 system. The Studio Wizardsrecognize any JDBC drivers found in your workstation classpath and make themselectable by name. Make sure to add the Toolbox JDBC driver to yourworkstation classpath. See 2.3.3, “Configuring the AS/400 Toolbox for Java” onpage 20, for information about adding drivers in your workstation classpath.

The following Studio Wizards are available:

• SQL Wizard• Database Wizard• JavaBean Wizard

In this section, we use SQL, Data Access, and JavaBean wizards to create,insert, update, and delete records in an AS/400 database.

3.2.2.1 Creating an SQL SELECT statementThe Studio provides the SQL Wizard, which allows you to interact with thedatabase metadata to build SQL statements. These statements are stored in afile with an .sql extension. The Database Wizard uses the created .sql file to

30 Web Enabling AS/400 Applications with IBM WebSphere Studio

generate the necessary JavaBeans, servlets, and XML files to execute the SQLstatement.

In this section, we create a SELECT statement to view an AS/400 database table.We use the Item table, which is found in AS/400 APILIB database. Refer toChapter 5, “Order Entry application” on page 137, for descriptions of thedatabase tables we use in this chapter. To successfully do these steps, you must:

• Restore APILIB to your AS/400 system. See Appendix A, “Example programs”on page 405, for information about how to obtain the APILIB database.

• Make the AS/400 Toolbox for Java .zip or .jar file is available through yourworkstation classpath.

To use WebSphere Studio to create a query of the AS/400 Item Table, followthese steps:

1. Select the DemoCompany project folder.

2. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

The Welcome window appears as shown in Figure 17.

Figure 17. Studio SQL Wizard

3. Complete the following steps:

a. Enter ItemSearch as the name of the query. The wizard adds an .sql file toyour project.

b. Click Next.

The Logon window appears shown as shown in Figure 18 on page 32.

WebSphere Studio tools 31

Figure 18. SQL Select: Logon

4. Complete the following steps:

a. Enter the information the wizard needs to connect to the database, forexample:

• Database URL: jdbc:as400://sysname• Userid: USERID• Password: PASSWORD• Driver: AS/400 Toolbox for Java

Replace sysname with the name of your AS/400 system. Case is importantfor the Userid and Password. Both should be in uppercase.

b. Click Connect to connect to the specified database.

c. After you successfully connect, click the Next button to go to the next tab.

5. The Schema(s) to View window appears as shown in Figure 19. If theSchema(s) to View window does not appear, click the View schema(s) button.

Figure 19. SQL Select: View schema(s)

32 Web Enabling AS/400 Applications with IBM WebSphere Studio

6. Complete the following steps:

a. In the Schema(s) to View window, find the Library with which you want towork, which, in this case, is APILIB. Click on the library to select it, andclick the Add>> button.

b. If there are schema(s) in the Selected Schema window that you want toremove, select the schema, and click the <<Remove button.

c. Click the OK button to return to the Tables window.

The Tables window appears as shown in Figure 20.

Figure 20. SQL Select: Table window

7. Complete the following steps:

a. Select the Select radio button under Statement type.b. Select the APILIB.ITEM table from the list of tables shown.c. Click Next.

The Join window appears as shown in Figure 21 on page 34.

WebSphere Studio tools 33

Figure 21. SQL Select: Join window

8. Click the Next button.

The Columns window appears as shown in Figure 22.

Figure 22. SQL Select: Columns window

9. Complete the following steps:

a. Verify whether the correct table name is selected in the Selected table(s)drop-down list.

b. Select the required columns, and click Add>> button to move thesecolumns over to Columns to include. Refer to Figure 22 as a guide.

c. When the SQL query is used, data from the selected columns is retrievedby the SELECT statement. After making your column choices, you can

34 Web Enabling AS/400 Applications with IBM WebSphere Studio

change the order in which they appear by selecting the column name andusing the Move Up and Move Down buttons.

d. Click Next.

The Condition 1 window appears as shown in Figure 23.

Figure 23. SQL Select: Condition window

10.Complete the following steps:

a. Verify whether the correct table name is selected in the Selected table(s)drop-down list.

b. Select a column name on which you wish to put a condition, which is IID(Item Number) in this case.

c. Select the condition from the Operator list box. In this case, select is afteror equal to.

d. Click the Values field, and then click the Parameter button. Enter Low forthe field in the parameter dialog.

e. Click the OK button to return to the Condition 1 tab.

f. Click the Find on another column button.

The Condition 2 window appears as shown in Figure 24 on page 36.

WebSphere Studio tools 35

Figure 24. SQL Select: Condition window

11.Complete the following steps:

a. Check if the correct table name is selected in the Selected table(s)drop-down list.

b. Select the Find fewer rows (AND) radio button.

c. Select the column name on which you want to put a condition, which is IID(Item Number) in this case.

d. Select the condition from the Operator list box, is before or equal to, inthis case.

e. Click the Value field, and then click the Parameter button. Enter High forthe field in the parameter dialog.

f. Click the OK button to return to the Condition 2 tab.

g. Click Next.

The Sort window appears as shown in Figure 25.

36 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 25. SQL Select: Sort window

12.Complete the following steps:

a. Select a column name from the columns box, IID (Item ID) in this case.

b. Select the order from the Sort order drop-down list. Select Ascending.

c. Click the Add button.

d. The selected column is used to sort the retrieved data. You can add morecolumns on which to sort. After you add the columns to the Columns to sorton box, you can change their order by using Move Up and Move Downbuttons.

e. Click Next.

The SQL window appears as shown in Figure 26 on page 38.

WebSphere Studio tools 37

Figure 26. SQL Select: Statement window

13.Complete the following steps:

a. The SQL tab shows the completed SQL statement. You can copy thestatement to the clipboard to use it in another application.

b. You can test the SQL statement by clicking on the Run SQL button.

Valid Item numbers are 000001 to 000100.

c. Click Next.

The Finish window appears as shown in Figure 27.

Figure 27. SQL Select: Finish window

14.Click the Finish button.

38 Web Enabling AS/400 Applications with IBM WebSphere Studio

15.Check in the generated ItemSearch.sql file in the Studio Workbench.

3.2.2.2 Building the servlet using the SQL SELECT statementWe use the Database Wizard to create a servlet, which uses the SQL statementthat we created in the previous section. The Database Wizard helps you createWeb applications that can query, insert, update, and delete relational data.

When you start the Database Wizard, Studio assumes that the current project inthe file view is where you want your database access files to go. The DatabaseWizard puts the .java, .class, and .servlet files it creates in the servlet folder, andthe HTML and JSP files in whichever folder is current (selected) when you startthe Database Wizard.

Follow these steps:

1. Select the DemoCompany project from the Studio Workbench.

2. Start the Database Wizard by selecting Tools->Wizards->Database Wizard.

The Database Wizard window appears as shown in Figure 28.

Figure 28. Studio Database Wizard

3. Complete the following steps:

a. Select the appropriate SQL statement. Select\DemoCompany\ItemSearch.sql.

b. Click Next.

The Web Pages window appears as shown in Figure 29 on page 40.

WebSphere Studio tools 39

Figure 29. Database Wizard: Web Page window

4. Complete the following steps:

a. The Web pages window allows you to specify the HTML and JSP files thatwill be generated. You need an input page to collect the data for insertion,an output page to show the result from the query, and an error page ifsomething unforeseen happens.

i. Select the input page check box.ii. Select the output page check box.iii. Select the error page check box.

b. Click Next.

The Input Page window appears as shown in Figure 30.

Figure 30. Database Wizard: Input Page window

40 Web Enabling AS/400 Applications with IBM WebSphere Studio

5. Complete the following steps:

a. Select both the Low and High input parameters.

b. To give the fields a more meaningful name, follow these steps:

i. Select the parameter name check box.

ii. Select the parameter line and then change the caption to somemeaningful name by clicking the Change button and entering the text inthe dialog.

c. Click Next.

The Results Page window appears as shown in Figure 31.

.

Figure 31. Database Wizard: Results Page window

6. Complete the following steps:

a. Select the following items:

• APILIB_ITEM_IDATA• APILIB_ITEM_IID• APILIB_ITEM_INAME• APILIB_ITEM_IPRICE

b. If desired, change all of the captions to more meaningful names. Select thefirst row, and click Change. When prompted, enter the name. Follow thisstep to change the caption for all the fields.

c. Ensure that the Table radio button is selected.

d. Click Next.

The Standard Error Page window appears as shown in Figure 32 on page42.

WebSphere Studio tools 41

Figure 32. Database Wizard: Standard Error Page window

7. Click Next.

The Methods window appears as shown in Figure 33.

Figure 33. Database Wizard: Methods window

8. Click Next.

The Session window appears as shown in Figure 34.

42 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 34. Database Wizard: Session window

9. Complete the following steps:

a. Select the No radio button.

b. Click Next.

The Finish window appears as shown in Figure 35.

Figure 35. Database Wizard: Finish window

WebSphere Studio tools 43

10.Complete the following steps:

a. Give a meaningful name to the generated source files. Click Rename andtype ItemSearch in the Prefix dialog. Click OK. Note that all of the files nowhave the prefix of ItemSearch.

b. Click the Finish button to generate the code.

You should see the following files added to the DemoCompany project:

• ItemSearchInput.html• ItemSearchResults.jsp• ItemSearchError.jsp

If you look inside the servlet->DemoCompany folder, you also see that thefollowing files have been created:

• ItemSearchDBBean.java• ItemSearch.java• ItemSearch.servlet• ItemSearchDBBean.class• ItemSearchDBBean.class

11.Check all of the generated files into Studio. Select the DemoCompany folder.Using the pop-up menu, select the Check In option. The files are alreadychecked in if the Check In option is not available from the pop-up menu.

Before you can view the Web site application, you must publish it.

3.2.3 Publishing the Web siteTo deploy an application developed using WebSphere Studio, you must publish it.You can publish your project files to your local workstation, to a shared filesystem, or to a remote system that you can access using FTP. These systemscan hold test or live sites. You can publish entire projects, a part of a project, orjust individual files.

A publishing stage specifies the publishing Web server (or Web servers) and thefolder structure of the files. To publish the Web site, you need to define at leastone publishing stage with an accessible publishing server. By default, allWebSphere Studio projects have a Test and a Production publishing stage, andyou can create and name your own custom stages. If you have an HTTP serverrunning locally, the Test stage starts out with localhost as the default publishingserver, and it has the same file and directory structure as the File view. In all othercases, you must add one or more publishing servers to the stage and configuretheir properties.

3.2.3.1 Setting up publishing stagesIn WebSphere Studio, a publishing stage is a model of the structure of your Website that is used for publishing. A publishing stage specifies the publishing Webserver (or Web servers) and the folder structure of the files. Having more thanone publishing stage can be useful if you publish your Web sites to different Webservers at various stages of their design and development. For example, you mayhave a Web server inside the firewall that you use to review your work before it iscomplete, and another Web server outside a firewall where you publish your finalWeb site.

44 Web Enabling AS/400 Applications with IBM WebSphere Studio

Creating publishing stagesWebSphere Studio comes with two publishing stages for you to use: Test andProduction. If you have an HTTP server installed on your computer, WebSphereStudio detects this and creates a default server setting for your Test publishingstage that points to your local host (http://localhost). Otherwise, WebSphereStudio uses the first server you define for a Test or Production stage as thedefault server for that stage in each project. You can change the default stagesetting for both the Test and Production stages at any time. You can define andcreate other custom publishing stages as needed.

When the publishing view is on, you can switch from one publishing stage toanother:

• To change the default server for Test and Production publishing stages:

1. From the main menu, select Tools->Publishing.2. Click the Advanced tab, and select a server from the list.

• To create a custom publishing stage:

1. Select Project->Custom Publishing Stages.2. Enter the name, and click the Add button.

• To copy the files from one publishing stage to another:

1. Select Project->Copy Publishing Stages.2. Select the From and To stages.

Defining the default publishing server in a stageWhen you add a new server to a stage, you can make it the default publishingserver. WebSphere Studio then uses this new default publishing server whendetermining the default publishing path of any new files you add to the project orany files that you move. The files that were on the other server (previously thedefault publishing server) are now considered to have customized publishingpaths. If you want to move them to the new default publishing server, you candrag and drop them there, or you can change their default publishing pathproperty.

• To add a server to a publishing stage:

1. Right-click on the stage icon.2. Select Insert->Server from the menu, and then enter the server name.3. After you add the server, define its properties.

• To change the default server:

1. Right-click on the stage icon.2. Select Properties from the menu.3. Click the Advanced tab, and select the server.

Notice that this server is added under the stage icon. Right-click on thisserver, and select Properties. The properties window appears, selectDefine Publishing Targets, and enter the path for the Web server and theWebSphere server.

Note

WebSphere Studio tools 45

3.2.4 Publishing to the AS/400 systemTo publish the Web site to the AS/400 system, perform the following steps:

1. Map a network drive to the IFS of the AS/400 system. In this example, we mapthe I: drive to the root of the AS/400 IFS:

\\yourAS400\root

2. Start WebSphere Studio, and open the DemoCompany project.

3. Select Project->Publishing Stage->Test.

4. Select the Publishing View by selecting View->Publishing.

5. Add the AS/400 server to the Test stage. Right-click the Test stage icon.Select Insert->Server from the menu as shown in Figure 36.

Figure 36. Inserting a server in the Test publishing stage

6. Enter the server name, yourAS400, and the TCP/IP port on which youconfigured the WebSphere Application Server as illustrated in Figure 37. Afteryou add the server, you need to define its properties.

Figure 37. Inserting the AS/400 server in the Test publishing stage

As shown in Figure 38, you now see the new server under the Test publishingstage.

Figure 38. The Test publishing stage

7. To change the default server to your AS/400 server, right-click on the Teststage icon, and select Properties from the menu. Click the Advanced tab,and select the AS/400 server http://yourAS400 from the Default serverdrop-down list as illustrated in Figure 39.

46 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 39. Changing the default server

8. Close the Test Properties dialog by clicking the OK button.

9. Update the publishing targets for the AS/400 server by right-clicking on theAS/400 server icon, and selecting Properties from the menu. When thePublishing Properties dialog appears, click the Define Publishing Targetsbutton. When the publishing targets dialog appears as shown in Figure 40 onpage 48, verify that the targets match as shown here:

• html I:\QIBM\ProdData\IBMWEBAS\

• servlet I:\QIBM\ProdData\IBMWEBAS\servlets

Here, I: is a network drive assigned to the root of the AS/400 IntegratedFile System (IFS).

10.If your targets do not match the description in step 9, click the Browse buttonto navigate through the file system to find the files.

You may want to publish your HTML files to a separate directory. For this,you have to create an HTML directory under the\QIBM\ProdData\ibmwebas\html directory, and then add a Pass directive inyour HTTP configuration file.

Publishing target

WebSphere Studio tools 47

Figure 40. AS/400 Publishing Targets

11.Close the Publishing Targets dialog by clicking the OK button.

12.Close the Publishing Properties dialog by clicking the OK button.

13.To set a default publishing target, select Tools->Publishing Options from thepull-down menu. Click the Advance tab. Select the AS/400 publishing targetsystem from the Test drop-down list as illustrated in Figure 41.

Figure 41. Setting the AS/400 server as the default publishing server

14.Close the Publishing Options dialog by clicking the OK button.

15.To move the files to the publishing stage, select the DemoCompany project.Then, select Edit->Set as Publishable->Yes from the pull-down menu to setthe ABC Company files as publishable. This process moves all the projectcomponents under the Test->yourAS400 stage as illustrated in Figure 42.

48 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 42. Setting the project files as publishable

16.From the publishing view, select the server http://yourAS400. Right-click todisplay the pop-up menu, and select Publish this server.

17.Several dialogs may appear. Select the default options on each. Simply clickOK, Yes, or Yes to All, ignoring the warnings. Publishing causes WebSphereStudio to copy all the files set as publishable to the publishing target (a Webservers directory structure). After this publishing process finishes, you receivea report as illustrated in Figure 43 on page 50.

WebSphere Studio tools 49

Figure 43. Publishing a report for the Demo Company project

18.Browse through the report to ensure that no files were found with errors beforeattempting to proceed. In case errors were found, you need to correct them,and then repeat the steps in this section.

3.2.5 Previewing the Demo Company Web siteOnce you have published the Web site, you can preview it.

Perform the following steps to preview the Demo Company Web site:

1. Ensure that the WebSphere Application Server on AS/400 is up and running.

2. To test the publishing process, select the ItemSearchInput.html file from thepublishing view to preview it. Then, right-click and select Preview file withNetscape or Internet Explorer. When the Web browser appears, the DemoCompany input page appears as in Figure 44.

The first time you call a generated Studio Wizards servlet, it will be slow. This isdue to the fact that the JSP has to be compiled and the servlet has to connectto the database. Subsequent tries will be much faster.

Previewing Web sites

50 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 44. Input Search page on the browser

3. Enter the values for the search condition of the SQL statement. Valid valuesare 000001 to 000100. Click the Submit button to execute the query.

The generated servlet shows the results that satisfy the query condition asshown in Figure 45.

Figure 45. Result page on the browser

A number of files are generated by the Database Wizard. Figure 46 on page 52shows how they fit together.

WebSphere Studio tools 51

Figure 46. Application flow

To run the application, we enter the URL for the ItemSearch.html page. In thiscase, we enter: http://sysname:port/ItemSearch.html. The following actionsoccur:

1. The HTML form is displayed in the browser.

2. The action of the Submit button executes the ItemSearch servlet.

3. The ItemSearch servlet instantiates ItemSearchDBBean, which executes thequery.

4. The ItemSearch servlet calls the JSP named ItemSearchResults.jsp.

5. The ItemSearchResults JSP uses methods of the ItemSearchDBBean beanto retrieve the query results.

6. The JSP renders an HTML form that displays the query results.

3.2.6 More WebSphere Studio Wizard examplesIn this section, we show more examples using the Studio Wizards. Theseexample are all similar, but they show examples of generating different SQLstatements. We also show an example of the JavaBean Wizard. If you arecomfortable with the Studio Wizards, you can skip to the Page Designerexamples in 3.3, “Page Designer” on page 88.

3.2.6.1 Creating an SQL INSERT statementIn this section, we create a simple INSERT statement to insert records in the Itemdatabase table. Follow this process:

1. Select the DemoCompany project.

2. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

ItemSearchInput.html ItemSearch.java

servlet

ItemSearchDBBean

ItemSearchResults.jsp

JSP12

3

4

ACTION="/servlet/DemoCompany.ItemSearch"

5

6

http://sysname:port/ItemSearchInput.html Item

52 Web Enabling AS/400 Applications with IBM WebSphere Studio

The Welcome window appears as shown in Figure 47.

Figure 47. Studio SQL Wizard

3. Complete the following steps:

a. Enter ItemInsert as the name of the query. The wizard adds an .sql file inyour project.

b. Click Next.

The Logon window appears as shown in Figure 48.

Figure 48. SQL Insert: Logon window

4. Complete the following steps:

a. Enter the information the wizard needs to connect to the database, forexample:

WebSphere Studio tools 53

• Database URL: jdbc:as400://sysname

• Userid: USERID• Password: PASSWORD• Driver: AS/400 Toolbox for Java

Replace sysname with the name of your AS/400 system. Case isimportant for Userid and Password. Both should be in uppercase.

b. Click Connect to connect to the specified database.

c. Click Next.

The Tables window appears as shown in Figure 49.

Figure 49. SQL Insert: Tables window

5. Complete the following steps:

a. Click Insert under Statement type.

b. Select APILIB.ITEM from the list of tables shown.

c. Click Next.

The Insert window appears as shown in Figure 50.

54 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 50. SQL Insert window

6. Complete the following steps:

a. Select the columns that are to be part of the Insert statement by clicking inthe value text field to enable the Parameter button. For each column, clickthe Parameter button to enter a parameter value, and then type the nameof the parameter.

b. Click Next.

The SQL Statement window appears as shown in Figure 51.

Figure 51. SQL Insert: Statement window

WebSphere Studio tools 55

7. Complete the following steps:

a. The SQL tab shows the complete SQL statement. You can copy thestatement to the clipboard to use it in another application. You can also testthe SQL statement by clicking the Run SQL button.

b. Click Next.

The Finish window appears as shown in Figure 52.

Figure 52. SQL Insert: Finish window

8. Click Finish button.

9. Check in the generated ItemInsert.sql file in the Studio Workbench.

3.2.6.2 Building the servlet using the SQL INSERT statementWe use the Database Wizard to create a servlet, which uses the SQL statementthat we created in 3.2.6.1, “Creating an SQL INSERT statement” on page 52. TheDatabase Wizard helps you create Web applications that can query, insert,update, and delete relational data. Follow these steps:

1. Select the DemoCompany project from the Studio Workbench.

2. Start the Database Wizard by selecting Tools->Wizards->Database Wizard.

The Database Wizard window appears as shown in Figure 53.

56 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 53. Studio Database Wizard

3. Complete the following steps:

a. Select the appropriate SQL statement \DemoCompany\ItemInsert.sql.

b. Click Next.

The Web Pages window appears as shown in Figure 54.

Figure 54. Insert: Web Page

4. Complete the following steps:

a. The Web pages window tab allows you to specify the HTML and JSP filesthat will be generated. You need an input page to collect the data forinsertion, an output page to show the result from the query, and an errorpage if something unforeseen happens:

WebSphere Studio tools 57

i. Select the input page check box.ii. Select the output page check box.iii. Select the error page check box.

b. Click Next.

The Input Page window appears as shown in Figure 55.

Figure 55. Insert: Input Page window

5. Complete the following steps:

a. Select all of the check boxes by clicking the Check All button.

b. Move the fields, using the up arrow and down arrow buttons, to interchangethe order of the columns.

c. Select the parameters by clicking on the row. Click Change button tochange the caption to a more meaningful name. Repeat this for all theparameters.

d. De-select the following fields:

• URL• Driver• UserID• password

e. Click the Next button to go to the next tab.

The Results Page window appears as shown in Figure 56.

58 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 56. Insert: Results Page window

6. Complete the following steps:

a. Click the Uncheck All button to deselect all of the check boxes.

b. Select Number of affected rows and SQL statement.

c. Ensure that the Table radio button is selected.

d. Click Next.

The Standard Error Page appears as shown in Figure 57.

Figure 57. Insert: Standard Error Page window

7. Click Next.

The Methods window appears as shown in Figure 58 on page 60.

WebSphere Studio tools 59

Figure 58. Insert: Methods window

8. Click Next.

The Session window appears as shown in Figure 59.

Figure 59. Insert: Session window

9. Complete the following steps:

a. Select the Yes, store it in the user’s session radio button so that thegeneration bean will be placed in the session for the user. This makes thebean available for future use.

b. Enter the name of the bean, iteminsertbean. Note that this is in lowercaseletters. Case matters.

c. Click Next.

The Finish window appears as shown in Figure 60.

60 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 60. Insert: Finish window

10.Complete the following steps:

a. Give a meaningful name to the generated source files. Click the Renamebutton, and type ItemInsert into the Prefix dialog. CLick OK. Note that all ofthe files will now have the prefix of ItemInsert.

b. Click Finish to generate the code.

You should see the following files added to the DemoCompany project:

• ItemInsertInput.html• ItemInsertResults.jsp• ItemCustInsertError.jsp

If you look inside the servlet->DemoCompany folder, you also see that thefollowing files have been created:

• ItemInsertDBBean.java• ItemCustInsert.java• ItemCustInsert.servlet• ItemCustInsert.class• ItemCustInsertDBBean.class

11.Check all of the generated files into Studio. Select the DemoCompany folder.Using the pop-up menu, select the Check In option. The files are alreadychecked in if the Check In option is not available from the pop-up menu.

12.Publish the project to the server. Follow the same steps as described in 3.2.4,“Publishing to the AS/400 system” on page 46.

13.To test the publishing process, select the ItemInsertInput.html file from thepublishing view to preview it. Then, right-click, and select Preview file withNetscape or Internet Explorer.

14.When the Web browser appears, enter values for all the fields, as shown inFigure 61 on page 62, and click Submit to execute the query.

WebSphere Studio tools 61

Figure 61. The input page

The result is displayed as shown in Figure 62.

Figure 62. The output page

3.2.6.3 Creating an SQL UPDATE statementIn this section, we create an SQL update statement to update a row in the Itemdatabase table. Follow these steps:

1. Select the DemoCompany project.

2. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

The Welcome window appears as shown in Figure 63.

Figure 63. Studio SQL Wizard

62 Web Enabling AS/400 Applications with IBM WebSphere Studio

3. Complete the following steps:

a. Enter UpdateItem as the name of the query. The wizard adds an .sql file inyour project.

b. Click Next.

The Logon window appears as shown in Figure 64.

Figure 64. SQL Update: Logon window

4. Complete the following steps:

a. Enter the information the wizard needs to connect to the database, forexample:

• Database URL: jdbc:as400://sysname• Userid: USERID• Password: PASSWORD• Driver: AS/400 Toolbox for Java

Replace sysname with the name of your AS/400 system. Case isimportant for the Userid and Password; both should be in uppercase.

b. Click Connect to connect to the specified database.

c. Click the Next button to go to the next tab.

The Tables window appears as shown in Figure 65 on page 64.

WebSphere Studio tools 63

Figure 65. SQL Update: Tables window

5. Complete the following steps:

a. Click Update in the Statement type.

b. Select the APILIB.Item table from the list of tables shown.

c. Click Next.

The Update window appears as shown in Figure 66.

Figure 66. SQL Update window

64 Web Enabling AS/400 Applications with IBM WebSphere Studio

6. Complete the following steps:

a. Select the columns that are to be part of the Update statement by clickingin the value text field to enable the Parameter button. For each column,click the Parameter button, and then type the name of the parameter toenter a parameter value.

b. Click Next.

The Condition 1 window appears as shown in Figure 67.

Figure 67. SQL Update: Statement window

7. Complete the following steps:

a. Check if the correct table name is selected in the Selected table(s)drop-down list.

b. Select the column name on which you wish to put a condition, which is IID(Item Number) in this case.

c. Select the condition is exactly equal to, for example, from the Operatorlist box.

d. Click on the Value field, and then click the Parameter button. Enter ItemNofor the field in the parameter dialog.

e. Click OK.

f. Click Next.

The SQL window appears as shown in Figure 68 on page 66.

This tab shows the complete SQL statement. You can copy the statementto the clipboard to use in another application. You can also test the SQLstatement by clicking the Run SQL button.

WebSphere Studio tools 65

Figure 68. Update SQL statement

8. Click Next.

The Finish window appears as shown in Figure 69.

Figure 69. SQL Update: Finish window

9. Click Finish.

10.Check in the generated UpdateItem.sql file in the Studio Workbench.

3.2.6.4 Building the servlet using the SQL UPDATE statementWe use the Database Wizard to create a servlet, which uses the SQL statementthat we created in 3.2.6.3, “Creating an SQL UPDATE statement” on page 62.The Database Wizard helps you create Web applications that can query, insert,update, and delete relational data.

66 Web Enabling AS/400 Applications with IBM WebSphere Studio

Follow these steps to build the servlet using the SQL Update statement:

1. Select the DemoCompany project from the Studio Workbench.

2. Start the Database Wizard by selecting Tools->Wizards->Database Wizard.

The Database Wizard window appears as shown in Figure 70.

Figure 70. Studio Database Wizard

3. Complete the following steps:

a. Select the appropriate SQL statement \DemoCompany\UpdateItem.sql.

b. Click Next.

The Web Pages window appears as shown in Figure 71.

Figure 71. Update: Web Page

WebSphere Studio tools 67

4. Complete the following steps:

a. The Web Pages window tab allows you to specify the HTML and JSP filesthat will be generated. You need an input page to collect the data forupdate, an output page to show the result from the query, and an errorpage if something unforeseen happens:

i. Select the input page check box.ii. Select the output page check box.iii. Select the error page check box.

b. Click Next.

The Input Page window appears as shown in Figure 72.

Figure 72. Update: Input Page window

5. Complete the following steps:

a. Click Check All to select all of the check boxes.

b. Move the fields, using the up arrow and down arrow button, to interchangethe order of the columns.

c. Select the parameters by clicking on the row. Click the Change button tochange the caption to a more meaningful name. Repeat this for all theparameters.

d. Deselect the following fields:

• URL• Driver• UserID• password

e. Click Next.

The Results Page window appears as shown in Figure 73.

68 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 73. Update: Result Page window

6. Complete the following steps:

a. Click the Uncheck All button to deselect all of the check boxes.

b. Select the following items:

• Data• ItemNo• Name• Price• SQL Statement

c. Ensure that the Table radio button is selected.

d. Click Next.

The Standard Error Page appears as shown in Figure 74 on page 70.

WebSphere Studio tools 69

Figure 74. Update: Standard Error Page

7. Click Next.

The Methods window appears as shown in Figure 75.

Figure 75. Update: Methods window

8. Click Next.

The Session window appears as shown in Figure 76.

70 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 76. Update: Session window

9. Complete the following steps:

a. Select the Yes, store it in the user’s session radio button so that thegeneration bean will be placed in the session for the user. This makes thebean available for future use.

b. Name the bean, itemupdatebean. Note that this is in lowercase letters, andcase does matter.

c. Click Next.

The Finish window appears as shown in Figure 77.

Figure 77. Update: Finish window

WebSphere Studio tools 71

10.Complete the following steps:

a. Give a meaningful name to the generated source files. Click the Renamebutton and type UpdateItem into the dialog. Click OK. Note that all of thefiles will now have the prefix of UpdateItem.

b. Click the Finish button to generate the code.

You should see the following files added to the DemoCompany project:

• UpdateItemInput.html• UpdateItemResults.jsp• UpdateItemInsertError.jsp

If you look inside the servlet->DemoCompany directory, you will also see thatthe following files have been created:

• UpdateItemDBBean.java• IUpdateItem.java• UpdateItem.servlet• UpdateItem.class• UpdateItemDBBean.class

11.Check all of the generated files in the Studio. Select the DemoCompanyfolder. Using the pop-up menu, select the Check In option. The files arealready checked in if the Check In option is not available from the pop-upmenu.

12.Publish the project to the server. Follow the same steps as described in 3.2.4,“Publishing to the AS/400 system” on page 46.

13.To test the publishing process, select the UpdateItemInput.html file from thepublishing view to preview it. Then, right-click, and select Preview file withNetscape or Internet Explorer.

14.When the Web browser appears, the page appears as shown in Figure 78.Enter values for all the fields, and click the Submit button to execute theupdate.

Figure 78. The input page

The result will be displayed as shown in Figure 79.

72 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 79. The output page

3.2.6.5 Creating an SQL DELETE statementIn this section, we create a SQL DELETE statement to delete a row from the Itemdatabase table. Follow these steps:

1. Select the project folder DemoCompany.

2. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

The Welcome window appears as shown in Figure 80.

Figure 80. Studio SQL Wizard

3. Complete the following steps:

a. Enter DeleteItem as the name of the SQL query. The wizard adds an .sqlfile in your project.

b. Click Next.

The Logon window appears as shown in Figure 81 on page 74.

WebSphere Studio tools 73

Figure 81. Delete: Logon window

4. Complete the following steps:

a. Enter the information that the wizard need to connect to the database, forexample:

• Database URL: jdbc:as400://sysname• Userid: USERID• Password: PASSWORD• Driver: AS/400 Toolbox for Java

Replace sysname with the name of your AS/400 system. Case isimportant for the Userid and Password; both should be in uppercase.

b. Click Connect to connect to the specified database.

c. Click Next.

The Tables window appears as shown in Figure 82.

74 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 82. Delete: Tables window

5. Complete the following steps:

a. Click Delete in the Statement type.

b. Select APILIB.ITEM from the list of tables shown.

c. Click Next.

The Condition 1 window appears as shown in Figure 83.

Figure 83. Delete: Condition window

WebSphere Studio tools 75

6. Complete the following steps:

a. Check if the correct table name is selected in the Selected table(s)drop-down list.

b. Select the Item Id (IID) column from the columns field. This is the conditionon which you want to delete the row from Item table.

c. Select the condition, for example is exactly equal to, from the Operatorlist box.

d. Click in the first value field. Then, click Parameter, and enter ItemID as thename of the parameter.

e. Click Find to see the result of the conditional query.

f. When the Value Lookup for the Item Id dialog appears, enter any valid ItemId in the search field.

g. Click Find Now, and see which row gets deleted from the Item table.

h. Click OK to return to the Condition 1 tab.

i. Click Next.

The SQL Statement window appears as shown in Figure 84.

The SQL tab shows the completed SQL statement. You can copy thestatement to the clipboard to use it in another application.

Figure 84. Delete: SQL statement

7. Click Next.

The Finish window appears as shown in Figure 85.

76 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 85. Delete: Finish window

8. Click Finish.

9. Check in the generated DeleteItem.sql file in the Studio Workbench.

3.2.6.6 Building the servlet using the SQL DELETE statementWe use the Database Wizard to create a servlet, which uses the SQL statementthat we created in the previous section. The Database Wizard helps you createWeb applications that can query, insert, update, and delete relational data. Followthese steps:

1. Start the Database Wizard by selecting Tools->Wizards->Database Wizard.

The Database Wizard window appears as shown in Figure 86.

Figure 86. Database Wizard window

WebSphere Studio tools 77

2. Complete the following steps

a. Select the appropriate SQL statement \DemoCompany\DeleteItem.sql.

b. Click Next.

The Web Pages window appears as shown in Figure 87.

Figure 87. Delete: Web Page window

3. Complete the following steps:

a. The Web Pages window tab allows you to specify the HTML and JSP filesthat will be generated. You need an input page to input the data fordeletion, an output page to show the result from the query, and an errorpage if something unforeseen happens:

i. Check the input page check box.ii. Check the output page check box.iii. Check the error page check box.

b. Click Next.

The Input Page window appears as shown in Figure 88.

Figure 88. Delete: Input Page window

78 Web Enabling AS/400 Applications with IBM WebSphere Studio

4. Complete the following steps:

a. Select the IID (ItemId) check box.

b. Select the IID line by clicking on the row. Click the Change button tochange the caption to a more meaningful name.

c. Click Next.

The Results Page window appears as shown in Figure 89.

Figure 89. Delete: Results Page window

5. Complete the following steps:

a. Select all of the check boxes by clicking the Check All button.

b. Deselect driver and userid options.

c. Change all the captions to more meaningful names.

d. Ensure that the Table radio button is selected.

e. Click the Next button to go to the next tab.

The Standard Error Pages window appears as shown in Figure 90.

Figure 90. Delete: Standard Error Pages window

WebSphere Studio tools 79

6. Click Next.

The Methods window appears as shown in Figure 91.

Figure 91. Delete: Methods window

7. Click Next.

The Session window appears as shown in Figure 92.

Figure 92. Delete: Session window

8. Complete the following steps:

a. Select the Yes, store it in the user’s session radio button so that thegeneration bean will be placed in the session for the user. This makes thebean available for future use.

b. Name the bean deleteitembean. Note that this is in lowercase letters, butcase does matter.

The Finish window appears as shown in Figure 93.

80 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 93. Delete: Finish window

9. Complete the following steps:

a. Give a meaningful name to the generated source files. Click the Renamebutton, and type DemoDeleteItem into the Prefix dialog. Click OK. Note thatall of the files now have the prefix of DemoDeleteItem.

b. Click the Finish button to generate the code.

You should see the following files added to the DemoCompany project:

• DemoDeleteItemInput.html• DemoDeleteItemResults.jsp• DemoDeleteItemError.jsp

If you look inside the servlet->DemoCompany directory, you will also see thatthe following files have been created:

• DemoDeleteItemDBBean.java• DemoDeleteItem.java• DemoDeleteItem.servlet• DemoDeleteItem.class• DemoDeleteItemDBBean.class

10.Check all of the generated files in the Studio. Select the DemoCompanyfolder. Using the pop-up menu, select the Check In option. The files arealready checked in if the Check In option is not available from the pop-upmenu.

11.Publish the project to the server. Follow the same steps as described in 3.2.4,“Publishing to the AS/400 system” on page 46.

12.To test the publishing process, select the DemoDeleteItemInput.html filefrom the publishing view to preview it. Then, right-click, and select Previewfile with Netscape or Internet Explorer.

13.When the Web browser appears, the page appears as shown in Figure 94 onpage 82. Enter a valid Item number that you want to delete from the ITEMtable. Click the Submit button to execute the query.

WebSphere Studio tools 81

Figure 94. The Input page on the browser

The result is displayed as shown in Figure 95.

Figure 95. The Output page on the browser

3.2.6.7 Building a servlet using the JavaBean WizardThe JavaBean Wizard allows you to create servlets that interact with pre-builtJavaBeans. In this section, we create a sample JavaBean using a Studiotemplate. Then, we create a servlet, which uses the JavaBean, with the JavaBeanWizard. Follow this process:

1. Select the DemoCompany project.

2. Select Insert->File. A window appears with various templates for creatingfiles. For example, you can create HTML files, JSP files, JavaBean files, andso on.

3. Select JavaBean.java from the list in the left-hand side of the Insert filewindow. Enter a more meaningful name for the file by entering Sample.java forFile Name. The Insert file window is shown in Figure 96.

82 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 96. Insert File window

4. Click OK to allow the file to be created in the project. Notice that Sample.javafile is now listed in the file view.

5. Double-click on the sample.java file to open it. Change the class name toSample instead of JavaBean.

This bean has some properties defined and setter and getter methods definedfor each of the properties. You see a commented line at the beginning of thefile where you can add your package name if this JavaBean belongs to apackage. The class extends to Java.lang.Object and has such propertiesdefined as address, city, and so on. It has setter and getter methods for eachof these properties. You can add your own code for making databaseconnections and providing your own business logic.

The sample JavaBean has the following properties

• FirstName• LastName• Age• Address• Phone• City• State• Zip

6. Select the Sample.java file. Right-click, and select the Check In option fromthe pop-up menu to check in the file.

7. Select the Sample.java file. Right-click, and select the Compile option fromthe pop-up menu to compile the program. This creates a Sample.class file.

8. Check In the Sample.class file.

9. Select both the Sample.java and Sample.class files, and move them toservlet folder.

We use the JavaBean Wizard to create a servlet that uses the Sample JavaBean.Complete this series of steps:

1. Select the DemoCompany project from the Studio Workbench.

2. Start the JavaBean Wizard by selecting Tools->Wizards->JavaBean Wizard.

WebSphere Studio tools 83

The JavaBean Wizard window appears as shown in Figure 97.

Figure 97. JavaBean Wizard

3. Complete the following steps:

a. Select the appropriate JavaBean \DemoCompany\servlet\Sample.class.

b. Click Next.

The Web Pages window appears as shown in shown in Figure 98.

Figure 98. JavaBean: Web Pages window

4. The Web Page window tab allows you to specify the HTML and JSP files thatwill be generated. You need an input page to collect the data for insertion, anoutput page to show the result of the query, and an error page to displayerrors. Complete the following steps:

a. Check the input page checkbox.b. Check the results page checkbox.c. Check the error page checkbox.

Click Next.

84 Web Enabling AS/400 Applications with IBM WebSphere Studio

The Input Page window appears as shown in Figure 99.

Figure 99. JavaBean: Input Page window

5. Complete the following steps:

a. Click Check All button to select all the check boxes.

b. Click Next.

The Results Page window appears as shown in Figure 100.

Figure 100. JavaBean: Results Page window

6. Complete the following steps:

a. Click Check All button to select all the check boxes.

b. Click Next.

The Standard Error window appears as shown in Figure 101 on page 86.

WebSphere Studio tools 85

Figure 101. JavaBean: Standard Error window

7. Click Next.

The Methods window appears as shown in Figure 102.

Figure 102. JavaBean: Methods window

8. Click Next.

The Session window appears as shown in Figure 103.

86 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 103. JavaBean: Session window

9. Complete the following steps:

a. Select the Yes, store it in the user’s session radio button so that thegeneration bean will be placed in the session for the user. This makes thebean available for future use.

b. Name the bean samplebean. Note that this is in lowercase letters, but casedoes matter.

c. Click Next.

The Finish window appears as shown in Figure 104.

Figure 104. JavaBean: Finish window

10.Complete the following steps:

a. Give a meaningful name to the generated source files. Click the Renamebutton. Type DemoSampleBean into the Prefix dialog.

b. Click OK. Note that all of the files now have the prefix ofDemoSampleBean.

WebSphere Studio tools 87

c. Click Finish to generate the code.

You see the following files added to the DemoCompany project:

• DemoSampleBeanInput.html• DemoSampleBeanResults.jsp• DemoSampleBeanError.jsp

If you look inside the servlet->DemoCompany directory, you also see that thefollowing files have been created:

• DemoSampleBean.java• DemoSampleBean.servlet• DemoSampleBean.class

The servlet configuration file is where the servlet finds the initial parameters touse. The initial parameters include the user ID, password, and the JDBCdriver to use. The servlet configuration file has an extension of .servlet.

11.Check all of the generated files into Studio. Select the DemoCompany folder.Right-click, and select the Check In option. The files are already checked in ifthe Check In option is not available from the pop-up menu.

12.Publish the project to the server. Follow the same steps as described in 3.2.4,“Publishing to the AS/400 system” on page 46.

13.To test the publishing process, select the DemoSampleBeanInput.html filefrom the publishing view to preview it. Right-click, and select Preview file withNetscape or Internet Explorer.

14.When the Web browser appears, enter the values for all the fields, and clickSubmit. This shows the output page with the values of all the fields.

3.3 Page Designer

With Page Designer, you can build complex Web pages, both visually andtextually. Page Designer provides an advanced HTML editor that allows you tobuild dynamic content including form elements, Java applets, embedded scripts,dynamic controls, and JSP tags. Page Designer includes its own library ofreusable graphics and two companion graphic programs, WebArt Designer andAnimatedGif Designer, that create, edit, and animate image files.

3.3.1 Using WebArt Designer and AnimatedGif Designer to add enhanced graphicsIn this section, we use WebArt Designer and AnimatedGif Designer to creategraphics for use in Web pages. WebArt Designer helps you create GIF and JPGfiles. It comes with sample artwork, which you can modify or combine to createcustom graphics. AnimatedGif Designer provides tools for creating animationfrom graphics files. You can combine the tools to create interesting animatedgraphics.

3.3.1.1 Registering the AnimatedGif Designer toolTo register the AnimationGif Designer tool as the default program to run for GIFfiles, perform the following steps:

1. Select Tools->Tools Registration. The Tools Registration window appears asshown in Figure 105.

88 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 105. Studio Workbench: Tools Registration window

2. Type gif for File extension, and click the Edit button. The Edit object typewindow appears with the MIME type tab selected as shown in Figure 106.

Figure 106. Tools Registration: Edit Object Type window

3. Select the Editing Application tab. Then, select Animated Gif Designerfrom the left-hand list.

4. Click the Add-> button to add it to the right-hand list.

5. Remove any other registered tools by selecting them, and then click theRemove-> button. At this point, the Edit object type window appears as shownin Figure 107 on page 90.

WebSphere Studio tools 89

Figure 107. Tools Registration: Edit Object Type window

6. Click OK and then the Close button to close the window.

3.3.1.2 Registering the WebArt Designer toolTo register the WebArt Designer tool as the default program to produce GIF files,perform the following steps:

1. Select Tools->Tools Registration. The Tools Registration window appears asshown in Figure 108.

Figure 108. Studio Workbench: Tools Registration window

2. Type mif for File extension and click the Edit button. The Edit object typewindow appears with the MIME type tab selected.

3. Select the Editing Application tab, and then select Web Art Designer fromthe left-hand list.

4. Click the Add-> button to add it to the right-hand list.

90 Web Enabling AS/400 Applications with IBM WebSphere Studio

5. Remove any other tools registered by selecting them. Then click theRemove-> button. At this point, the Edit object type window appears as shownin Figure 109.

Figure 109. Tools Registration: Edit Object Type window

6. Click OK and then the Close button to close the window.

3.3.1.3 Creating the banner and logo buttonsWe create a banner and logo buttons for ABC Company using WebArt Designer.They are used as the base gif files for the design of the site discussed in Chapter7, “ABC Company Web site design and development” on page 157. Follow thesesteps:

1. Start WebSphere Studio if it is not already started.

2. Open the DemoCompany project.

3. Create a folder named Images under the DemoCompany project. Right-clickon DemoCompany, and select Insert->folder from the pop-up menu. Then,enter Images as the folder name.

4. Select the Images folder, and then select Insert->File. When the dialogappears, select WebArtDesigner.mif as the file type. Enter banner.mif as thefile name (Figure 110 on page 92).

WebSphere Studio tools 91

Figure 110. Insert File window

5. Click OK to cause the banner.mif file to be created in the images folder.

6. Open the new banner.mif file in the WebArt Designer.

a. Select banner.mif.

b. Right-click, and select Edit with->WebArt Designer.

The WebArt Designer opens with a canvas.

Note that the left-hand side of the WebArt Designer is a tabbed frame,which allows you to select existing graphics and drag them to the canvas.

7. Create the banner.gif file, which is used as the banner for the ABC Companysite:

a. From the WebArt Designer, modify the size of the canvas by selectingFile->Preferences->Display Tab. Enter a width of 250 and a height of 150.Click on the WebSphere logo and press the Delete key to delete it. Changethe color by selecting the Background tab on the left side of WebArtDesigner and dragging the white square onto the canvas.

b. Select the Button tab from the left-hand bottom corner. Drag the circle09button to the left top corner of the canvas. Right-click on the button, andselect Properties from the pop-up menu. Enter a width of 89 and height of89 so that the circle resizes to 89 x 89.

c. Double-click on the circle button on the canvas. The Edit Button Objectwindow appears. Select the Color tab. Select Plain Color for Group andBlue for Type. Close the Edit Button Object window.

d. Click the Logo tab on the left-hand, bottom corner of the page. Drag theengrave logo to the canvas so that it is on top of the circle.

e. Double-click on the engrave logo so that the Edit Logo Object windowappears with the Text and Font tab selected. Enter ABC Company for Text, set56 for Font Size, Anti-alias for Style, and Left for alignment. Select theColor tab. Set Plain Color for Group and Yellow for Type. Click theOutline tab, and select Normal for Type. Click the Logo Effect tab, andselect Cut Out for Type. The window at this point appears as shown inFigure 111.

92 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 111. WebArtDesigner: The ABC Company banner

f. Select File->Save Wizard. Select the Object Only radio button, and thenclick Next. Select GIF as the image file format. Click Next, and then clickFinish. Navigate to the Image folder in your workstation, and save the fileas banner.gif. With GIF files, you can specify transparency as the part ofimage, where with JPEG, you cannot specify transparency.

Note: Ensure that no object on the canvas is selected before you save thewizard.

g. Close the WebArt Designer, and save the banner.mif file.

8. Create the buttons for navigation. Follow step 4 to create a general.mif file.

9. Right-click on the general.mif file to edit it with WebArt Designer:

a. From the WebArt Designer, modify the size of the canvas by selectingFile->Preferences->Display Tab. Enter a width of 250 and a height of 150.Delete the WebSphere logo by clicking on it and press the Delete key.Change the color by selecting the Background tab on the left side ofWebArt Designer and dragging the white square onto the canvas.

b. Select the Button tab from the left-hand, bottom corner, and drag thecircle09 button to the left top corner of the canvas. Right-click on thebutton, and select properties from the pop-up menu. Enter a width of 29and height as 29 so that the circle resizes to 29 x 29.

c. Double-click on the circle button on the canvas. The Edit Button Objectwindow appears. Select the Color tab. Select Plain Color for Group andBlue for Type. Close the Edit Button Object window.

d. Click the Logo tab on the left-hand, bottom corner of the page. Drag theengrave logo to the canvas so that it is on top of the circle.

e. Double-click on the engrave logo so that the Edit Logo Object windowappears with the Text and Font tab selected. Enter About Us for Text. Setthe Font Size to 30, Style to Anti-alias, and Alignment to Left. Select theColor tab, and set Plain Color for Group and Yellow for Type. Click theOutline tab, and select Normal for Type. Click the Logo Effect tab, andselect Emboss for Type. The window, at this point, appears as shown inFigure 111.

f. Select File->Save Wizard. Select the Object Only radio button, and thenclick the Next button. Click GIF as the image file format. Click Next, andthen click Finish. Navigate to the Image folder in your workstation andsave the file as aboutus.gif. With GIF files, you can specify transparency asthe part of image, where with JPEG, you cannot specify transparency.

WebSphere Studio tools 93

10.While in the WebArt Designer, double-click on the text object in the rightpalette. Select the Text and Font tab from the window and replace the textwith About Site.

This way, you ensure that the alignment is not disturbed and the size and colorare consistent for all the buttons.

11.Select File->Save Wizard. Select the Object Only radio button, and then clickthe Next button. Click GIF as the select image file format. Click the Nextbutton, and then click Finish. Navigate to the Image folder in your workstation,and save the file as aboutsite.gif.

12.Repeat steps 10 and 11 to create buttons for the main page and the generateuser page. Name them welcome.gif and generate.gif.

13.Close WebArt Designer, and save general.mif for further use.

You can use this procedure to create as many buttons you need for the site.

3.3.1.4 Creating animated imagesYou can create an animated GIF, which involves creating several graphics andthen combining them together in an animation object. It is a redbook image thatspins continuously. Follow these steps to create the redbook animated image:

1. Select the Images folder, and then select Insert->File. When the dialogappears, select WebArtDesigner.mif as the type of file. Enter book.mif as thename of the file.

2. Click the OK button to cause the book.mif file to be created in the Imagesfolder.

3. Right-click on the book.mif file to edit it with WebArt Designer.

4. From the WebArt Designer, modify the size of the canvas by selectingFile->Preferences->Display Tab. Enter a width of 250 and a height of 150.Delete the WebSphere logo by clicking on it and pressing the Delete key.Change the color by selecting the Background tab on the left side of WebArtDesigner and dragging the white square onto the canvas.

5. Drop an image of a book onto the canvas. Select the other tab in theleft-hand, bottom corner, and navigate to the \WebSphere\Studio\iconsdirectory. Select the book.gif image. Drag the image to the canvas, and placeit in the center of the canvas.

6. To make the image look like a redbook, you need the redlogo.gif file, which isavailable from the SG245634.EXE self-extracting file (refer to Appendix A,“Example programs” on page 405, for more information). If you downloaded it,place it in the \DemoCompany\images folder.

7. Right-click on the book on the canvas, and select properties. Set the width to94 and the height to 81. Click on the other tab from the left-hand, bottomcorner, and navigate to the \DemoCompany\images folder. Drag theredlogo.gif file to the canvas to place it on top of the book. Resize theredlogo.gif image to fit the book so that it looks like a redbook.

8. Select both the objects by using the Shift key. Then, select Object->Combine.This combines both objects into one. The image at this point appears asshown in Figure 112.

94 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 112. The redbook image

9. Create the remaining graphics for the animation. You need to add effects tomake it look like the redbook is spinning. In this process, you create a numberof GIF files that together can create an animation effect. Complete thesetasks:

a. With the redbook selected, select Tool->Effect to open the Effects Palettewindow.

b. Click the Preview button. All of the available effects are applied to theredbook and shown in the Effects Palette window (Figure 113).

Figure 113. WebArt Designer: Effects Palette window

c. While in the Effects Palette window, select the Turbulence icon, and clickApply. Notice that the image changes. Click on the WebArt Designerwindow.

WebSphere Studio tools 95

d. Click File->Save Wizard, select Object Only, and click Next. Select GIFas the image file format. Click Next, and then click Finish. Navigate to the\DemoCompany\Image folder in your workstation, and save the file asbook11.gif.

e. Select Edit->Undo to get the original image of the redbook.

f. Repeat these steps to create more images. Select the Effect type and thename as shown in Table 1.

Table 1. Effect types and file names

g. Close the WebArt Designer window.

h. From the Studio Workbench, check in all the files.

10.Use WebSphere AnimationGif Designer to put all the graphics createdtogether into an animation.

a. From the Studio Workbench, select the images folder. Create a newanimation file by selecting Insert->File. When the dialog appears, select afile type of Animation.gif, and name the file as book.gif.

b. Click the OK button. When prompted to check out the file, click the CheckOut button.

c. To edit with AnimationGif Designer, select Edit with->AnimationGifDesigner.

d. When the AnimationGif Designer opens, select File->Animation Wizard.

e. When the wizard starts, click the Add Image File button. When the openfile dialog appears, select the following files in order, and click the Openbutton:

• \DemoCompany\images\book11.gif• \DemoCompany\images\book12.gif• \DemoCompany\images\book13.gif• \DemoCompany\images\book14.gif• \DemoCompany\images\book15.gif• \DemoCompany\images\book16.gif• \DemoCompany\images\book17.gif• \DemoCompany\images\book18.gif• \DemoCompany\images\book19.gif• \DemoCompany\images\book19.gif• \DemoCompany\images\book19.gif• \DemoCompany\images\book19.gif

Effect type File name

Vortex book12.gif

Mirage book13.gif

Bubble book14.gif

Flat book15.gif

Mosaic book16.gif

Blur book17.gif

Tile book18.gif

Sharp book19.gif

96 Web Enabling AS/400 Applications with IBM WebSphere Studio

f. Notice that book19.gif was used multiple times. This is to make theanimation sequence more realistic. Click the Next button.

g. Specify that the frame center should be put on middle center, and clickNext.

h. Specify that the animation should be set to an Infinite number of repeats,and the delay is 200 msec. Click the Next button.

i. On the Finish panel, click the Play button and preview the animation. TheAnimatedGif Designer, at this point, appears as shown in Figure 114.

Figure 114. AnimatedGif Designer: Redbook animation

j. If everything looks good, click Finish.

k. Save the animation as a bookani.gif animation file by selecting File->SaveAs.

l. Close the AnimatedGif Designer window.

11.To add the bookani.gif file to the Studio Workbench publishing stage, followthese steps:

a. Select the Images folder.

b. Right-click, and select Insert->File.

c. Select the Use Existing tab.

d. Locate bookani.gif in the \DemoCompany\images folder, and click the OKbutton.

e. Check in all the files.

3.3.2 Constructing the Logon pageIn order for users to navigate and shop at the ABC Company Web site, usersneed to be a registered member of this site. The Logon page takes the user IDand password as input from the user and verifies whether the user is registered inthe database. If the userid and password are valid, the user is allowed to navigateand shop at the ABC Company Web site.

WebSphere Studio tools 97

In this section, we build the front end for the Logon page, which will be offered tothe user over the Internet. Later in Chapter 8, “Creating the complete ABCCompany Web site” on page 361, we build a servlet, which provides the back-endfunctionality of validating the userid and password. As you go through thissection, refer to Figure 118 on page 102 as a guide for the completed page:

1. Add a new folder named ABC_Company to the DemoCompany project.

2. Create the Logon page, and call it Logon.html.

a. From the Files view of the Studio workbench, select the ABC_Companyfolder, and then select the Insert->File menu option. A dialog displayingmany types of files which can be added to a WebSphere Studio projectappears. Select the Blank.html file on the left, and then supply a file nameof Logon.html. The Insert File window appears as shown in Figure 115.

Figure 115. Studio: Login page creation

b. Click the OK button. Then, the file Logon.html is created and added to theStudio Workbench.

3. Double-click the file to open it. When the file opens, the Normal mode tab ofthe Page Designer is selected. Delete the Put your text here sentence.

4. Change the Document Title to Logon Page by selecting the DocumentProperties menu option from the pop-up menu. Since Document Properties isthe top-level object for everything in the Normal view of Page Designer, themouse can be positioned over any object in the page.

5. Click OK to close the Attributes dialog window.

6. Add the banner to the page. Our banner is banner.gif, which we created in3.3.1, “Using WebArt Designer and AnimatedGif Designer to add enhancedgraphics” on page 88.

a. To ensure that the images and text that you place on the Logon.html pagehave the same layout at display time that they have at edit time, you mustuse tables for placing the items.

b. Insert a Table containing two columns and two rows at the top of the page.Select Insert->Table. A dialog is displayed requesting the number ofcolumns and rows. Enter 2 for the columns and 2 for the number of rows.Close the Insert Table dialog by clicking OK.

98 Web Enabling AS/400 Applications with IBM WebSphere Studio

c. A 2 X 2 table will be added to the page and has borders. Remove theborders by changing the table attributes. Select the table. Right-click, andselect Attributes to view the Attributes dialog. A dialog showing the tableattributes appears. Select the Table tab. Deselect the Show Border checkbox. Enter 0 for Cell Spacing and Cell Padding, which leaves no roombetween the cells. The table attribute window should look like the exampleshown in Figure 116. Click OK to save the new settings.

Figure 116. Page designer table attributes

d. Select the top row of the table so that the cursor is inside the top row andsecond column. Then, select Insert->Image. Add the\DemoCompany\images\banner.gif file to the table. Notice that the tableexpands to accommodate the image.

7. Select the top row of the table so that the cursor is inside the top row and thefirst column. Then, select Insert->Image. Add the\DemoCompany\images\bookani.gif file to the table.

8. Add a column of buttons for navigation purposes:

a. Add a table inside the first table. Do this by placing the cursor in the secondrow first column of the table.

b. Add another table by selecting Insert->Table. When the dialog appears,specify 4 rows and 1 column. We place four images in this table to functionas a button bar. Close the Insert Table dialog by clicking OK.

c. Modify the table attribute for the new table. Select the new table, and thenopen the Attribute dialog by double-clicking on the table. Select the Tabletab, and then de-select the Show Border check box. Enter 0 for CellSpacing and Cell Padding as this leaves no room between the images.Click OK to save the new settings. The Logon page appears as shown inFigure 117 on page 100.

WebSphere Studio tools 99

Figure 117. Inserting a table inside the outer table

9. To add the images, place the mouse cursor inside of a cell in the inner table,and then select Insert->Image to add the images. Add the About Us button tothe inner table. This involves adding an image and a link:

a. With the first cell in the inner table selected, select Insert->Image to openthe Insert Image dialog and the File Selection dialog simultaneously.

b. Navigate to the \DemoCompany\images\aboutus.gif file, and click theOpen button. The File Selection dialog and the Insert Image dialog willclose.

c. Add a link by selecting the Insert Link option from the Image pop-up menu.At this point, you do not actually add the link. That is discussed in Chapter8, “Creating the complete ABC Company Web site” on page 361. Click theCancel button to close the Attributes dialog window.

d. Add the remaining buttons to the inner table by following the instructionsused to add the About Us button. Assume that all of the files are in thedirectory \DemoCompany\images.

The images to add to the Logon page are:

• aboutsite.gif• generate.gif• welcome.gif

10.Create an HTML form in the second column, second row of the outer table.This form contains the necessary items for the user to enter the user ID andpassword to log in and navigate the site. The form contains a table with labels,entry fields, and buttons.

a. You need to add a form inside the outer table. Place your cursor in thesecond row in the second column of the table.

100 Web Enabling AS/400 Applications with IBM WebSphere Studio

b. Select Insert->Form and Input Fields->Form to add a form to theselected cell of the outer table.

c. Click on any point inside the form and add another table. This table servesas the layout mechanism for the Form field. Add the table by clickingInsert->Table. Make this table with 3 columns and 2 rows.

d. Since this table is for layout purposes, you want it to be invisible or hiddento the Web user. Select the table, right-click, and select Hide Table Framefrom the pop-up menu.

e. With the inner table still selected, open the attributes dialog by selectingthe Attributes option from the pop-up menu. Select the Table tab, andthen set the alignment to Center. Click the OK button to save the newsettings.

f. Make the table larger by grabbing one of the corners and stretching ithorizontally.

g. Add the userid label and text fields:

i. Select the top, left-most cell, and type Userid in the cell. SelectFormat->Physical Emphasis->Font. Enter a size of +1, a color ofBlack, and a Face of Arial. Click OK to close the dialog.

ii. With userid still selected, select Format->Physical->Emphasis->Bold.

iii. Press the Tab key twice to select the right-most cell in the same row.Leave the middle cell empty to have a space between the label and thetext field. Enter an input field by selecting Insert->Form and InputFields->Text Field. The Attributes dialog opens on the Text Field tag.Enter userid as the name of this field. Set both the Columns andMaximum Length to 20. Click OK to close the Attributes dialog.

h. Add the password label and the Text field for password. Use the samesteps as above.

11.Add another table below the table used for the user ID and password:

a. Add a table of 2 rows and 3 columns to hold the buttons. Leave the first rowand second column empty to have a gap in between, and use the secondrow to insert the buttons.

b. Since this table is for layout purposes, you want it to be invisible or hiddento the Web user. Select the table, right-click, and select Hide Table Framefrom the pop-up menu.

c. Add a Submit button by selecting the second row in the first column of thetable. Select Insert->Form and Input Fields->Push Button->SubmitButton. When the Attributes dialog opens on the Push button tag, enter aName of submit, a Label of Submit, and Button Type of Submit. Click OK tosave the settings.

d. Add a Reset button by selecting the second row in the third column of thetable. Select Insert->Form and Input Fields->Push Button->ResetButton. When the Attributes dialog opens on the Push button tag, enter aName of reset, a Label of Reset, and Button Type of Reset. Click OK to savethe settings.

Figure 118 on page 102 shows the completed Logon page.

WebSphere Studio tools 101

Figure 118. Page Designer: Viewing the final Logon page

12.Close the Page Designer, and respond “Yes” to the dialogs requesting that yousave the files.

13.Use the Check In menu to check the Logon.html file into the StudioWorkbench.

3.3.3 Creating a page templateOne of the interesting features of WebSphere Studio is that we can create a fileusing the existing templates within the WebSphere Studio. Also, WebSphereStudio allows you to add a custom design template to the list of templates andreuse this template in the future. Normally, while building a Web site, a developerwould want a site template in place so that it becomes easier for reusing thetemplate. The template created in this section is used as the base template forbuilding the ABC Company Web site. Follow these steps:

1. Double-click the Logon.html file (created in 3.3.2, “Constructing the Logonpage” on page 97) to open it in Page Designer.

2. Select the content of the second row in the second column of the outer mosttable. This has the field to enter the password. Press the Delete key to deletethe content of the cell.

3. Make sure that the cell, second row, and second column of the outer table areempty. The page appears as shown in Figure 119.

102 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 119. Page Designer: Creating a page template

4. Select File->Save As. The Save As dialog appears, which prompts you for thefile name. Enter SiteTemplate.html as the name. Click the Save button to savethe file.

5. From the Studio Workbench, select SiteTemplate.html, and check in the file.

6. Open Windows Explorer, and navigate to find the SiteTemplate.html file.Right-click, and select Copy from the pop-up menu. Navigate to the\WebSphere\Studio\templates folder and paste the SiteTemplate.html file intoit.

7. Go back to the Studio Workbench. Select Insert->File, and the Insert Filewindow appears. You should now be able to view the SiteTemplate.html as oneof the templates in the list. Select it, and enter a meaningful name. Click OK toadd the file to the WebSphere Studio project.

8. Open the file by double-clicking on it. Make sure that the file template is theone you created.

3.3.4 Working with style sheetsStyle sheets are a way for publishing professionals to manage the overall look oftheir publications. They control the background, colors, fonts, and all elements ofstyle that publishing professionals want to reuse for a large set of documents.Web publishing professionals have the same needs and, as such, can use aconcept know as cascading style sheets. There are three ways to attach a style toa tag: inline, document-level, and external style sheets. Each of these types ofstyle is merged by the browser, giving the ability to have a master style sheet(external), which is used for an entire Web site while still allowing each specificpage to override style elements locally. Style sheets are somewhat new, so not allversions of Web browsers fully support them. Follow these steps:

WebSphere Studio tools 103

1. Open the DemoCompany project if it is not already open.

2. Look at how the style sheets are being used:

a. The master style sheet can be found in the theme directory and is calledMaster.css.

b. In the Studio Workbench file view, select the Master.css file. You will see inthe relations view that Master.css is related to all the files under thisproject. This means all the files in this project use the Master style sheet.

c. Double-click the Logon.html page to open it in Page Designer.

d. To see the style of this page, select View->Style Sheet Manager fromPage Designer.

e. The style manager dialog opens with the Show the style list buttonselected. From this dialog, you can add, delete, and edit document styles.Additionally, from this dialog, you can drill down on external style sheetsand then add, delete, and edit elements of style in the external style sheet.The style sheet window appears as shown in Figure 120.

Figure 120. Page Designer: Style Sheet Manager status

f. To see how various styles are used in this page, select the Show currentstyle status button at the top of the window. Selecting this button shows allthe types of tags found in the document. Then, it shows which tag isactually being used. This is valuable for many reasons. If you have morethan one style for a tag, the current style status view shows which style isactually being used for the tag.

3. You want all the H1 tags for the entire site to have a color of Red. This styleneeds to be placed in the Master.css external style sheet so that all pages canuse the external style sheet and have H1 tags in the color of Red.

a. While still in Style Sheet Manager dialog window, select the Show thestyle list->Master.css. Click the Edit button. The External Style Sheetdialog window appears as shown in Figure 121.

104 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 121. Page Designer: External Style Sheet

b. Add a new style to this external style sheet. Select Add->Create, and clickthe Add The Style button. The Style Definition dialog appears.

c. Ensure that the Set the style to the HTML tag is selected. We want thisstyle to apply for all H1 tags.

d. Change the HTML tag List to H1 by selecting it from the drop-down list.

e. Select the Color and Background tab, and then select red from thedrop-down list of colors.

f. Click OK to close the Style Definition dialog. Then, click OK to close theExternal Style Sheet dialog.

g. From the Studio Workbench, double-click on the Logon.html page to openit. Select some text on the page. Assign it an H1 tag by selectingInsert->Paragraph->H1. Notice that the text changes color to red.

4. In the previous step, you changed the Master.css by opening an HTMLdocument that used the Master.css file. Here, we edit the Master.css filedirectly:

a. The master style sheet is found in the theme directory and is calledMaster.css.

b. In the Studio Workbench file view, double-click on the Master.css file toopen it in the Page Designer. Upon opening this file, notice that the PageDesigner opens the External Style Sheet dialog.

c. Change the background to a bitmap. To do this, select the <BODY> tag,and then click the Edit button. The Style Definition dialog appears.

d. Select the Color and Background tag. From this tab, click the Browsebutton beside the Background Image label and navigate to the\DemoCompany\images\ directory. Select one of the GIF files, and clickOpen.

e. Click OK twice to return to Studio Workbench.

WebSphere Studio tools 105

f. From the Studio Workbench, open the Logon.html page. Notice that thebackground now contains a pattern of the GIF file you chose.

3.3.5 Using Page Designer with JavaBeansWe use the facilities provided by WebSphere Studio Page Designer to createdynamic pages that interact with servlets created by the Studio Wizards. We usethe JavaBean and the servlet created in 3.2.6.7, “Building a servlet using theJavaBean Wizard” on page 82. To do this, we use the wizlet function ofWebSphere Studio, as demonstrated in the following steps:

1. Create a new HTML page using the page template you created. Follow thesesteps:

a. With the ABC_Company folder highlighted, select the Insert->File menuoption. When the Insert File dialog appears, select SiteTemplate.htmlfrom the list, and enter DemoBean.html as the file name.

b. Click OK to add the file to Studio Workbench.

2. Double-click the DemoBean.html page in Page Designer to open it.

3. With the Page Designer open, go to the Studio Workbench. Select theSample.class JavaBean that was generated in 3.2.6.7, “Building a servletusing the JavaBean Wizard” on page 82.

4. Right-click on the Sample.class file. From the pop-up menu, select Copy asHTML Script. A dialog appears that looks much like the Database Wizard.This is a wizlet, which allows you to generate an Input or Results page from aJavaBean. Select the Input Page radio button. The wizlet window looks likethe example in Figure 122.

Figure 122. Wizlet window

Make sure that you select the JavaBean and not the servlet to drop on thepage. In 3.2.6.7, “Building a servlet using the JavaBean Wizard” on page82, the JavaBean is Sample.class.

Note

106 Web Enabling AS/400 Applications with IBM WebSphere Studio

5. Click Next to go to the next window in the wizlet. On this window, you mustselect the fields that you want to be displayed on the input page. Click CheckAll to select all the fields. Select each row and click Change to change thecaption of each field to a meaningful name. Use the Up and Down arrows ifyou want to reorganize the order of fields.

6. Click Next. The next window shows the generated HTML. Click Finish to copythe contents of the panel to the copy and paste buffer. At this point, the dialogcloses and you return to the Studio Workbench. The HTML is in your copy andpaste buffer.

7. Return to the Page Designer window to edit the DemoBean.html file. Placeyour mouse cursor in the empty cell of the table, in the second row andsecond column of the outer table. Select Edit->Paste. A form is then paintedon the page. The DemoBean.html page now appears as shown in Figure 123.

Figure 123. Page Designer: Page created using a JavaBean Wizlet

8. In the Studio Workbench, select the servletservlets/DemoCompany/DemoSampleBean.servlet. Right-click on this file.From the pop-up menu, select Copy as URL Text to copy the servlet URL intothe copy and paste buffer.

9. In Page Designer, select the form and open the Attributes dialog bydouble-clicking on the form. Use the drop-down list to select the Form tag.Change the action to call the generated servlet by pasting the name into theaction field. As shown in Figure 124 on page 108, the action should be/servlet/DemoCompany.DemoSampleBean. Ensure that the Method radiobutton is set to POST.

WebSphere Studio tools 107

Figure 124. Form Attribute window

10.Click OK to save your settings.

11.Close the Page Designer window, and save your work.

12.From the Studio Workbench, check in the DemoBean.htm file.

13.Publish the DemoBean.html file. Refer to 3.2.4, “Publishing to the AS/400system” on page 46, if you still need help for the publishing task.

14.To test the publishing process, select the DemoBean.html file from thepublishing view, right-click, and select Preview file with Netscape or InternetExplorer. When the Web browser appears, the input page appears as shownin Figure 125.

108 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 125. Page Designer: Using a JavaBean in a Web page

In this section, we demonstrated how to use a JavaBean in a Web page. In ourcase, the JavaBean did not have any business logic. Chapter 8, “Creating thecomplete ABC Company Web site” on page 361, shows you how to add logic toyour JavaBeans.

3.3.6 Modifying the Studio Wizards generated result pageThe output page generated by the Studio Wizards appear in a simple format. Thegenerated page can be updated for added functionality. For example, you couldadd a column for calculating totals. Here, we modify the Studio Wizardsgenerated results page to enhance the overall look of the output page. In thisexample, we use the Studio Wizards generated output file from 3.2.2.2, “Buildingthe servlet using the SQL SELECT statement” on page 39. We add a banner tothe output page. Here are the steps for this process:

1. In Page Designer, open the ItemSearchInput.html file generated in 3.2.2.2,“Building the servlet using the SQL SELECT statement” on page 39. TheStudio Wizards generated input file is shown in Figure 126 on page 110.

WebSphere Studio tools 109

Figure 126. Page Designer: Studio Wizard generated input file

2. Place the cursor on the top of the output page.

3. To ensure that the banner image and the content of the input file have thesame layout at display time that it has at edit time, use tables for placing theitems:

a. Insert a table containing one column and one row at the top of the page byselecting Insert->Table. A dialog is displayed that requests the number ofcolumns and rows. Enter 1 for the column and 1 for the number of rows.

b. A one column by one row table is added to the page, which also hasborders. Remove the borders by changing the table attributes. Select thetable. Right-click, and select Attributes to open the Attributes dialog. Adialog showing the table attributes appears. Select the Table tab and thende-select the Show Border check box. Enter 0 for Cell Spacing and CellPadding. This leaves no room between the images.

c. Click OK to save the settings.

4. Add the banner image to the cell in the table. Select the cell of the table sothat the cursor is inside the cell. Then, select Insert->Image. Add the\DemoCompany\images\banner.gif file to the table. Notice that the tableexpands to accommodate the image.

5. Resize the width of the cell to that of the input page content. Right-click in thetable cell and select Attributes. Then, enter the appropriate cell width toresize the cell to the width of the output page. The modified output page at thispoint appears as shown in Figure 127.

110 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 127. Page Designer: The modified input page

6. Close the Page Designer window, and save your work.

7. From the Studio Workbench, check in the ItemSearchInput.html file.

8. Publish the ItemSearchInput.html file. Refer to 3.2.4, “Publishing to theAS/400 system” on page 46, if you still need help for the publishing task.

9. To test the publishing process, select the ItemSearchInput.html file from thepublishing view. Right-click, and select Preview file with Netscape or InternetExplorer. When the Web browser appears, the input page appears as in Figure128.

Figure 128. Page Designer: The final modified input page

WebSphere Studio tools 111

3.4 Applet Designer

Applet Designer allows you to visually construct Java applets. You drag and dropJavaBeans from a palette onto a canvas to construct applets. Applet Designerincludes a number of JavaBeans that you access from the palette. You can alsoadd your own JavaBeans to the palette. The JavaBeans included with the AppletDesigner include user interface controls such as buttons and check boxes;multimedia beans for adding images, audio, roll-overs, ticker tapes and othereffects to your applet; and networking beans for e-mail, database, and Webaccess in your applet.

3.4.1 Creating an applet with Applet Designer

In this section, we build an applet that displays the animated redbook. It has startand stop buttons, which causes the book to spin and stop spinning respectively.To create the applet, follow these steps:

1. Open the DemoCompany project if it is not already open.

2. From the Studio Workbench, create a new folder to hold the files created byApplet Designer. Select the DemoCompany folder, and then selectInsert->Folder. When the dialog appears, enter the new folder name asAppletDesigner. Click OK to close the dialog and create the folder.

3. Select the AppletDesigner folder, and create a new Applet Designer file byselecting Insert->File. From the dialog, select a file type ofAppletDesigner.app, and enter a name of WebSphereNJava.app. WebSphereStudio creates the file and places it in the AppletDesigner folder.

4. Open the AppletDesigner folder, and double-click on theWebSphereNJava.app file to start the Applet Designer. When AppletDesigner opens, the New Applet Wizard also opens. The New Applet Wizardwindow appears as shown in Figure 129.

This section uses the animated redbook file created in 3.3.1.4, “Creatinganimated images” on page 94. It is named bookani.gif. You, too, can use theanimated book object, which is available from the self-extracting fileSG245634.exe file called book.gif.

Refer to Appendix A, “Example programs” on page 405, for more informationon how to download the SG245634.exe self extracting file from the ITSO Website.

Animated redbook file

112 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 129. Applet Designer: Applet Wizard

5. Click Next to bypass the Welcome Page. Deselect the check box if you do notwant the wizard to automatically start next time.

6. On the Animation page, select the Yes, please, and Medium (for the speed)radio buttons, and click Find.

7. Select the \DemoCompany\images\bookani.gif file. Click Open to select thefirst image in the animation. Figure 130 shows the current wizard view.

Figure 130. Applet Designer: Previewing the animation

8. Click Preview to see how the animation is going to look before placing it onthe applet.

9. Click Finish to generate the animation.

10.As shown in Figure 131, you see a white area (Applet1) and a red color book.

WebSphere Studio tools 113

Figure 131. Applet Designer: The generated animation

11.Click the book, and set the Autostart property to No in the Properties window.

12.Select and resize Applet1 to provide enough space to place other beans.Center the book image in the top part of the applet:

a. The applet resizes itself if you drop controls on it. You can also selectLayout->Set To Preferred Size, which sizes a control to its preferred sizeif it has one.

b. If you cannot select Applet1 by clicking on the white area, click SelectedBean drop-down list at the top of the Composer window, and selectApplet1 from the list of beans.

13.In the left-hand frame (from the Palette frame), select the Controls tab, andclick on the Button icon.

14.Place two buttons, to the left and right of the book, on Applet1. These buttonswill serve as the Start and Stop buttons for the animation. Refer Figure 132 onpage 116 as a guide.

15.Select both buttons and align them horizontally (press the Shift key andleft-click to select multiples; select Layout->Align->Middle to align). If youselect the Undo menu option, the alignment will be undone.

16.Select Button1. In the Properties frame, change the Label to Start.Additionally, change Name to StartPB.

17.Select Button2. In the Properties frame, change the Label to Stop.Additionally, change Name to StopPB.

114 Web Enabling AS/400 Applications with IBM WebSphere Studio

18.When the Start button is pressed, you want the animation to begin. To do this,you need to establish a connection that will fire when the Start button isclicked.

a. Click the Start button. Then, click in the first cell of the Connection frame atthe bottom.

b. For each element in the table, select a provided value from the drop-downlist. Even if the value you want automatically appears in the cell, you mustclick the drop-down button, and select it again. For each column, select thefollowing options:

• When -> clicked• Bean -> Animation1• Do -> start

c. Ensure that when you are finished, the connection is not red. Incompleteconnections are in the color red.

19.When the Stop button is clicked, you want the animation to end. To do this,you need to establish a connection that will fire when the Stop button isclicked.

a. Click the Stop button. Then, click in the first cell of the Connections frame.

b. For each element in the table, select a provided value from the drop-downlist. Even if the value you want automatically appears in the cell, you mustclick the drop-down button, and select it again. For each column, select thefollowing options:

• When -> clicked• Bean -> Animation1• Do -> stop

c. Ensure that when you are finished, the connection is not red. Incompleteconnections are in the color red.

At this point, the Applet Designer window looks similar to Figure 132 on page116.

It is also a good idea to give more meaningful names to beans. Meaningfulnames make it is easier to create correct connections. If you ever need tocreate a new Java method on your applet, it will be much easier to code withmeaningful bean names.

Bean names

WebSphere Studio tools 115

Figure 132. Applet Designer: The completed applet

20.Test your applet by selecting File->Run.

Figure 133. Applet Designer: The animated redbook

3.4.2 Placing a Rollover button on the applet and connecting it to a URLIn this section, we add a rollover button, which, when pressed, opens the IBMWebSphere Web site. A rollover button changes its state when the mouse passesover it. Also, when the button is clicked, it changes its state again. To create theRoll Over, follow these steps:

1. Select the Multimedia tab in the Palette window.

2. Click on the Rollover icon, and place it below the book.

116 Web Enabling AS/400 Applications with IBM WebSphere Studio

3. When the dialog box appears, use the Find buttons to locate the threepictures for the Rollover button:

• Button Picture\Redbook\Code5634\WebSph.gif

• Pressed Picture\Redbook\Code5634\WebSphp.gif

• Rollover Picture\Redbook\Code5634\WebSpho.gif

Refer to Appendix A, “Example programs” on page 405, for more informationon how to download the SG245634.exe self-extracting file from the ITSO Website.

4. Select On rollover for a 3-D effect, and click Done.

5. Click the Networking tab in the Palette window, and select the URL Linkbean.

6. Place the URL Link somewhere on the Applet Designer surface. Logically, thisbean should be placed outside of the applet (white surface). However, insideor outside of your applet, it is not visible at runtime.

7. In the Properties frame, enter the URL address:

http://www.as400.ibm.com/Websphere

8. Click on the Rollover picture, and select the Connections frame. For eachcolumn, select the following options:

• When-> clicked• Bean-> URL Link1• Do-> show document

Ensure that when you are finished, the connection is not red. Incompleteconnections are in the color red.

9. Run the applet again, and test the Rollover button. If you click the Rolloverpicture nothing happens. In the applet viewer you cannot go to the URL. Thiscan only be done in a browser. The animated redbook with the Rollover buttonwindow appears as shown in Figure 134 on page 118.

The following GIF files are available from the SG245634 self-extracting file.If you have restored this file as described in the ReadMe file, they should belocated at the \Redbook\Code5634 directory.

Note

WebSphere Studio tools 117

Figure 134. Applet Designer: Animated redbook with Rollover button

3.4.3 Creating nervous text on the appletIn this section, we add nervous text to the applet and make connections so thatwhen the cursor enters the text area, the text starts to jump. It stops jumpingwhen the cursor is moved out of the text area. Follow these steps:

1. Select Multimedia in the Palette window.

2. Click on the Nervous Text icon, and then place it below the rollover button.

3. In the Properties frame of Nervous Text1, change the text to WebSphere Studio

is Cool!

4. Set Autostart to No and Anxiety Level to Calm.

5. Set Font to Sans Serif, bold, 20.

6. In Connections, select the following items:

• When-> mouse entered• Bean-> Nervous Text1• Do-> start

7. In Connections select, the following options:

• When-> mouse exited• Bean-> Nervous Text1• Do-> stop

Ensure that when you are finished, the connection is not red. Incompleteconnections are in the color red.

8. Test the applet. The applet appears as shown in Figure 135.

118 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 135. Applet Designer: Animated redbook with nervous text

3.5 Net Objects ScriptBuilder 3.0

NetObjects ScriptBuilder provides you with a text-based, context-sensitive editorfor files that contain common markup, scripting, and programming languages.

NetObjects ScriptBuilder 3.0 is a script development environment for the Internetthat offers a fast way to bring client and server side scripting to Web sites. Itcombines a powerful script editor and rich development tools with a visual,point-and-click environment that speeds script development.

ScriptBuilder bridges the gap between Netscape, Microsoft, IBM, and SunMicrosystems Web scripting environments. It includes full support for Allaire ColdFusion Markup Language (CFML), Dynamic HTML, ECMAScript, HTML, JavaServer Pages (JSP), Java, Lotus LotusScript, Microsoft Active Server Pages(ASP), Microsoft Channel Definition Format (CDF), Microsoft Document ObjectModel (DOM), Microsoft JScript, Microsoft VBScript, Netscape JavaScript,Netscape LiveWire, Perl, and Wireless Markup Language (WML).

With NetObjects ScriptBuilder, you can:

• Check your script syntax for errors• Create reusable object-oriented script components• Access local and Web-based language reference from within ScriptBuilder• Customize the language reference using Extensible Markup Language (XML)• Check your documents for browser compatibility• Drag and drop language elements into your document• Use Web-standard languages or languages other than Web-standard• Quickly navigate to embedded functions and components• Automate repetitive tasks• Preview your documents internally or in the external browser of your choice

WebSphere Studio tools 119

3.6 VisualAge for Java 3.0 Professional Edition

VisualAge for Java Professional Edition provides you with a complete JavaIntegrated Development Environment (IDE) including a Java code editor,debugger, visual composition editor, class browser, and various wizards.VisualAge for Java Enterprise Edition is available separately from WebSphereStudio for even more Java development capabilities, including team support.

WebSphere Studio integrates with VisualAge for Java Version 3.0 to providequick navigation between the two products:

• When you use the Studio Wizards to develop servlets and JavaBeans, you cantransfer them to VisualAge to extend their functions and maintain them there.

• When you develop new servlets and JavaBeans in VisualAge, you can bringthem into Studio to use in the JavaBean Wizard or publish to your Web sites.

• When you modify components in VisualAge for Java, you can update thecopies in the Studio project with the newer versions. In this case, werecommend that VisualAge for Java be your primary tool for maintaining theseJava components. If you have your Studio project under a version-controlsystem, you should use the same version-control system for VisualAge forJava.

120 Web Enabling AS/400 Applications with IBM WebSphere Studio

Chapter 4. Restoring the ABC Company Web site sample project

This chapter explains how to enable the ABC Company Web site by restoring theWebSphere Studio archive file (ABCCompany.war) into WebSphere Studio. Thefollowing topics are discussed in detail:

• Creating the ABC Company project within WebSphere Studio based on theWebSphere Studio archive file (ABCCompany.war)

• Defining the AS/400 system as the publishing target system into WebSphereStudio

• Publishing the ABC Company Web site to the AS/400 system

• Surfing the ABC Company Web site

4.1 Installing the download files

At this time, we assume that you have already downloaded the SG245634.exeself-extracting file, as explained in Appendix A, “Example programs” on page 405,for more information. You do not need a copy of Winzip program to install thiscompressed file since it is self extracting. However, if you prefer to browse thecontents (for example, for security reasons), you need a copy of the Winzipprogram. You can get a demonstration copy from the Web, or use an unzip utilitythat supports long file names.

To install the AS/400 save file and WebSphere Studio archive file, you should runthe SG245634.exe self-extracting file on a Windows 95, 98, or NT system fromWindows Explorer or from the command prompt. Winzip asks you for thedirectory to which you want to extract the files. We suggest that you use theC:\Redbook directory, as described in Appendix A, “Example programs” on page405. Then, it automatically creates a Code5634 sub-directory and places all thefiles into it.

4.2 Creating the WebSphere Studio project using the archive file

In this section, we assume that you have already extracted theABCCompany.war file. This is the WebSphere Studio archive file, which containsthe ABC Company WebSphere Studio sample project. We create the projectbased on the archive file, so we can later create the Web site by publishing theproject to an AS/400 server.

Before attempting to restore the WebSphere Studio archive file(ABCCompany.war) and create the ABC Company Web site, you must followthe instructions on the ReadMe file that is package with the self-extracting fileSG245634.exe.

Refer to Appendix A, “Example programs” on page 405, for more informationon how to download the SG245634.exe self-extracting file from the ITSO Website.

ReadMe file

© Copyright IBM Corp. 2000 121

4.2.1 Restoring the project archive filePerform the following steps to restore the ABC Company Web site project fromthe WebSphere Studio archive file:

1. Start WebSphere Studio if it is not already started.

2. Select File->Open Archive and open the ABCCompany.war file. The OpenArchive dialog appears with three tabs at the top.

3. On the Extract tab, select the Create new project and extract entirearchive radio button as shown in Figure 136.

Figure 136. Open Archive window: Extracting components

4. On the Destination tab, select the Custom locations radio button andspecify the location where you want to extract the project components, forexample C:\redbook\ABCCompany as shown in Figure 137.

Figure 137. Open Archive window: Customizing the project location

5. On the Options tab, select the Use archived publishing targets radio buttonto preserve target definitions as shown in Figure 138.

122 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 138. Open Archive window: Preserving publishing targets

6. Click Extract.

WebSphere Studio extracts the files and creates the ABC Company project asshown in Figure 139.

Figure 139. WebSphere Studio ABC Company project

4.2.2 Updating the ABC Company project files to use your AS/400 serverThe ABC company sample project was developed using our AS/400 serversystem, which we call AS20. You need to update the files to reflect your AS/400system name. Perform the following tasks to update the project files:

1. Start WebSphere Studio if it is not already started.

2. Select the ABCCompany project. Then, select Edit->Find and Replace Text.

Restoring the ABC Company Web site sample project 123

3. Replace the AS20 server with your AS/400 server (AS/400 system name)using the Find and Replace Text dialog box as shown in Figure 140.

Figure 140. Studio Workbench: Find and Replace Text dialog box

4. Click Find Now. After finding the first AS20 occurrence, the Replace buttonsare enabled.

5. Click the Replace All (AllFiles) button.

6. If you receive a Check Out message, as illustrated in Figure 141, click the Yesto All button. Also, click OK, Yes, or Yes to All on any further messages.

Figure 141. Studio Workbench: Check Out files message

7. When finished, click OK, and close the Find and Replace Text dialog box.

8. Right-click the ABCCompany project, and select the Check In option tocheck in all project files that have been checked out during the updateprocess.

4.2.3 Creating an AS/400 user profileTo run the servlets created by the Studio Wizards, you need to create an AS/400user profile that matches the user ID and password in the ABC Company servletfiles. On the AS/400 system, run the following OS/400 command:

CRTUSRPRF USRPRF(REDBOOK) PASSWORD(HEAD4SEA)

124 Web Enabling AS/400 Applications with IBM WebSphere Studio

4.3 Setting up the AS/400 system to run the ABC Company Web site

Now that the WebSphere Studio archive file has been restored, the next step is todeploy and run the ABC Company application on the AS/400 system. Theobjective of this section is to cover the deployment and packaging of theWebSphere Studio applications.

4.3.1 Publishing to the AS/400 systemOnce the WebSphere Studio application is ready and working on your clientmachine, you are ready to publish the project on your AS/400 system. Performthe following steps to publish the ABC Company project on your AS/400 system:

1. Map a network drive to the IFS of the AS/400 system. In this example, we mapthe I: drive to the root of the AS/400 IFS.

\\yourAS400\root

2. Start WebSphere Studio, and open the ABCCompany project.

3. Select Project->Publishing Stage->Test.

4. Select View->Publishing.

5. Add the AS/400 server to the Test stage. Right-click on the Test stage icon.Select Insert->Server from the menu as shown in Figure 142.

Figure 142. Inserting a server in the Test publishing stage

6. Enter the server name, yourAS400, and the TCP/IP port on which youconfigured the WebSphere Application Server as illustrated in Figure 143 onpage 126. After you add the server, you need to define its properties.

If your AS/400 system does not allow you to create a user profile with theUSRPRF(REDBOOK) and PASSWORD(HEAD4SEA), for any reason, you can create itwith any other values. However, you have to replace the ABC Company projectfiles with the new userid and password values.

Refer to 4.2.2, “Updating the ABC Company project files to use your AS/400server” on page 123, for information on replacing text in the WebSphere Studioproject files.

AS/400 user profile

Restoring the ABC Company Web site sample project 125

Figure 143. Inserting the AS/400 server in the Test publishing stage

As shown in Figure 144, you now see the new server under the Test publishingstage.

Figure 144. The Test publishing stage

7. To change the default server to your AS/400 system, right-click on the Teststage icon, and select Properties from the menu. Click the Advanced tab,and select the AS/400 server http://yourAS400 from the Default serverdrop-down list as illustrated in Figure 145.

Figure 145. Changing the default server

126 Web Enabling AS/400 Applications with IBM WebSphere Studio

8. Close the Test Properties dialog by clicking OK.

9. Update the publishing targets for the AS/400 server by right-clicking on theAS/400 server icon and selecting Properties from the menu. When thePublishing Properties dialog appears, click the Define Publishing Targetsbutton. When the publishing targets dialog appears as shown in Figure 146 onpage 127, verify that the targets match the following names:

• html I:\QIBM\ProdData\IBMWEBAS\

• servlet I:\QIBM\ProdData\IBMWEBAS\servlets

Here, I: is a network drive assigned to the root of the AS/400 IntegratedFile System (IFS).

10.If your targets do not match the path names in step 10, click the Browsebutton to navigate through the file system to find the files.

Figure 146. AS/400 Publishing Targets

11.Click OK to close the Publishing Targets dialog.

12.Click OK to close the Publishing Properties dialog.

13.To set a default publishing target, select Tools->Publishing Options. Clickthe Advance tab, and select the AS/400 publishing target system from theTest drop-down list (Figure 147 on page 128).

You may want to publish your HTML files to a separate directory. For this,you have to create an HTML directory under\QIBM\ProdData\ibmwebas\html and then add a Pass directive in yourHTTP configuration file.

Publishing target

Restoring the ABC Company Web site sample project 127

Figure 147. Setting the AS/400 server as the default publishing server

14.Click OK to close the Publishing Options dialog.

15.To move the files to the publishing stage, select the ABCCompany project.Then select Edit->Set as Publishable->Yes from the pull-down menu to setthe ABC Company files as publishable. This process moves all the projectcomponents under the Test->yourAS400 stage as illustrated in Figure 148.

Figure 148. Setting the project files as publishable

16.From the publishing view, select the server http://yourAS400. Then,right-click, and select the Publish this server option.

128 Web Enabling AS/400 Applications with IBM WebSphere Studio

17.Several dialogs may appear. Select the default options on each and simplyclick OK, Yes, or Yes to All ignoring the warnings. Publishing causesWebSphere Studio to copy all the files set as publishable to the publishingtarget (a Web servers directory structure). After this publishing processfinishes, you receive a report as illustrated in Figure 149.

Figure 149. Publishing report for the ABC Company project

18.Browse through the report and ensure that no files were found with errorsbefore attempting to proceed. In case errors were found, you need to correctthem, and then repeat the steps in this section.

19.Ensure that the WebSphere Application Server on AS/400 is up and running.

20.To test the publishing process, select the index.html file from the publishingview to preview it. Then, right-click, and select Preview file with Netscape orInternet Explorer. When the Web browser appears, the ABC CompanyWelcome page appears as shown in Figure 150 on page 130.

Restoring the ABC Company Web site sample project 129

Figure 150. ABC Company Web site: Welcome page

4.3.2 Packaging the WebSphere Studio applicationThe objective of this section is to package the application so it can be distributedto different systems. The key consideration is how to keep the packaging simple.There are many ways of packaging the application. Here is a simple way to do it.

The first time you call a generated Studio Wizards servlet, it will be slow. This isdue to the fact that the JSP has to be compiled and the servlet has to connectto the database. Subsequent tries will be much faster.

Previewing Web sites

If you succeeded in publishing the ABC Company project to your AS/400system, you should see the ABC Company Welcome page when previewingthe index.html file, as shown in Figure 150. However, before attempting tobrowse other Web site pages, or use the Web site functionality, you mustconfigure the WebSphere Application Server to use the LoginServlet servlet asdescribed in 4.3.3, “ABC Company Web site configuration” on page 132. TheLoginServlet validates the user ID input against an AS/400 database todetermine if the user is a valid one.

Important

130 Web Enabling AS/400 Applications with IBM WebSphere Studio

Once the application is ready, deployed, and tested, you are ready fordistribution. The challenge is to package the application in such a way that thedistribution is easy. Perform the following steps to package the ABC Companyapplication:

1. Create a customized publishing stage by selecting Project->CustomizePublishing Stages. Enter Distribute as the stage name (Figure 151).

Figure 151. Customize Publishing Stages

2. Click the Add button, and then click the OK button to close the CustomizedPublishing Stage window.

3. Select Project->Publishing Stage->Distribute.

4. To add a server to a publishing stage, right-click on the Distribute stage icon.Select Insert->Server from the menu, and then enter Export as the servername. Click OK. After you add the server, you need to define its properties.

5. Right-click on the Export server icon, and select Properties from the menu.When the Publishing Properties dialog appears, click the Define PublishingTargets button. The publishing targets dialog appears as shown in Figure 152.Enter the following paths as publishing targets:

• html x:\output\html

• servlet x:\output\servlets

Here, x: is the drive where you want the files be located in your computer.

Figure 152. Publishing Targets

Restoring the ABC Company Web site sample project 131

6. Click OK twice to return to the Studio Workbench window.

7. Publish the entire project by right-clicking on it and selecting Publish wholeProject from the menu option.

8. Several dialogs may appear. Select the default options on each and simplyclick OK, Yes, or Yes to All ignoring the warnings. Publishing causesWebSphere Studio to copy all the files set as publishable to the publishingtarget (a Web server directory structure). After this publishing processfinishes, you receive a report as illustrated in Figure 149 on page 129.

9. Open the Windows Explorer. You should now see a folder named “output”which contains the HTML and servlets folders.

10.Compress the “output” folder to a .zip file. It is now ready for distribution.When you restore the files on the target system, make sure that you put thecontents of the HTML and servlets folder in the appropriate publishing folder.

4.3.3 ABC Company Web site configurationThis section discusses some of the configuration considerations for the ABCCompany Web site. These considerations apply for any Web site development.To make the distribution of an application easier, you should externalizeparameters. You can then change the parameters without changing theprograms. In this application, we externalize the userid, password, database, andJDBC driver used by the application.

This section also highlights the different ways in which you can configure theWebSphere Application Server to use a JDBC driver to access the AS/400system. With the AS/400 system, you have two choices for a JDBC driver: theAS/400 Toolbox for Java driver or the native driver. The one to use depends onwhere you are running the WebSphere Application Server. If it is on the AS/400system, use the native driver. Otherwise, use the AS/400 Toolbox for Java driver.

4.3.3.1 Soft coding the parameters and creating a servlet aliasThe objective of this section is to avoid hard-coding the connection relatedparameters. As discussed in Chapter 8, “Creating the complete ABC CompanyWeb site” on page 361, the LoginServet servlet takes the user ID input andvalidates it against an AS/400 database to determine if the user is a valid one. Weuse JDBC to validate the user ID. To do this, there has to be a connection to theAS/400 system. To establish a connection, you need an AS/400 system user ID,password, URL, and the JDBC driver to use.

There are various ways in which you can avoid hard-coding these values in theservlet. In this example, we use the WebSphere Application Server administrationtool to define the parameters. We then access them in the servlet. By followingthis technique, you are more secure because you are not hard coding theparameters in the servlet. You can also change them based on the environment inwhich you deploy the application.

In every servlet, there is a Init() method, which executes only one time duringthe lifetime of the servlet. It executes when the server loads the servlet. You canconfigure the server to load the servlet when the server starts or when a clientfirst accesses the servlet.

In the LoginServlet servlet, we use the getInitParameter() method to retrieve theparameters that we need for the connection to the AS/400 system. We use the

132 Web Enabling AS/400 Applications with IBM WebSphere Studio

WebSphere Application Server administration tool to configure the name of theservlet and the properties that it uses. Perform the following steps to configurethe properties:

1. Open the WebSphere Application Server administration page on your browserby entering http://yourAS400:9090. Enter the user ID and password to sign on.

The default userid and password are Admin and Admin respectively.

2. Select Configuration under Servlets from the left-hand side frame.

3. Click Add to add a new servlet to the configuration. The Add New Servletwindow appears as shown in Figure 153.

Figure 153. Add a New Servlet

a. Enter login for the Servlet name. For the Servlet Class, entersession.LoginServlet, which is the package and class name.

When you use this technique, you assign the servlet a name. In this case,the name of the servlet is login. It points to the proper package and classname (session.LoginServlet). When you execute this servlet, you executelogin, not session.LoginServlet.

b. Click Add to add this servlet to the configuration.

c. Verify that the servlet name appears in the Servlet Name list.

d. Highlight it by selecting the servlet name under Servlet Name list.

4. Add the servlet properties to the servlet you created:

a. Click the Add button in the Servlet Properties area of the administrationpage.

b. Click the Name column of first row, and enter driver. Click the Valuecolumn, and enter com.ibm.as400.access.AS400JDBCDriver. If you are runningthe application on the AS/400 system enter com.ibm.db2.jdbc.app.DB2Driverinstead to use the native JDBC driver.

c. Click Enter to add this parameter to the properties list.

d. Enter the following additional name and values parameters:

• Password: yourPassword• User: yourUserid• URL: jdbc:as400://sysname//library

Use jdbc:db2://sysname//library for the native JDBC driver.

Restoring the ABC Company Web site sample project 133

• Login: /loginIndex.jsp• Logout: /logout.jsp

5. Verify that the Loaded Now (YES) radio button is selected in order to load theservlet.

6. Click Save to save the configuration.

The servlet properties window appears as shown in Figure 154.

Figure 154. Servlet properties page

Here, apart from the normal parameters for the ABC Company site, we alsohave login and logout parameters, which point to the login and logout pages.By using this technique, we do not need to hard code the parameters.

When running on the AS/400 system, the servlets.properties file on theAS/400 system is found in theQIBM\ProdData\IBMWebAS\properties\server\servlet\servletservice directory.

The administration tool updates the servlets.properties file with the values weset. As a result of the entries made with the administration tool, the followingentries are added to the servlets.properties file:

servlet.login.code=session.LoginServletservlet.login.initArgs=user=yourUserid,password=yourPassword,url=jdbc:as400:sysname/library,driver=com.ibm.as400.access.AS400JDBCDriver,login=/loginIndex.jsp,logout=/logout.html

The code used to retrieve the parameter in the LoginServlet is:

String url = getInitParameter("URL");String userid = getInitParameter("user");String password = getInitParameter("password");String driver = getInitParameter("driver");String login = getInitParameter("login");String logout = getInitParameter("logout");

134 Web Enabling AS/400 Applications with IBM WebSphere Studio

7. For the ABC Company application, we need two additional servlets added tothe configuration file. They are:

• For session management purpose, we use check as the servlet name. Thispoints to session.SessionCheckServlet. It has one property namedloginPage and a value of /login.html.

The following entries are added to the servlets.properties file:

servlet.check.code=session.SessionCheckServletservlet.check.initArgs=loginPage=/login.html

• The second servlet is logout, which points tosession.SessionLogoutServlet. It has a property named logoutPage with avalue of /logout.html.

The following entries are added to the servlets.properties file:

servlet.logout.code=session.SessionLogoutServletservlet.logout.initArgs=logoutPage=/logout.html

8. Save the configuration and recheck to see if all the servlet names and theirproperties are saved and correct.

4.3.3.2 Using AS/400 Toolbox for Java to access the AS/400 databaseThe objective of this section is to show how make classes from the AS/400Toolbox for Java available to the WebSphere Application Server. Once youpublish the application to the AS/400 system, the WebSphere Application Serverneeds to know how to locate all the classes it uses. Follow these steps to allowthe AS/400 Toolbox for Java classes to be used:

1. Open the WebSphere Application Server administration page on your browserby entering:

http://yourAS400:9090

2. Click Java Engine under Setup. The Java Engine page appears as shown inFigure 155.

Figure 155. Java Engine page

3. Add the following path to the Application Server Classpath:

/QIBM/ProdData/IBMWebAS/web/classes:/QIBM/ProdData/HTTP/Public/jt400/lib/jt

400.zip:/QIBM/ProdData/HTTP/Public/jt400/lib/x4j400.jar

Restoring the ABC Company Web site sample project 135

/QIBM/ProdData/IBMWebAS/web/classes is the classpath entry for theWebSphere Application Server. It is added by default.

/QIBM/ProdData/HTTP/Public/jt400/lib/jt400.zip is the classpath entry for theAS/400 Toolbox for Java. This is needed to tell the WebSphere ApplicationServer where to look for the AS/400 Toolbox for Java classes.

/QIBM/ProdData/HTTP/Public/jt400/lib/x4j400.jar is the classpath entry for theXML parser class files. This is required for using PCML calls. To avoid this,you can serialize the servlet that uses PCML calls.

As a result of this configuration, the following line is added to thebootstrap.properties file in the AS/400 IFS /QIBM/ProdData/ibmwebas/propertiesdirectory path:

java.classpath=/QIBM/ProdData/IBMWebAS/web/classes:/QIBM/ProdData/HTTP/Public/jt400/lib/jt400.zip:/QIBM/ProdData/HTTP/Public/jt400/lib/x4j400.jar.

Now, you are ready to run the ABC Company Web site application. At this point,all the required configuration is done.

For the AS/400 system, the classpath has colons between the entries and notcommas as in other platforms.

Note

136 Web Enabling AS/400 Applications with IBM WebSphere Studio

Chapter 5. Order Entry application

This chapter presents the RPG Order Entry application example. This applicationis representative of a commercial application, although it does not include all ofthe necessary error handling that a business application requires.

The chapter also introduces the application and specifies the database layout. InChapter 6, “Enabling the Order Entry application: Methodology” on page 151, weconvert the RPG Order Entry application to a Web-enabled application. The goalis to use the existing RPG application to service both the Web application and thehost 5250 application.

5.1 Overview of the Order Entry application

This section provides an overview of the application and a description of how theapplication database is used.

5.1.1 The ABC CompanyThe ABC Company is a wholesale supplier with one warehouse and 10 salesdistricts. Each district serves 3,000 customers (30,000 total customers for thecompany). The warehouse maintains stock for the 100,000 items sold by thecompany.

Figure 156 illustrates the company structure (warehouse, district, and customer).

Figure 156. The company structure

5.1.2 The ABC Company databaseThe company runs its business with a database. This database is used in amission critical, online transaction processing (OLTP) environment. The databaseincludes tables with the following data:

• District information (next available order number, tax rate, and so on)• Customer information (name, address, telephone number, and so on)• Order information (date, time, shipper, and so on)• Order line information (quantity, delivery date, and so on)

© Copyright IBM Corp. 2000 137

• Item information (name, price, item ID, and so on)• Stock information (quantity in stock, warehouse ID, and so on)

5.1.3 A customer transactionA customer transaction occurs based on the following series of events:

1. Customers telephone one of the 10 district centers to place an order.

2. The district customer service representative answers the telephone, obtainsthe following information, and enters it into the application:

• Customer number• Item numbers of the items the customer wants to order• The quantity required for each item

3. The customer service representative may prompt for a list of customers or alist of parts.

4. The application then performs the following actions:

a. Reads the customer last name, customer discount rate, and customercredit status from the Customer table (CSTMR).

b. Reads the District table for the next available district order number. Thenext available district order number increases by one and is updated.

c. Reads the item names, item prices, and item data for each item ordered bythe customer from the Item table (ITEM).

d. Checks if the quantity of ordered items is in stock by reading the quantity inthe Stock table (STOCK).

5. When the order is accepted, the following actions occur:

a. Inserts a new row into the Order table to reflect the creation of the neworder (ORDERS).

b. A new row is inserted into the Order Line table to reflect each item in theorder.

c. The quantity is reduced by the quantity ordered.

d. A message is written to a data queue to initiate order printing.

5.1.4 Application flowThe RPG Order Entry Application consists of the following components:

• ORDENTD (Parts Order Entry): Display file• ORDENTR (Parts Order Entry): Main RPG processing program• PRTORDERP (Parts Order Entry): Print file• PRTORDERR (Print Orders): RPG server job• SLTCUSTD (Select Customer): Display file• SLTCUSTR (Select Customer): RPG SQL stored procedure• SLTPARTD (Select Part): Display file• SLTPARTR (Select Part): RPG stored procedure

To download the sample code used in this redbook, please refer to Appendix A,“Example programs” on page 405, for more information.

Note

138 Web Enabling AS/400 Applications with IBM WebSphere Studio

Each component is shown in the RPG Application flow in Figure 157.

Figure 157. RPG application flow

ORDENTR is the main RPG program. It is responsible for the main lineprocessing. It calls two supporting RPG programs that are used to prompt for andselect enduser input. They are SLTCUSTR, which handles selecting a customer,and SLTPARTR, which handles selecting part numbers. PRTODERR is an RPGprogram that handles printing customer orders. It reads order records that wereplaced on a data queue and prints them in a background job.

5.1.5 Customer transaction flowThe following scenario walks through a customer transaction showing theapplication flow. By understanding the flow of the AS/400 application, you canunderstand the changes made to this application to support a graphical client.

5.1.5.1 Starting the applicationTo start the application, the customer calls the main program from an AS/400command line:

CALL ORDENTR

When the Order Entry application is started, the display shown in Figure 158 onpage 140 appears.

Order Entry application 139

Figure 158. Parts Order Entry

When the Parts Order Entry display appears, the user has two options:

• Type in a customer number, and press the Enter key.• End the program by pressing either F3 or F12.

If the user does not know the customer number, they can press F4 to view awindow containing a list of available customers.

Figure 159. Select Customer

The user presses F12 to remove the window and return to the initial panel, orthey scroll through the items in the list until they find the customer they want. By

140 Web Enabling AS/400 Applications with IBM WebSphere Studio

typing a 1 in the option field and pressing the Enter key, the user indicates theirchoice. The selected customer is then returned to the initial panel (Figure 160).

Figure 160. Parts Order Entry

After selecting a customer from the list, or typing a valid customer number andpressing the Enter key, the customer details are shown and an order number isassigned. An additional prompt is displayed allowing the user to type a partnumber and quantity.

If the user does not know the part number, they can press F4 to view a windowcontaining a list of available parts (Figure 161 on page 142).

Order Entry application 141

Figure 161. Select Part

The user presses F12 to remove the window and return to the initial panel, orthey scroll through the items in the list until they find the part they want. By typinga 1 in the option field and pressing the Enter key, they indicate their choice. Theselected part is returned to the initial panel (Figure 162).

Figure 162. Parts Order Entry

After selecting a customer from the list, or typing a valid customer number andpressing the Enter key, the part and quantity ordered are added to the list sectionbelow the part entry fields (Figure 163).

142 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 163. Parts Order Entry

The user may type a 2 beside an entry in the list to change the order. When theEnter key is pressed, a window appears that allows the order line to be changed(Figure 164).

Figure 164. Change Selected Order

The user chooses to press F12 to cancel the change, press F4 to list the parts, ortype a new part identifier or different quantity. Pressing the Enter key validatesthe part identifier and quantity. If valid, the order line is changed in the list and thewindow is closed.

Order Entry application 143

Figure 165. Completed order

In Figure 165, you see the quantity for Zoo Season Pass is changed to 3. Whenthe order is complete, the user presses F6 to update the database. Then, anorder is placed on the data queue for printing.

Figure 166. Printed order

144 Web Enabling AS/400 Applications with IBM WebSphere Studio

The printed order (Figure 166) is created by a batch process. It shows thecustomer details and the items, quantities, and cost of the order.

5.1.6 Database table structureThe ABC Company database has eight tables:

• District• Customer• Order• Order Line• Item• Stock• Warehouse• History

The relationship among these tables is shown in Figure 167.

Figure 167. Table relationships

5.1.7 Order Entry application database layoutThe sample application uses the following tables of the database:

• District• Customer• Order• Order line• Stock• Item (catalog)

The following tables describe, in detail, the layout of the database.

Order Entry application 145

Table 2. District table layout (Dstrct)

Table 3. Customer table layout (CSTMR)

Field name Real name Type Length

DID District ID Decimal 3

DWID Warehouse ID Character 4

DNAME District Name Character 10

DADDR1 Address Line 1 Character 20

DADDR2 Address Line 2 Character 20

DCITY City Character 20

DSTATE State Character 2

DZIP Zip Code Character 10

DTAX Tax Decimal 5

DYTD Year to Date Balance Decimal 13

DNXTOR Next Order Number Decimal 9

Primary Key: DID and DWID

Field name Real name Type Length

CID Customer ID Character 4

CDID District ID Decimal 3

CWID Warehouse ID Character 4

CFIRST First Name Character 16

CINIT Middle Initials Character 2

CLAST Last Name Character 16

CADDR1 Address Line 1 Character 20

CCREDT Credit Status Character 2

CADDR2 Address Line 2 Character 20

CDCT Discount Decimal 5

CCITY City Character 20

CSTATE State Character 2

CZIP Zip Code Character 10

CPHONE Phone Number Character 16

CBAL Balance Decimal 7

CCRDLM Credit Limit Decimal 7

CYTD Year to Date Decimal 13

CPAYCNT Payment Decimal 5

146 Web Enabling AS/400 Applications with IBM WebSphere Studio

Table 4. Order table layout (ORDERS)

Table 5. Order Line table layout (ORDLIN)

CDELCNT Delivery Qty Decimal 5

CLTIME Time of Last Order Numeric 6

CDATA Customer Information Character 500

Primary Key: CID, CDID, and CWID

Field name Real name Type Length

OWID Warehouse ID Character 4

ODID District ID Decimal 3

OCID Customer ID Character 4

OID Order ID Decimal 9

OENTDT Order Date Numeric 8

OENTTM Order Time Numeric 6

OCARID Carrier Number Character 2

OLINES Number of Order Lines Decimal 3

OLOCAL Local Decimal 1

Primary Key: OWID, ODID, and OID

Field name Real name Type Length

OID Order ID Decimal 9

ODID District ID Decimal 3

OWID Warehouse ID Character 4

OLNBR Order Line Number Decimal 3

OLSPWH Supply Warehouse Character 4

OLIID Item ID Character 6

OLQTY Quantity Ordered Numeric 3

OLAMNT Amount Numeric 7

OLDLVD Delivery Date Numeric 6

OLDSTI District Information Character 24

Primary Key: OLWID, OLDID, OLOID, and OLNBR

Field name Real name Type Length

Order Entry application 147

Table 6. Item table layout (ITEM)

Table 7. Stock table layout (Stock)

5.1.8 Database terminologyThis redbook concentrates on the use of the AS/400 system as a database serverin a client/server environment. In some cases, we use SQL to access the AS/400database. In other cases, we use native database access.

Field name Real name Type Length

IID Item ID Character 6

INAME Item Name Character 24

IPRICE Price Decimal 5

IDATA Item Information Character 50

Primary Key: IID

Field name Real name Type Length

STWID Warehouse ID Character 4

STIID Item ID Character 6

STQTY Quantity in Stock Decimal 5

STDI01 District Information Character 24

STDI02 District Information Character 24

STDI03 District Information Character 24

STDI04 District Information Character 24

STDI05 District Information Character 24

STDI06 District Information Character 24

STDI07 District Information Character 24

STDI08 District Information Character 24

STDI09 District Information Character 24

STDI10 District Information Character 24

STYTD Year to Date Decimal 9

STORDERS Number of orders Decimal 5

STREMORD Number of remote orders Decimal 5

STDATA Item Information Character 50

Primary Key: STWID and STIID

148 Web Enabling AS/400 Applications with IBM WebSphere Studio

The terminology used for database access is different in both cases. In Table 8,you find the correspondence between the different terms.

Table 8. Database terminology

AS/400 native SQL

Library Collection

Physical File Table

Field Column

Record Row

Logical File View or Index

Order Entry application 149

150 Web Enabling AS/400 Applications with IBM WebSphere Studio

Chapter 6. Enabling the Order Entry application: Methodology

This chapter walks through the Web-enablement methodology cycle of a simpleAS/400 order entry application, as described in Chapter 5, “Order Entryapplication” on page 137. Many, but not all, tools available in the IBM WebSphereStudio are discussed.

6.1 Identifying the AS/400 application to Web-enable

The idea behind Web enabling is identifying portions of a company’s businessoperations and functions, which could be off loaded to clients or customers.Some primary examples are catalog browsing, inventory stock status lookups,order entry, customer service functions. In our example scenario, we identify a“call center” model. We offload the functions of answering the phone, order entry,and order acceptance from the call center clerks. We eliminate the phone callsand allow the customers to perform catalog browsing, order entry and orderacceptance, order status look up all by themselves. However, this does not meanthat we eliminate the call center all together. Even though the tasks of the callcenter could be accomplished by the end users (customers, clients), ascaled-down version of the call center is still needed to accommodate the endusers who are not Web or computer savvy.

6.1.1 Primary users of the Web applicationPrior to the development of the Web site, primary users need to be identified.Knowledge of who the primary users are guides the design and developmentprocesses. In our scenario, primary users are:

• Customers/clients who use the call center to:

– Place orders– Browse products catalog to check availability and pricing– Check order status

• Administrator to (these function are not implemented in the ABC Companysample project):

– Validate new “Web users”– Review or Print various order reports– Delete Web user profiles– Reset passwords

6.1.2 Identifying issues and assumptionsA Web site can certainly alter a company’s operations, business processes, andso forth. To foresee the changes and analyze the impact, issues and assumptionsneed to be identified:

• Issues (not in any particular order):

– Since Web users will trigger the creation of their Web profiles (not AS/400user profiles) and customer records, the validation function becomes veryimportant.

© Copyright IBM Corp. 2000 151

– Security is another concern, which should be include authentication andencryption.

– Performance evaluations should become a standard practice toaccommodate the Web traffic loads.

• Assumptions (not in any particular order):

– Business logic is preserved on AS/400 server. Presentation logic is put onthe Web.

– Existing customers have to be “setup” as Web users.

– Validation and error handling should be strong to avoid the “bad” datagetting into the enterprise database.

Refer to 8.6, “Heading towards e-commerce” on page 400, for more in depthdiscussion on e-commerce.

6.1.3 Analysis of the AS/400 application: Business and presentation logicThe idea behind the separation of business and presentation logic is to preservecurrent databases and application programs that are running on the AS/400server. Application programs and databases have specific business rules built in.The AS/400 server is a secure, reliable, and stable platform. We cannot afford torewrite it all, for example, using Enterprise JavaBeans (EJBs), because of thecost, risk, and other factors. Some portions of the application on the AS/400server may not need to be rewritten because they are efficient, fast, and proven.

For the ABC company, the order commitment, inventory management, andcustomer record validation logic are preserved within the AS/400 database andapplications. The RPG Order Entry program was changed to allow the separationof the presentation from business logic. Refer to 7.6, “Changes to the Host OrderEntry application” on page 343, for details on a separation presentation frombusiness logic.

6.2 Web-site design

When it comes to working with presenting content on the Internet, there are manyconsiderations a designer or developer must take into account. You need toremember who your target audience is.

Many people design Web sites that are difficult to navigate and use. A keyconcept to remember when developing an Internet Web site is to make thecontent fit the Web site and not the Web site fit the content.

Many people decide the entire content of the Web site first and then create adesign and navigation to suit. A better way to create a Web site is to decide theobjective of the Web site, the key areas of the site, and how to navigate betweenall these pages. Once this is decided, it is easy to fill the content in on each page.Figure 168 shows the navigation we use in the ABC Company Web site.

152 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 168. Complete Web site navigation

6.2.1 Dividing the Web site into subsites based on functionalityOnce you decide the navigation between the various sections of the Web site, itbecomes clear that there are “subsites” that make the generation of the Web sitea lot easier. If you look at the initial design, you see how the flow of the sitebetween the static front pages and the dynamic interactive pages has a one-waypath. This is a good place to break the site into subsites. All of the front pagesthat are static can be the static subsite and all the interactive pages can besubsite two. If you look closer at the interactive site, you see some different areasof functionality. You have a shopping cart, catalog, order status, and orderprocessing. Each of these should be broken down into subsites since you knowthat there is some sort of code generation that needs to go on inside these sites.If you break them into subsites, testing each section becomes significantly easier.

6.2.1.1 Static HTML pagesThe static pages should contain all the information about the company. It isimportant to remember for the user that has come to this Web site for the firsttime and has no idea who the company is. The pages that would make up thissubsite are shown in Figure 168:

• Welcome• About Us• History• Catalog• Login• Login Error• Logout• New User

6.2.1.2 Login and session managementLogin and session management is important to verify if the user is allowed in thedynamic Web site and so you can use their username to retrieve their customer

Enabling the Order Entry application: Methodology 153

ID from the database. Once you have their customer ID, you can get allinformation about this user, such as what they have in their shopping cart. Afterthe user has logged in, you also generate a dynamic session ID that is assignedand maintained in the AS/400 WebSphere Application Server.

The session that the user gets allocated is tested on every page for its existence.This is important because if a user accesses a page that requires a customer IDand they have not logged in, errors appear since you have no way to identify thisuser. The session test looks to see if the user has a session and will then redirectthe user to the login page if they are required to login.

6.2.1.3 New usersWithin the existing order entry application users must have user profiles definedon the AS/400 server. Web users are not going to have user profiles setup on theAS/400 server, yet you need to authenticate them and provide some sort ofsecurity. There are many different ways to handle the issue. Our solution is tocreate a table on the AS/400 server to hold Web users’ records with Web-relatedinformation and a link to their customer ID. When a new Web user wants toaccess the Web site, they fill out a form with their personal information andspecify their login ID and password. When they click the Submit button, theirrecords are added to the existing customer table and to the Web user table.

Once a new user has been created, the user is given the acknowledgement. Theycan then log straight into the dynamic pages without having to provide theirusername and password again.

There is some information that the user will not provide. For example, the userwill not be able to give their credit limit or discount. This means that any new userthat is generated will be flagged as having a new account. The user can orderwhatever they like from the Web site. However, before the order is packed andshipped, their account needs to be validated. You can also take extendedinformation from the user that, until now, was not needed within the customerdatabase. The main piece of new information that you require is the users e-mail.If you expect the customer to deal with you over the Internet, it would be better tocontact them over the Internet providing the information is not confidential.

6.2.1.4 CatalogThe catalog subsite allows the user to view the catalog and find all products thatABC Company has to offer. It is important for the user to access the catalogregardless of being a registered member. If you look back at the subsite layout onFigure 168 on page 153, you see that the catalog can be accessed in two places.If a user accesses the catalog in the static site area, they have gone there simplyto view the products that are offered with absolutely no obligation to purchase.

The second place the catalog can be found is inside the dynamic site section.This version of the catalog allows the user to view all products on offer from theABC Company and to select a product from the catalog to add to the catalog. Youcan only offer this to the Web shopper since you only know their customer ID afterthey have logged in.

Another key feature of the catalog is to allow the user to search for items meetinga certain criteria. The search requirement we added to our demonstrationapplication allows the user to select the price range of an item. We could easilyallow the user to search for items based on a description or even availability. The

154 Web Enabling AS/400 Applications with IBM WebSphere Studio

other way we present the catalog is to display all items in alphabetical order. Thisis only practical when the company has no more than 100 products. You need toremember that when a user views the entire catalog they need to wait for thecatalog to download to their browser. If the company has 10,000 products, theuser needs to wait some time to view the catalog and lose interest in the site.

6.2.1.5 Shopping cartThe shopping cart subsite allows the user to view and edit all the items they haveselected to date. The shopping cart has its own table on the AS/400 system thatstores all the products that the user wants to purchase. There are techniques inwhich the shopping cart could be stored besides in a table. You could easily usebeans that are bound to the WebSphere Application Server. However, if you have15 concurrent users each with 30 items in their shopping cart, performance willsuffer and again cause your Web customers to lose interest. The downside tomaintaining a table for the shopping cart is that it is not tightly integrated with theWebSphere Application Server, and you need to add logic to look at how relevanttheir shopping cart is. For example, if the user shopped with you two years agoand did not purchase the contents of their shopping cart, they will see oldinformation and possibly even products that do not exist any more.

6.2.1.6 Order purchaseThe order purchasing subsite is where the integration into the RPG applicationhappens. Until this point, you have added layers around the application so thatyou can accumulate the information about the products the user wants topurchase. Once they are satisfied, you can pass this information to the RPGapplication as parameters. You cannot partially process an order since the userprogresses through the Web site.

The order purchase passes the contents of the shopping cart to the RPGapplication. Once the RPG application is called and the order has been created,the contents of the shopping cart are deleted. Once the user has ordered thoseitems, there is no need to maintain the cart.

6.2.1.7 Order statusIt is good for a user to see what is happening with their order. You have allowedyour user to order your products over the Web. The last thing you need is forthem to call you to find out what is happening with their product. If the customercalls you because they cannot find their order status on your Web site, you havefailed in using the Internet e-commerce, e-business solution.

The order status subsite also needs to be behind the login page for the samereason as the other subsites. You need to know the users customer ID so you canretrieve the correct information.

6.2.2 Subsite development and unit testingNow that we have established what a subsite is, we explore the added benefit ofhaving a subsite. Subsites can be distributed among Web site developers andthere is no concern for overlapping work. WebSphere Studio supports multiplepeople working on the one project. However, if, in the early stages, two peopleshare the work on a single page, the process becomes slow and inefficient. Theonly time multiple people should work on the same pages is when the site isbeing finalized and ready for deployment. This optimizes the work performed andproduces results faster.

Enabling the Order Entry application: Methodology 155

When each of the subsites are created, they can be tested individually. Chapter 7,“ABC Company Web site design and development” on page 157, shows how theWebSphere Studio Wizards are used to generate the dynamic pages and a staticpage is produced. The static page uses a static parameter given by you and youcan fully test to make sure the results are as you expect.

6.2.3 Tying it all togetherAfter the subsites have been generated, you can tie the entire Web site together.The first thing you need to look at is what parameters are passed to each of thepages. This can be determined by looking at the test HTML page. You can callthe servlets that have been generated by any page, provided you pass theparameters that are expected. By looking at the test page, you can clearly seewhat these parameters are. If there are four fields on your test page, you need tosubmit for parameters to the servlet that is called. This is discussed in furtherdetail in Chapter 7, “ABC Company Web site design and development” on page157.

The final step to tying it all together is placing the session checking servlet onevery page that is inside the dynamic Web site. This needs to be there to ensurethat any parameter that are required by that page are instantiated before thatpage is called.

6.2.4 Integration testingNow that the entire site has been created, some extensive testing should bedone. It is important to remember that this is being presented to people that youwant to do business with you. If the Web site does not work correctly, people willbe disheartened and not trade with you in this manner. Spend some time goingthough the full process and testing everything. Treat the entire Web site as anapplication and put it through the same testing regime through which you wouldput any application you created on the AS/400 system.

6.3 Summary

You should consider these issues during the Web site design:

• Keep site message and appearance consistent and “familiar”.• Use content elements wisely.• Test as many different likely client scenarios as possible.

In Chapter 7, “ABC Company Web site design and development”, we coverdesign and development of the building blocks, which we call subsites, for theABC Company Web site. We heavily rely on the WebSphere Studio Wizards,which generate queries, servlets, beans, HTML pages, and Java Server Pages(JSPs), which, in turn, provide most of the functionality required.

156 Web Enabling AS/400 Applications with IBM WebSphere Studio

Chapter 7. ABC Company Web site design and development

This chapter covers the design and development of the building blocks, which wecall subsites, for the ABC Web site. We heavily rely on the WebSphere StudioWizards, which generate queries, servlets, beans, HTML pages, and JavaServerPages (JSPs), which, in turn, provide most of the functionality required.

Except login and session management subsites, the development process, forthe most part, follows this series of steps:

1. Analyze the requirements for the particular subsite to determine thefunctionality and flow. For example, for new user subsite, plan to determinethe inputs, database access, validation, confirmation pages, and so forth.

2. Use the SQL WebSphere Studio SQL Wizard to generate the query to select,update, delete, or insert database records.

3. Use the WebSphere Studio Database Wizard to generate HTML pages,servlet, bean, and JSPs.

4. Modify or add the code inside the servlet or the bean where necessary. Forexample, for Order purchase subsite, you may indicate “Added code to call theAS/400 application program”.

5. Change the format of the resulting pages where necessary.

6. Create a self-contained subsite, consequently making it easier to integrate itinto the complete ABC Web site.

7. Unit test the subsite.

The WebSphere Studio tools we use should be familiar to you if you read and ranthe examples described in Chapter 3, “WebSphere Studio tools” on page 23.

To avoid confusion, we explain each step during the development of everysubsite. It may seem redundant. However, we describe the steps we took todeliver the complete and functional ABC Company’s Web site.

Before testing your work for the individual subsites, be sure to define publishingtargets to the AS/400 server. You can find instructions on setting up publishingtargets in 4.3.1, “Publishing to the AS/400 system” on page 125. You also need todownload and restore the AS/400 library (APILIB), which contains databasetables and program objects. Refer to Appendix A, “Example programs” on page405, for detailed instructions.

You can download the resulting project of the complete ABC Company Web sitein the archive form and set it up as a reference. To download, restore, and createWebSphere Studio ABC Company project, corresponding AS/400 APILIB library,and to publish the ABC Company Web site, follow instructions in Table 9.

Table 9. Setting up ABC Company Web site

Information source Information

Section Appendix A, “Example programs” onpage 405.

Downloading and running the self extractingzip file.

ABC Company Web site sample project -Readme file

Restoring AS/400 library from the save file.

© Copyright IBM Corp. 2000 157

7.1 Login and session management

Login and session management are key features to all e-commerce ande-business Web sites. It is necessary that you track the user across the site andmaintain session information.

7.1.1 Creating the login servletThe following steps are required for using the WebSphere Studio to create aservlet to validate and login a user.

7.1.1.1 Flow of the login servletFirst, you need to establish the login process:

1. The user goes to the login page.

2. The user enters a user name and password.

3. The user name and password are checked against the Web user table.

4. If the user name and password are valid, test if they have a session.

5. If they have a session, do not allocate one. They will maintain all sessionobjects.

6. If they do not have a session, allocate a session.

7. If the user name does not exist, redirect the user to the new user page.

8. If the user name exists, but the password is incorrect, redirect the user to thelogin page.

7.1.1.2 Using the WebSphere Studio servlet templateWebSphere Studio has custom templates of servlets. These were discussed in3.3.3, “Creating a page template” on page 102.

The servlet template has been setup to handle what to do on both a post and aget of a form. If you wanted to secure the servlet for one method, only you couldmove all the code from the performTask() method to either the doPost() or doGet()method. For this example, we leave the code in the performTask() method.

You need to add to the template the package to which this servlet will belong. Youalso need to add what the servlet will implement. You can also fill in all thecustom comments and the servlet information method.

Chapter 4, “Restoring the ABC CompanyWeb site sample project” on page 121.

Creating WebSphere Studio project basedon the archive file provided in the download.

Section 4.3.1, “Publishing to the AS/400system” on page 125.

Defining publishing targets to the AS/400server.

Section 4.3.3, “ABC Company Web siteconfiguration” on page 132.

Registering specific servlets in theWebSphere Application Server on theAS/400 server.

Information source Information

158 Web Enabling AS/400 Applications with IBM WebSphere Studio

7.1.1.3 Getting the parametersThe first few lines of code in the performTask() method should get parameters thatthe user enters and also parameters that exist inside the WebSphere ApplicationServer. The WebSphere Application Server parameters relate to where you wantto redirect the user to under various circumstances and also where the databaseis and what it is called. By implementing these as softcoded parameters, you canchange them at any time without having to recompile the Java source file. This isa useful technique especially if you are distributing your source code toeverybody that uses your Internet application.

7.1.1.4 Validating the user name and passwordNow you have the parameters you need to test the user name and passwordagainst the Web user table on the AS/400 system. The following code does this:

pstmt = con.prepareStatement("SELECT PWD,WCID FROM WEBUSRID.WEBUSRDB WHERELOGIN_NAME = ? ");

pstmt.setString(1, userId);rs = pstmt.executeQuery();

Normally, password-capable input fields are masked with “*******” to protect thepassword value from being seen by someone other than the primary user.Double-click on the password input field to open the Attribute dialog box. In theInput Type section, select the Password radio button, and click OK.

7.1.1.5 Creating the sessionThe next step is to create a session for this user. You can then bind information tothis user’s session and carry it across the entire site wherever the user goes.

If you set the session to false, it gets the session based on the session cookiethat the user has. If it is set to true, a session is created for the user. On the firstlogin page, you can create a new session. But, what if the user was here fiveminutes ago and their browser crashed? All of the information will be lost if youblindly give them a new session. The best way to generate a session at login iswith the following code:

HttpSession session = request.getSession(true);

7.1.1.6 Instantiating the custID beanNow that the user has been validated and has a session, you can instantiate thecustomer ID bean and bind it to the session you allocated to this user. Beans arethe cleanest way to get information from a servlet to a JSP. By instantiating thebean, you can get the custID bean into your pages at any point after login. Theonly time you will lose this information is when the session expires. The code toinstantiate the bean is given shown here:

session.putValue("custIDBean", custIDBean);session.putValue("logon.isDone", "y");

7.1.1.7 Redirecting usersOnce you have identified the user as being valid or invalid, you can determinewhere to send them. You can redirect them using the send redirect method, butbe careful of using hardcoded parameters here. If you use hardcoded parametersand change the structure of the Web site, you have to modify this servlet andrecompile. It is easiest to use hardcoded parameters in the testing stages. Youshould redirect the user to the appropriate place depending on how they went inthe login. The code to do this is shown here:

ABC Company Web site design and development 159

response.sendRedirect(loginIndex);

The code to redirect users if invalid login information provided is:

response.sendRedirect(loginError);

7.1.1.8 Finishing the servletYou now have all the pieces to complete this servlet. You also need to addexception handling. You need this to send the information to the users’ Webbrowser. The final code for the login servlet is given here:

//------------------------------------------------------------------------------// Copyright 19xx Your Company//// Owner: Your Name//// Class: JavaServlet//------------------------------------------------------------------------------

// Uncomment the next line if you want your Servlet in a package.package session;

import com.ibm.servlet.*;import com.ibm.webtools.runtime.*;

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

import java.sql.*;import com.ibm.as400.access.*;import java.util.*;

/*** JavaDoc comment for this servlet*/

public class LoginServlet extends javax.servlet.http.HttpServlet{

/* ***************************************************************************** Returns a string that contains information about the servlet** @return The servlet information*/public java.lang.String getServletInfo(){return "This servlet matches a username and password to our web database.";

}

/* ***************************************************************************** Process incoming HTTP GET requests** @param request Object that encapsulates the request to the servlet* @param response Object that encapsulates the response from the servlet*/public void doGet(javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response){performTask(request,response);

}

/* ***************************************************************************** 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(javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response){performTask(request,response);

}

/* ****************************************************************************

160 Web Enabling AS/400 Applications with IBM WebSphere Studio

* Process incoming requests for information** @param request Object that encapsulates the request to the servlet* @param response Object that encapsulates the response from the servlet*/public void performTask(javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response){

//Declaration of variablesConnection con = null;PreparedStatement pstmt = null;ResultSet rs = null;

//Reterive the parameters from the servlet.properties fileString dburl = getInitParameter("URL");String ProfId = getInitParameter("user");String ProfPwd = getInitParameter("password");String driver = getInitParameter("driver");String logout = getInitParameter("logout");String loginIndex = getInitParameter("login");String loginError = getInitParameter("loginErrorPage");

// Get the user input valuesString userId = request.getParameterValues("username")[0];String password = request.getParameterValues("password")[0];

try{

//Get the Connection to the AS/400 DatabaseClass.forName(driver);con = DriverManager.getConnection(dburl,ProfId,ProfPwd);

//Create a Statement objectpstmt = con.prepareStatement("SELECT PWD,WCID FROM APILIB.WEBUSRDB WHERE LOGIN_NAME = ?

");pstmt.setString(1, userId);

// instantiate the beans and store them so they can be accessed by the called pageABC_Company.CustIDBean custIDBean = null;custIDBean = (ABC_Company.CustIDBean)

java.beans.Beans.instantiate(getClass().getClassLoader(), "ABC_Company.CustIDBean");

//Execute the SQL query and get the resultsetrs = pstmt.executeQuery();

if (rs.next ()){if (rs.wasNull()){

//User does not exist, redirect the user to the logout pageresponse.sendRedirect(loginError);

}else{String dpwd = rs.getString("PWD");String dcid = rs.getString("WCID");// Compare the password with that in the databaseif ((password).compareTo(dpwd.trim()) == 0){

//If the password entered by user is correct then create a sessionHttpSession session = request.getSession(true);

// Assign the customer id value to the session as a parameter to be used in futuresession.putValue("custIDBean", custIDBean);session.putValue("logon.isDone", "y");custIDBean.setCustID(dcid);

//send the user to the page after the loginresponse.sendRedirect(loginIndex);

}else{

//Password failure - redirect the user to the logout pageresponse.sendRedirect(loginError);

}}

}else // rs.next if end block{

//User does not exist, redirect the user to the logout pageresponse.sendRedirect(loginError);

ABC Company Web site design and development 161

}// close the statement and the connection

pstmt.close();con.close();} catch (Exception e) {

}

}

}

7.1.2 Building the custID beanWe already been discussed how important it is to have the customer ID whereverthe user goes after logging in. The bean can be generated from the template in asimilar fashion as we did with the servlet.

The bean becomes very simple. We need one property called custID, a getter forcustID, and a setter for custID. The final code looks like the following example:

package session;

import com.ibm.webtools.runtime.*;import java.io.*;

public class CustIDBean extends java.lang.Object

{

protected java.lang.String custID = null;

public java.lang.String getCustID()

{

return custID;

}

/* ***************************************************************************** Set method for the custID property* @param value the new value for the custID property

*/public void setCustID(java.lang.String value)

{

this.custID = value;

}}

7.1.3 Building a session management servletThe key feature of developing the session management servlet is to keep itsimple. The process of session management is:

1. Check if the user has a session.2. If a session exists, display the page.3. If a session does not exist, redirect the user to the login page.

This technique works really well. However, if a user takes a long time browsingthe Web site, the session can time out and they will be redirected back to thelogin page. The user may be confused but, because we have maintained theshopping cart on the AS/400 system in a table, the information will not be lost.

162 Web Enabling AS/400 Applications with IBM WebSphere Studio

The code for this is identical to the login servlet. First, you do a create sessionwith the parameter being false. You then test the session that you created. If thesession results in being Null, the user has not been allocated and you redirectthem to the login page. If the result is not Null, the user must have a validsession.

The final step is to figure out where to send the user depending on their sessionstatus. If you allow them on the page, you need to finish the servlet with the printwriter method so the rest of the page will be displayed. If they are not allowed tobe there, they will be redirected. The redirection parameter should come from thevariables inside the WebSphere Application Server as discussed above. Thecode for the session management servlet looks like this example:

//------------------------------------------------------------------------------// Copyright 19xx Your Company//// Owner: Your Name//// Class: JavaServlet//------------------------------------------------------------------------------

// Uncomment the next line if you want your Servlet in a package.package session;import com.ibm.servlet.*;import com.ibm.webtools.runtime.*;

import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

import java.sql.*;import com.ibm.as400.access.*;import java.util.*;

/*** JavaDoc comment for this servlet*/

public class SessionCheckServlet extends javax.servlet.http.HttpServlet{

/* ***************************************************************************** Returns a string that contains information about the servlet** @return The servlet information*/public java.lang.String getServletInfo(){return "some useful information about the servlet goes here";

}

/* ***************************************************************************** Process incoming HTTP GET requests** @param request Object that encapsulates the request to the servlet* @param response Object that encapsulates the response from the servlet*/public void doGet(javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response) throws ServletException, IOException{performTask(request,response);

}

/* ***************************************************************************** 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(javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response) throws ServletException, IOException{performTask(request,response);

ABC Company Web site design and development 163

}

/* ***************************************************************************** Process incoming requests for information** @param request Object that encapsulates the request to the servlet* @param response Object that encapsulates the response from the servlet*/public void performTask(javax.servlet.http.HttpServletRequest request,

javax.servlet.http.HttpServletResponse response) throws ServletException, IOException{

String loginPage = getInitParameter("loginPage");

try{

// Step 1: Get the Session objectHttpSession session = request.getSession(false);

Object done = session.getValue("logon.isDone");

if ( done == null){response.sendRedirect(loginPage);

}else

{PrintWriter out = response.getWriter();

}} catch (Exception e) {

PrintWriter out = response.getWriter();response.sendRedirect(loginPage);

}}

}

7.2 Creating the new users subsite

This section covers the development of the new users subsite. To browse thecatalog of ABC products, or to place an order with the ABC Company, you need a“Web user profile”. If a person accessing ABC’s Web site does not have a loginID, they can fill out a form. Based on the information entered, customer and Webuser records are created.

“Web user profile” is not to be confused with the OS/400 user profile. OrdinaryWeb users (not the administrator) do not need an OS/400 user profile. AS/400database access is accomplished via one dedicated user profile, which is setupon the AS/400 system.

The creation of the new users subsite requires development efforts withinWebSphere Studio and on the AS/400 server as well.

7.2.1 New users: Development on the AS/400 serverThis section covers development efforts on the AS/400 server to support thecreation of new Web users and creation of Web user profiles for the existingcustomers.

Create a new table (physical file) on the AS/400 server to store and authenticateWeb users and to link a Web user to a customer number within an existingAS/400 application. Table creation can be accomplished using the DDS methodor an SQL statement, depending on your preference. We used the SQL methodto create the WEBUSRDB table by following these steps:

164 Web Enabling AS/400 Applications with IBM WebSphere Studio

1. Issue the Start SQL (strsql) command on an AS/400 command line to start anSQL session.

2. Issue the following SQL statement:

CREATE TABLE MYLIB/WEBUSRDB (LOGIN_NAME CHAR ( 10) NOT NULL WITH DEFAULTPRIMARY KEY, PWD CHAR ( 10) NOT NULL WITH DEFAULT, WCID CHAR ( 4) NOT NULLWITH DEFAULT UNIQUE, EMAIL CHAR ( 25) NOT NULL WITH DEFAULT, VLDTED NUMERIC(1 ) NOT NULL WITH DEFAULT 0, LOGGEDIN NUMERIC (1 ) NOT NULL WITH DEFAULT 0,DATE DATE NOT NULL WITH DEFAULT, TIME TIME NOT NULL WITH DEFAULT)

Table 10 describes the newly created WEBUSRDB physical file.

Table 10. Web user table layout (WEBUSRDB)

Access to the Catalog, Order Purchase, Order Status, and Shopping Cart pagesis granted only if users properly login into the “Registered Users Area” of the ABCWeb site. Login is successful if and only if the user specifies the login ID andpassword, which exist in the WEBUSRDB table.

There are two ways in which the records may be created (inserted) in theWEBUSRDB table:

• New users supply their personal information via the Web. Based on theinformation entered, the WEBUSRDB table record and customer record inCSTMR table are created.

• An application program is written on the AS/400 server to create records in theWEBUSRDB table for existing customers in the CSTMR table. The programhas to generate login IDs and passwords. Login IDs and passwords then haveto be communicated to the Web users.

In this redbook, we only cover the creation of the new Web user records via theWeb. Developing the program to generate WEBUSRDB table records for theexisting customers is a straight forward and trivial process, so we did not includeit in the scope of this redbook.

Field name Field description Type Length Default value

LOGIN_NAME Web user login Character 10 None

PWD Web user password Character 10 None

WCID Customer ID(link to Customer ID inCSTMR table)

Character 4 None

EMAIL EMAIL address Character 25 None

VLDTED Record Validated Flag Numeric 1 0 -- means “no”

LOGGEDIN User is logged in flag Numeric 1 0 -- means “no”

DATE Record created date Date 10 Current

TIME Record created time Time 8 Current

Primary key: LOGIN_NAME

ABC Company Web site design and development 165

7.2.2 New users: Development using WebSphere Studio toolsTo develop the new user subsite functionality, we use WebSphere Studio Wizardsand WebSphere Page Designer tools. To completely achieve desired functionality,we will alter wizard generated servlets, JSPs, and HTML files.

The following list is a conceptual representation for the steps to creating a newWeb user:

1. Obtain user information over the Web, such as, name, address, desired loginname, password, and so forth.

2. Calculate the next Customer ID to be assigned to the new Web user.

3. Insert the customer record into the CSTMR table with user-suppliedinformation and the Customer ID field equal to the result from step 2.

4. Insert the Web user record into the WEBUSRDB table with user-suppliedinformation and the Customer ID field being equal to the result from step 2.

You need to create a new WebSphere Studio project to package all the HTML,servlet, JSPs, and SQL files, which will be created during the process. Followthese steps:

1. On your PC, create a folder named subsites wherever your designateddevelopment area (drive) is, for example: c:\subsites.

Replace “c” with the workstation drive on which you want to create the project.

2. Start WebSphere Studio if it is not already started.

3. Create a new project by selecting File->New Project from the pull-downmenu:

a. Type NewUser for the project name.b. Type drive:\subsites\NewUser for the project folder.

The entries shown in the Figure 169 should resemble your entries.

The key to creating a Web user profile is getting the information from theuser and calculating the new customer number. The CSTMR table holdsmost of the information elements for the user to enter. WEBUSRDB recordsare the links between the Web user login ID and the customer ID. Wegenerate the input HTML form based on the CSTMR table.

Hint

166 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 169. New Project dialog box

3. Click OK.

WebSphere Studio creates the folder \subsites\NewUser and the project filecalled NewUser.wao. Within the project WebSphere Studio also creates theservlet folder, as illustrated in Figure 170.

Figure 170. NewUser.wao project

To accomplish the task of creating a Web user and to mostly rely on WebSphereStudio Wizards, follow these steps:

1. Create INSERT SQL for the CSTMR table using WebSphere Studio SQLWizard.

2. Create an input HTML form for the user to enter personal information to beinserted in to the CSTMR database table.

3. Create a servlet and the DB access bean to update the CSTMR databasetable on the AS/400 system.

ABC Company Web site design and development 167

4. Create resulting JavaServer Pages (JSPs) to provide feedback to the user onthe updating CSTMR table.

5. Create SELECT SQL CSTMR table, using WebSphere Studio SQL Wizard, tofind the highest customer ID used in order to calculate the next availablecustomer number.

6. Create a servlet and the DB access bean to select the highest customer IDfrom the CSTMR database table on AS/400 system using WebSphere StudioDatabase Wizard.

7. Create INSERT SQL for the WEBUSRDB table, using WebSphere Studio SQLWizard.

8. Create an input HTML form for the user to enter personal information to beinserted into the WEBUSRDB database table.

9. Create a servlet and the DB access bean to update the WEBUSRDB databasetable on the AS/400 system.

10.Create the resulting JavaServer Pages (JSPs) to provide feedback to the useron the updating WEBUSRDB table.

11.Write a simple Java code to calculate the next customer number, based on theresult of the query in step 5. Insert the code into the CSTMR insertion servlet.

12.Modify the CSTMR table update servlet to insert Java code and INSERT logicfor the WEBUSRDB table.

13.Clean up the CSTMR table based HTML input form and include user input forthe WEBUSRDB table.

14.Modify the resulting page to confirm Web user creation.

7.2.2.1 Creating INSERT SQL for the CSTMR tableIn this section, we create the INSERT statement to insert a record into theCSTMR database table using WebSphere Studio SQL Wizard. Follow thesesteps:

1. Start WebSphere Studio if it is not already started.

2. Use the SQL Wizard to create an INSERT SQL for the CSTMR table.

a. Select the project folder NewUser.

b. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

Steps 2 through 4 are accomplished using WebSphere Studio DatabaseWizard. The HTML input form, a servlet, and resulting JSPs will begenerated all at the same time based on the SQL file created in step 1.

Note on steps 2 through 4

Steps 8 through 10 are accomplished using WebSphere Studio DatabaseWizard. The HTML input form, a servlet, and resulting JSPs will begenerated all at the same time based on the SQL file created in step 7.

Note on steps 8 through 10

168 Web Enabling AS/400 Applications with IBM WebSphere Studio

c. Proceed through the tabbed windows of the wizard, specifying theinformation described in Table 11.

Table 11. Information to be entered in the SQL Wizard

Tabbed window Action explanation

Welcome Enter insertCSTMR as the name of the query. The wizard addsan .sql file in your project.

Click Next.

Logon Enter the information the wizard needs to connect to thedatabases, for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or an IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be in uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is, APILIB in this case. Click onthe library to select it, and click the Add button.

Click the OK button to return to the Tables window.

Select the Insert radio button in the Statement type.

Select APILIB.CSTMR from the list of tables shown.

Click Next.

ABC Company Web site design and development 169

3. Check in the generated file insertCSTMR.sql in the Studio Workbench.

Figure 171 and Figure 172 show our selections and parameter specifications forinsertCSTMR.sql.

Insert Select the columns that are to be part of the Insert statement.Refer to Figure 176 on page 183. For each column, enter aparameter value by clicking the Parameter button. Then, type inthe name of the parameter. For the remaining columns, enter theparameter values directly into the text filed, without using theParameter button.

Refer to Figure 171 on page 171 and Figure 172 on page 171 tosee the fields we selected and the values and parameters that wespecified.

Note: A plus sign + beside the column name designates arequired column. It means you have to supply the value or theparameter. Until you supply the values or parameters for allrequired columns, the Next button will be disabled. If you do notwant to update certain columns, supply a space for the value(for example: CDATA), and the Next button will becomeenabled.

Click Next.

SQL No action required.

This tab shows the complete SQL statement. You can copy thestatement to the clipboard to use it in another application. You canalso test the SQL statement by clicking the Run SQL button.

Click Next.

Finish Click the Finish button.

The completed SQL file should appear in the project asinsertCSTMR.sql.

Tabbed window Action explanation

170 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 171. Selecting fields and specifying parameters for insertCSTMR.sql (Part 1)

Figure 172. Selecting fields and specifying parameters for insertCSTMR.sql (Part 2)

ABC Company Web site design and development 171

7.2.2.2 Creating the HTML form, servlet, bean, and JSP for the CSTMRinsertIn this section, you create the input HTML form, the servlet, the bean, andresulting JSPs to insert a record into the CSTMR database table usingWebSphere Studio Database Wizard. Follow these steps:

1. Start WebSphere Studio if it is not already started.

2. Use the Database Wizard to create the servlet, HTML, and JSPs for insertinginto the CSTMR table:

a. Select the project folder NewUser.

b. Start the Database Wizard by selecting Tools->Wizards->DatabaseWizard.

c. Select the appropriate SQL statement, that you created in the previoussection. It should be drive:\subsites\NewUser\insertCSTMR.sql.

d. Click Next.

e. Proceed through the tabbed windows of the wizard, specifying theinformation described in Table 12.

Table 12. Information to be entered in the Database Wizard

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files will begenerated. You will need an input page to collect the data forinsertion, an output page to show the result from the query, andan error page if something unforeseen happens, and lastly:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.

Click Next.

Input Page Select all of the check boxes by clicking the Check All button.

De-select the following fields:• URL• Driver• UserID• Password

Move the fields, using the up arrow and down arrow buttons tointerchange the order of the columns, as shown in Figure 173 onpage 174.

Select the parameters by clicking on the row. Click the Changebutton to change the caption to a more meaningful name. You canalso change the field sizes. Repeat this for all parameters.

Click Next.

172 Web Enabling AS/400 Applications with IBM WebSphere Studio

3. Check all of the generated files (all files having the custInsert prefix) into theStudio Workbench. Select the NewUser folder. Then, right-click, and selectthe Check In option.

4. Publish the project to the AS/400 server. Follow the same steps as in 4.3.1,“Publishing to the AS/400 system” on page 125.

5. To test record insertion into the CSTMR table, select the custInsertInput.htmlfile to preview it. Then, right-click, and select Preview file with Netscape orInternet Explorer. When the Web browser appears, the screen appears asshown in Figure 173 on page 174.

Results Page Deselect all of the check boxes by clicking the Uncheck Allbutton.

Select the following options:• first• last• cust• and so on if you want to see some other fields

The result page will be modified later in the process.

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click Next.

Methods Click Next.

Session Select the Yes, store it in the user’s session radio button sothat the generation bean will be placed in the session for the user.This will make the bean available for future use during thesession.

Name the bean custInsertDBBean.

Click Next.

Finish Give a meaningful name to the generated source files. Click theRename button, and type custInsert into the Prefix dialog.Click OK. Note that all of the files will now have the prefix ofcustInsert.

Click the Finish button to generate the code.

The Database Wizard will generate and compile the files. Thefiles will be placed in a checked out state in the StudioWorkbench. You may receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

ABC Company Web site design and development 173

Figure 173. Testing Insertion Function into CSTMR: Input

6. Enter values for all the fields, and click the Submit button to invoke theservlet. This will instantiate the bean, which will execute the query. Theresulting JSP will be generated and sent to the client’s browser. The result isdisplayed as shown in Figure 174.

Figure 174. JSP result page of record insertion into CSTMR table

7.2.2.3 Creating a SELECT SQL for CSMTR tableIn this section, you create a SELECT statement using the WebSphere StudioSQL Wizard. Then, you modify it to select the highest customer ID, so you can

The resulting JSPs have to be modified later to indicate a WEBUSRDB tableupdates.

Note

174 Web Enabling AS/400 Applications with IBM WebSphere Studio

calculate the next customer ID to insert it into the CSTMR table and assign it to anew Web user. Follow these steps:

1. Start WebSphere Studio if it is not already started.

2. Use the SQL Wizard to create a SELECT SQL for the CSTMR table:

a. Select the project folder NewUser.

b. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

c. Proceed through the tabbed windows of the wizard by specifying theinformation described in Table 13.

Table 13. Information to be entered in the SQL Wizard

Tabbed window Action explanation

Welcome Enter selectCSTMR as the name of the query. The wizard addsan .sql file in your project.

Click Next.

Logon Enter the information the wizard need to connect to the database,for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work. Which is APILIB in this case. Click thelibrary to select it, and click the Add button.

Click OK to return to the Tables window.

Click the Select radio button in the Statement type.

Select the APILIB.CSTMR from the list of tables.

Click Next.

Join No action is required.

Click Next.

ABC Company Web site design and development 175

3. Check the generated file selectCSTMR.sql into the Studio Workbench.

7.2.2.4 Creating the servlet and DB access bean for CSTMR selectIn this section, you create the servlet and the DB access bean to get the result ofCSTMR select query, which should produce the highest customer ID found inCSTMR. Follow these steps:

1. Start WebSphere Studio if it is not already started.

2. Use the Database Wizard to create the servlet and the DB access bean:

a. Select the project folder NewUser.

b. Start the Database Wizard by selecting Tools->Wizards->DatabaseWizard.

c. Select the appropriate SQL statement, which you created in the previoussection. It should be drive:\subsites\NewUser\selectCSTMR.sql.

d. Click Next.

Columns Select only the CSTMR.CID column to be included in the outputresult.

Click the Add button.

Click Next.

Condition 1 No action is required.

Ideally, you want to select max(CID) to get the highest customerID in result. However, the wizard does not allow statements of thiskind. Thus, you are going to produce plain SELECT and modifythe SQL statement later in the DB access bean (see “Modifyingthe custSelectDBBean bean” on page 185).

Click Next.

Sort No action is required.

Click Next.

SQL No action is required.

This tab shows the completed SQL statement. You can copy thestatement to the clipboard to use in another application. Also youcan test the SQL statement by clicking the Run SQL button.

Click Next.

Finish Click the Finish button.

The completed SQL file should appear in the project asselectCSTMR.sql.

Tabbed window Action explanation

176 Web Enabling AS/400 Applications with IBM WebSphere Studio

e. Proceed through the tabbed windows of the wizard by specifying theinformation described in Table 14.

Table 14. Information to be entered in the Database Wizard

3. Check all of the generated files (all files having the custSelect prefix) into theStudio Workbench. Select the NewUser folder. Right-click, and select theCheck In option.

4. Modify the wizard’s generated SQL statement to return only one row with thehighest customer ID. You do this step later using IBM VisualAge for Java, asdescribed in 7.2.2.8, “Calculating and inserting new customer ID into theCSTMR table” on page 185.

5. Publish the project to the AS/400 server. Follow the same steps described in4.3.1, “Publishing to the AS/400 system” on page 125.

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You do not need any input or result pages, since youwill not show the results to the user, but rather use the result ofthe query to calculate the next customer ID.

Uncheck all the Pages check boxes.

Click Next.

Methods Click Next.

Session Select the Yes, store it in the user’s session radio button sothat the generation bean will be placed in the session for the user.This will make the bean available for future use during thesession.

Name the bean custSelectDBBean.

Click Next.

Finish Give a meaningful name to the generated source files. Click theRename button and type into the dialog, custSelect. Click theOK button. Note that all of the files now have the prefix ofcustSelect.

Click Finish to generate the code.

The Database Wizard generates and compiles the files. The fileswill be placed in a checked out state in the Studio Workbench.You may receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

ABC Company Web site design and development 177

7.2.2.5 Creating an INSERT SQL for WEBUSRDB tableIn this section, you create the INSERT statement to insert a record into theWEBUSRDB database table using WebSphere Studio SQL Wizard. Follow thesesteps:

1. Start WebSphere Studio if it is not already started.

2. Use the SQL Wizard to create an INSERT SQL for the WEBUSRDB table:

a. Select the project folder NewUser.

b. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

c. Proceed through the tabbed windows of the wizard by specifying theinformation described in the Table 15.

Table 15. Information to be entered in the SQL Wizard

Tabbed window Action explanation

Welcome Enter insertWEBUSR as the name of the query. The wizard addsan .sql file in your project.

Click Next.

Logon Enter the information the wizard needs to connect to thedatabase, for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user id and password; bothshould be in uppercase.

Click Connect. The wizard connects you to the specifieddatabase.

Click Next.

Tables If the Schema(s) to View window does not appear, click theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is APILIB in this case. Select thelibrary, and click the Add button.

Click the OK button to return to the Tables window.

Click the Insert radio button in the Statement type.

Select APILIB.WEBUSRDB from the list of tables shown.

Click Next.

178 Web Enabling AS/400 Applications with IBM WebSphere Studio

3. Check the generated file insertWEBUSR.sql into the Studio Workbench.

Figure 175 on page 180 shows selections and parameter specifications we usedfor insertWEBUSR.sql.

Insert Select the columns that are to be part of the Insert statement.Refer to Figure 175 on page 180. For each column, enter aparameter value by clicking the Parameter button and thentyping in the name of the parameter. For the remaining columns,enter the parameter values directly into the text filed, withoutusing the Parameter button.

Refer to Figure 175 on page 180 to see the fields we selected,values and parameters specified.

Note: A plus sign (+) beside the column name designates therequired column. It means you have to supply the value or theparameter. Until you supply the values or parameters for allrequired columns, the Next button will be disabled. If you do notwant to update certain columns, supply a space for the valueand the Next button will become enabled.

Note: Using the following workaround, we recreated theWEBUSRDB table, allowing null values for DATE and TIMEfields (see the following SQL statement). Then, we ran thewizard without specifying any values for the INSERT. After thewizard generated the .sql file, we recreated the file to havedefaults for the fields:

CREATE TABLE APILIB/WEBUSRDB (LOGIN_NAME CHAR ( 10)NOT NULL WITH DEFAULT PRIMARY KEY, PWD CHAR ( 10) NOTNULL WITH DEFAULT, WCID CHAR ( 4) NOT NULL WITHDEFAULT UNIQUE, EMAIL CHAR ( 25) NOT NULL WITHDEFAULT, VLDTED NUMERIC ( 1) NOT NULL WITH DEFAULT 0,LOGGEDIN NUMERIC ( 1) NOT NULL WITH DEFAULT 0, DATEDATE , TIME TIME )

Click Next.

SQL No action is required.

This tab shows the complete SQL statement. You can copy thestatement to the clipboard to use it in another application. Youcan also test the SQL statement by clicking the Run SQL button.

Click Next.

Finish Click Finish.

The completed SQL file should appear in the project asinsertWEBUSR.sql.

Tabbed window Action explanation

ABC Company Web site design and development 179

Figure 175. Specifying parameters and values for columns in insertWEBUSR.sql

7.2.2.6 Creating an HTML form, servlet, bean, and JSPIn this section, you create the input HTML form, the servlet, the bean and theresulting JSPs to insert a record into the WEBUSRDB database table usingWebSphere Studio Database Wizard. Follow these steps:

1. Start WebSphere Studio if it is not already started.

2. Use the Database Wizard to create the servlet, HTML, and JSPs for insertinginto the WEBUSRDB table:

a. Select the NewUser project folder.

b. Start the Database Wizard by selecting Tools->Wizards->DatabaseWizard.

c. Select the appropriate SQL statement, which you created in the previoussection. It should be drive:\subsites\NewUser\insertWEBUSR.sql.

d. Click Next.

e. Proceed through the tabbed windows of the wizard, specifying theinformation described in Table 16.

180 Web Enabling AS/400 Applications with IBM WebSphere Studio

Table 16. Information to be entered in the Database Wizard

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You need an input page to collect the data forinsertion, an output page to show the result from the query, andan error page if something unforeseen happens. You also needto:

a. Select the input page check box.b. Select the output page check box.c. Select the error page check box.

Click Next.

Input Page Select all of the check boxes by pressing the Check All button.

Deselect the following fields:• URL• Driver• UserID• Password

Note: The idea is to select all the fields, which you specified theparameter for inside the SQL. That way, you pass the parametervalue into the SQL statement via the input form.

Move the fields, using the up arrow and down arrow buttons, tointerchange the order of the columns, as shown in Figure 176 onpage 183.

Select the parameters by clicking on the row. Click the Changebutton to change the caption to a more meaningful name. Youcan also change the field sizes. Repeat this for all theparameters.

Click Next.

Results Page Deselect all of the check boxes by clicking the Uncheck Allbutton.

Select login ID and so on if you want to see some other fields.The Result page will be modified later in the process.

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click Next.

Methods Click Next.

ABC Company Web site design and development 181

3. Check all of the generated files (all files having the webUsrInsert prefix) intothe Studio Workbench. Select the NewUser folder. Right-click, and select theCheck In option.

4. Publish the project to the AS/400 server. Follow the same steps as outlined4.3.1, “Publishing to the AS/400 system” on page 125.

5. To test record insertion into WEBUSRDB table, select thewebUsrInsertInput.html file to preview it. Then, right-click and selectPreview file with Netscape or Internet Explorer. When the Web browserappears, the window shown in Figure 176 appears.

Session Select the Yes, store it in the user’s session radio button sothat the generated bean will be placed in the session for the user.This will make the bean available for future use during thesession.

Name the bean webUsrInsertDBBean.

Click Next.

Finish Give a meaningful name to the generated source files. Click theRename button, and type webUsrInsert into the dialog. ClickOK. Note that all of the files now have the prefix of webUsrInsert.

Click Finish to generate the code.

The Database Wizard generates and compiles the files. The filesare placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

182 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 176. Testing the Insertion function into WEBUSRDB: Input

6. Enter values for all the fields, and click the Submit button to invoke theservlet, which will instantiate the bean. This executes the query, and theresulting JSP is generated and sent to the client’s browser. The result isdisplayed as shown in Figure 177.

Figure 177. JSP result page of record insertion into the WEBUSRDB table

7.2.2.7 How servlets and beans generated by the DB Wizard workUp to this point, we did everything we could do using WebSphere Studio Wizards.The WebSphere Studio project should contain several files as illustrated in Figure178 on page 184.

JSPs produced at this stage are primarily for unit testing of the servlets, beans,HTMLs created by the wizards. Input HTMLs and resulting JSPs have to bemodified by Page Designer to achieve desired functionality and flow.

Note

ABC Company Web site design and development 183

Figure 178. NewUser project files generated by the wizards

Let us briefly explain how it all works. After the files are published on the AS/400WebSphere Application Server, they are ready to respond to the visitors' Web siteactivity. The following sequence shows the way these files are typicallyprocessed:

1. A Web site visitor goes to (requests) the input page.

2. The visitor submits the form, which calls the servlet with or withoutparameters.

3. The servlet calls (instantiates) the JavaBean, which implements the SQLstatement.

4. The same servlet from step 3 then calls the appropriate JSP file (based on theservlet configuration file) to dynamically create the output page based on thebean’s properties.

5. The server returns the output page to the browser.

6. You can enhance the HTML and JSP files in Page Designer and modify yourJava code using IBM VisualAge for Java or any other Java IDE. You canlaunch any of the tools directly from the Studio Workbench. When you havecompleted your enhancements and are ready, check the files in, publish, andpreview them.

The following sections explain how to enhance a servlet or a bean generated bythe Studio Wizards. They also explain how to modify HTML files to achievedesired the functionality and look.

184 Web Enabling AS/400 Applications with IBM WebSphere Studio

7.2.2.8 Calculating and inserting new customer ID into the CSTMR tableIn this section, you perform these tasks:

1. Modify the custselectDBBean.java bean to implement the SQL statement toreturn the highest customer ID from the CSTMR table. Recall that the SQL,servlet, and bean we created in 7.2.2.4, “Creating the servlet and DB accessbean for CSTMR select” on page 176, implements an SQL statement, whichsimply returns all customer IDs from the CSTMR table.

2. Modify the custinsert.java servlet to update the CSTMR table with acalculated customer ID, and not with a customer ID entered on the input HTMLscreen (custInsertInput.html).

3. Unit test insertion logic into the CSTMR table.

Modifying the custSelectDBBean beanThe beans created by Database Wizard have the following components:

• Properties: Implemented as instance variables• Setters and getters: Methods to set and get the values of the bean properties• Other methods, such as initialize(), execute(), and utility methods

A servlet calls an execute() method of the bean, which executes the initialize()method and then executes an SQL statement. The JavaServer Page (JSP)contains Java code to retrieve the bean’s properties including the SQL result viausing the getters.

The SQL statement in custSelectDBBean is a property called SQLString:

/*** Instance variable for SQL statement property*/protected java.lang.String SQLString = "SELECT APILIB.CSTMR.CID FROM

APILIB.CSTMR";

Double-click custSelectDBBean.java to edit the file. Change the SQL statementto select the maximum value of the CID column. The modified code should be asfollows:

/*** Instance variable for SQL statement property*/protected java.lang.String SQLString = "SELECT max(APILIB.CSTMR.CID) FROM

APILIB.CSTMR";

Save, check in, and compile the file to reflect the changes in the .class file. Thismethod should be used if and only if the SQL wizard is not capable of producingthe desired SQL statement.

After you create servlets (and their JavaBeans) with the wizards, you canmodify these classes in VisualAge for Java. WebSphere Studio integrates withVisualAge for Java 3.0. If you have VisualAge for Java 3.0 installed, you cannavigate between the two products. Send Java files there for editing andmaintenance, and then refresh your copy in WebSphere Studio beforepublishing. See 3.6, “VisualAge for Java 3.0 Professional Edition” on page 120.

Modifying Java files with VisualAge for Java

ABC Company Web site design and development 185

Modifying the custinsert servletIn this section, you perform the following tasks:

1. Modify the custInsert servlet to instantiate (call) custSelectDBBean to get thehighest customer ID found in the CSTMR table.

2. Insert the code into custInsert.java to calculate the next customer ID.

3. Propagate a new customer ID into custInsertDBBean, which implements anINSERT SQL statement for the CSTMR table. We propagate a new customerID value via using the setter method of custInsertDBBean.

Double-click custInsert.java to edit the file. Find the following section in thecode:

// Imports for beans used by this servlet

import NewUser.custinsertDBBean;

Since you have to instantiate (call) custSelectDBBean, you need to have accessto some of its properties and methods. The new version of the import section inthe code should look like the following example:

// Imports for beans used by this servlet

import NewUser.custinsertDBBean;import NewUser.custselectDBBean;

Next, copy the instantiation block of code from the performTask() method in thecustselect.java servlet into the performTask() method in the custinsert.java

servlet.

Double-click custSelect.java to edit the file. Find the following section in thecode as shown in Figure 179. Highlight and copy it to the clipboard.

186 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 179. Code block to be inserted into the custinsert servlet

Paste the copied block inside the performTask() method in custInsert.java rightafter the following lines:try

{HttpSession session = request.getSession(true);

Type in meaningful online documentation for the inserted block.

The following block of code executes the SQL statement and set or loads thebean properties with the result data:

// Call the execute action on the bean.custselectDBBean.execute();

This means you can use the getter method to get the result of SQL statementexecution, which is the highest customer ID currently in the CSTMR table.

Next, insert the following line of code inside the performTask() method incustinsert.java right after the first { (bracket) before the first try block. We feedthe customerId variable populated with a calculated customer ID into the INSERTSQL statement implemented by custInsertDBBean and later bywebUsrInsertDBBean:

StringBuffer customerId = new StringBuffer(4);

To get the highest customer ID found and calculate the next customer ID to beinserted into the CSTMR table, insert the code as shown in Figure 180 on page188 after the following lines:

// Call the execute action on the bean.custselectDBBean.execute();

// instantiate the beans and store them so they can be accessed by the called pageNewUser.custselectDBBean custselectDBBean = null;custselectDBBean = (NewUser.custselectDBBean)

java.beans.Beans.instantiate(getClass().getClassLoader(), "NewUser.custselectDBBean");

session.putValue("custselectDBBean", custselectDBBean);

// Initialize the bean userID property from the parameterscustselectDBBean.setUserID(getParameter(request, "userID", true, true, false, null));

// Initialize the bean password property from the parameterscustselectDBBean.setPassword(getParameter(request, "password", true, true, false,

null));

// Initialize the bean URL property from the parameterscustselectDBBean.setURL(getParameter(request, "URL", true, true, false, null));

// Initialize the bean driver property from the parameterscustselectDBBean.setDriver(getParameter(request, "driver", true, true, false, null));

// Call the execute action on the bean.custselectDBBean.execute();

ABC Company Web site design and development 187

Figure 180. Calculating the next customer ID code to be inserted into the custinsert servlet

It has to be within the try block to be in scope with bean instantiation logic. Thatway, the bean properties are visible and accessible. We convert the charactertype customer ID found into a numeric type, increment it by one, convert it backto character, and supply leading zeroes.

Now locate the following line of code:

// Initialize the bean cust property from the parameters

custinsertDBBean.setCust(getParameter(request, "cust", true, true,true, null));

This is how the servlet gets the value of cust from the input HTML page andpasses it to the bean, which in turn uses the value of cust for an SQL INSERTstatement. Modify the code to use the calculated value. Comment out the linegenerated by the wizard and type in the following statement below thecommented line:

custinsertDBBean.setCust(customerId.toString());

Unit testing customer insertionPerform the following tasks to unit test the customer insertion:

1. Compile the files you modified.

2. Publish the project to the AS/400 server. Follow the same steps explained in4.3.1, “Publishing to the AS/400 system” on page 125.

3. Select the custInsertInput.html file. Then, right-click, and select Preview filewith Netscape or Internet Explorer.

4. When the Web browser appears, complete the form, and click the Submitbutton as illustrated in Figure 181.

// Calculate new customer number by getting the custselectDBBean cust property

String cust = custselectDBBean.getAPILIB_CSTMR_CID(0);

java.math.BigInteger custn = new java.math.BigInteger(cust);custn = custn.add(new java.math.BigInteger("1"));String newcust = custn.toString();

for(int i=0; i < 4 - newcust.length(); i++){

customerId.append('0');}customerId.append(newcust);

188 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 181. Unit testing by calculating and inserting a new customer ID into CSTMR: Input

5. The result page should reflect the changes. Notice the cust ID in Figure 182 isequal to “3407”, even though, we have not entered the value for the customeron the input page (it would not matter even if we entered the value). The resultis “3407” because our highest customer ID in the CSTMR table used to be“3406”.

Figure 182. Unit testing by calculating and inserting a new customer ID into CSTMR: Result

7.2.2.9 Inserting a new customer ID into the WEBUSRDB tableIn this section, you perform these tasks:

1. Modify the custInsert.java servlet to include the WEBUSRDB table INSERTlogic. Supply the value of the calculated customer ID for INSERT SQL for theWEBUSRDB table.

2. Unit test insertion logic into WEBUSRDB table.

Modifying the custInsert servletIn this section you propagate a new customer ID into webUsrInsertDBBean,which implements an INSERT SQL statement for the WEBUSRDB table. Youpropagate a new customer ID value using the setter method ofwebUsrInsertDBBean.

ABC Company Web site design and development 189

Double-click custInsert.java to edit the file. Find the following section in thecode:

// Imports for beans used by this servlet

import NewUser.custinsertDBBean;import NewUser.custselectDBBean;

Since you have to instantiate (call) webUsrInsertDBBean, you need access to someof its properties and methods. The new version of the import section in the codeshould look like the following example:

// Imports for beans used by this servlet

import NewUser.custinsertDBBean;import NewUser.custselectDBBean;import NewUser.webusrinsertDBBean;

Next, you copy the instantiation block of code from the performTask() method inthe webUsrInsert.java servlet into the performTask()method in the custInsert.java

servlet.

Double-click webUsrInsert.java to edit the file. Find the following section in thecode, shown in Figure 183, and highlight and copy it to the clipboard.

190 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 183. The webuserinsert.java code segment to be copied into the custinsert servlet

Paste the copied block inside the performTask() method in custInsert.java rightafter the following line:

customerId.append(newcust);

and before these lines:

// instantiate the beans and store them so they can be accessed by the calledpage

NewUser.custInsertDBBean custInsertDBBean = null;

Type in meaningful online documentation for the inserted block. As soon as thenext customer ID is calculated, insert the record into WEBUSRDB (thewebUsrInsertDBBean.execute() method is run and we instantiate (call)custInsertDBBean to insert the record into the CSTMR table. However, you needto feed the calculated customer ID, instead of the one entered on the input HTMLform.

// instantiate the beans and store them so they can be accessed by the called pageNewUser.webusrinsertDBBean webusrinsertDBBean = null;webusrinsertDBBean = (NewUser.webusrinsertDBBean)

java.beans.Beans.instantiate(getClass().getClassLoader(), "NewUser.webusrinsertDBBean");

session.putValue("webusrinsertDBBean", webusrinsertDBBean);

// Initialize the bean userID property from the parameterswebusrinsertDBBean.setUserID(getParameter(request, "userID", true, true, false, null));

// Initialize the bean password property from the parameterswebusrinsertDBBean.setPassword(getParameter(request, "password", true, true, false, null));

// Initialize the bean URL property from the parameterswebusrinsertDBBean.setURL(getParameter(request, "URL", true, true, false, null));

// Initialize the bean driver property from the parameterswebusrinsertDBBean.setDriver(getParameter(request, "driver", true, true, false, null));

// Initialize the bean cust property from the parameters

// webusrinsertDBBean.setCust(getParameter(request, "cust", true, true, true, null));webusrinsertDBBean.setCust(customerId.toString());

// Initialize the bean pwd property from the parameters

webusrinsertDBBean.setPwd(getParameter(request, "pwd", true, true, true, null));

// Initialize the bean loginId property from the parameters

webusrinsertDBBean.setLoginId(getParameter(request, "loginId", true, true, true, null));

// Initialize the bean email property from the parameters

webusrinsertDBBean.setEmail(getParameter(request, "email", true, true, true, null));

// Call the execute action on the bean.webusrinsertDBBean.execute();

ABC Company Web site design and development 191

Find the following line of code:

// Initialize the bean cust property from the parameters

webUsrInsertDBBean.setCust(getParameter(request, "cust", true, true,true, null));

This is how the servlet gets the value of cust from the input HTML page andpasses it to the bean, which in its turn uses the value of cust for the SQL INSERTstatement. Modify the code to use the calculated value (see 7.2.2.8, “Calculatingand inserting new customer ID into the CSTMR table” on page 185). Commentout the line generated by the wizard and type in the following line below thecommented line:

webUsrInsertDBBean.setCust(customerId.toString());

Unit testing Web user insertionCompile and check in the files you modified. Since Web-user insertion logicshould occur at the same time with new customer record insertion, you cannotunit test just the Web user function. Instead, in the following section, you modifycustInsertInput.html using Page Designer to include fields and parameters forWeb-user insertion logic

7.2.2.10 Combining CSTMR and WEBUSRDB input HTML formsIn this section, you perform these tasks:

1. Modify the custInsertInput.html input form to include input elements from thewebUsrInsertInput.html form.

2. Test insertion logic in the CSTMR and WEBUSRDB tables.

Modifying the custInsertInput.html input formWe merge webUsrInsertInput.html into custInsertInput.html and not the other wayaround. When the Submit button is clicked, the custInsert servlet is called, whichis where you calculate new customer ID and insert the input information into theCSTMR and WEBUSRDB tables. Also, the WEBUSRDB table contains fewerdata elements to be inserted in comparison to the CSTMR table.

Open custInsertInput.html and webUsrInsertInput.html for editing in PageDesigner. Refer to Figure 184.

192 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 184. Combining HTML input forms to generate a new Web user

Follow this easy method:

1. Delete unnecessary table rows from custInsertInput.html, for example, cust.

2. Add new empty rows into the table inside custInsertInput.html.

3. Type the description (left table column cells) in the newly created rows.

4. Copy the text entry area (right table-column cells) from the table insidewebUsrInsertInput.html into the appropriate right-most cell inside the tableinside custInsertInput.html.

During the copy and paste, all the properties and attributes of the field arepreserved.

Figure 185 on page 194 shows combined forms.

ABC Company Web site design and development 193

Figure 185. Combined HTML input forms to generate a new Web user

If you double-click on the text entry area, you can examine the field name whichis used by the beans and the servlets (Figure 186).

Figure 186. Attributes of the name ‘pwd’

194 Web Enabling AS/400 Applications with IBM WebSphere Studio

Unit testing the new Web user creationPerform the following tasks to unit test the Web user insertion:

1. Compile the files you modified.

2. Publish the project to the AS/400 server. Follow the same steps outlined in4.3.1, “Publishing to the AS/400 system” on page 125.

3. Select the custInsertInput.html file. Then right-click, and select Preview filewith Netscape or Internet Explorer.

4. When the Web browser appears, complete the form, and click Submit, asillustrated in Figure 187.

Figure 187. New Web user creation test: Input

The result page should reflect the changes as illustrated in Figure 188.

Figure 188. New Web user creation test: Result

Examine the CSTMR and WEBUSRDB tables on the AS/400 system to verifyrecord insertion.

ABC Company Web site design and development 195

7.2.2.11 Creating a final resulting JSPIt is always a good idea to provide a confirmation (result) page after a criticalaction has been performed. In our case, we provide confirmation on the INSERTsdatabase into the CSTMR and WEBUSRDB tables.

In this section, you perform these tasks:

1. Modify the custInsertResult.jsp result page to also include elements fromwebUsrInsertResult.jsp, the result page of the record insertion intoWEBUSRDB.

2. Test the insertion logic into the CSTMR and WEBUSRDB tables and theconfirmation JSP result page.

Modifying the custInsertResult.jspWe merge webUsrInsertResult.jsp into custInsertResult.jsp. JSPs, which wegenerated with the help of the Database Wizard. JSPs contain HTML bean tags.

If the bean is instantiated, then the bean tags allow access to the bean’sproperties. WebSphere Studio Page Designer simplifies JSP enhancements andmodifications by letting you drag and drop the entire bean or select the bean’sproperties to be placed on the JSPs. Let us examine the WebSphere Studio PageDesigner abilities within our scenario.

Open custInsertResult.jsp and webUsrInsertResult.jsp for editing in PageDesigner. Refer to Figure 189.

Figure 189. Merging custInsertResult.jsp and webusrinsertResult.jsp

196 Web Enabling AS/400 Applications with IBM WebSphere Studio

The first “J” (in green color) in custInsertResult.jsp represents the bean tag. The“J” inside the table rows with “!” on each sides represents bean’s properties to bedisplayed on the page. Exclamation marks on each side represent meta tags withdescriptions. Refer to the Figure 190 and Figure 191 on page 198 to see theactual source for the bean tag and Page Designer dialog box representing thebean tag.

Figure 190. Actual source of the bean tag inside the custInsertResult.jsp

If you double-click on the first “J” inside the Page Designer, you get the bean tagrepresented via the dialog box shown in Figure 191 on page 198.

ABC Company Web site design and development 197

Figure 191. Bean tag inside the custInsertResult.jsp represented in the dialog box

The “J” inside the table rows (refer to Figure 189 on page 196) represents thefollowing actual source line. In the example, the custInsertDBBean.getCust() gettermethod is called, which results in the customer ID being displayed on the page:

<!--METADATA type="DynamicData" startspan <WSPX:PROPERTYproperty="custinsertDBBean.cust">--><%=custinsertDBBean.getCust()%><!--METADATA type="DynamicData" endspan-->

Since custInsertResult.jsp should include webUsrInsertDBBean properties, youhave to insert the webUsrInsertDBBean tag first. There are three ways to do it:

• Select Insert->JSP Tags->Insert a Bean from the pull-down menu.

• Drag and drop a bean from Studio Workbench onto Page Designer where youare editing custInsertResult.jsp.

• Copy the “Js” from webUsrInsertResult.jsp and paste it intocustInsertResult.jsp.

The reason you open both JSPs for editing is to use the copy and paste method.After copying and pasting, save custInsertResult.jsp and close the PageDesigner. Open the Page Designer with custInsertResult.jsp. Figure 192 showsthe result of the copy and paste action.

Refer to 3.3, “Page Designer” on page 88, for an in-depth demonstration ofPage Designer capabilities.

Note

198 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 192. Copying and pasting webUsrInsertResult.jsp elements into custInsertResult.jsp

The first “J” is the bean tag for custInsertDBBean, which is needed to display thebean’s properties. The next “J” is the bean tag for webUsrInsertDBBean. At thispoint, you have not yet used the Page Designer feature to select a bean’sproperty to be placed, and displayed, on the page. Let us reformat the screen todemonstrate the feature.

Position your cursor after the phrase “The login Id:”. Select Insert->DynamicElements->Property Display... (Figure 193 on page 200).

ABC Company Web site design and development 199

Figure 193. Selecting bean properties to be displayed on the JSP

Click Browse to see the available properties. Expand webUsrInsertDBBean toselect the loginID property to be placed on the page (Figure 194).

Figure 194. Selecting the loginId property of the webusrinsertDBBean

The loginID property is placed on the page in the location where cursor is. Theproperty is represented by “J” (green box). If you double-click on the “J” you justinserted, a display like the example in Figure 195 appears.

200 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 195. Examining the loginId property inserted into JSP with Page Designer

Now give the page a more user-friendly look. Start by removing the tablescreated by the wizards, and then inserting first and last names, which are theproperties of custInsertDBBean (Figure 196).

Figure 196. custInsertResult.jsp final look

Double-click “J” to investigate which property of which bean it represents.

Save custInsertResult.jsp.

Publish the project to the AS/400 server. Follow the same steps outlined in 4.3.1,“Publishing to the AS/400 system” on page 125.

ABC Company Web site design and development 201

7.2.2.12 Testing the resulting JSPPerform the following tasks to test the resulting JSP:

1. Select the custInsertInput.html file. Then, right-click, and select Preview filewith Netscape or Internet Explorer.

2. When the Web browser appears, complete the form (make sure to supply adifferent login ID to avoid duplicate keys in the WEBUSRDB table). Click theSubmit button (Figure 197).

Note: We deal with the potential duplicate keys error in the next section.

Figure 197. custInsertResult.jsp test: Input form

The result page should reflect the changes illustrated in Figure 198.

202 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 198. custInsertResult.jsp test: Resulting page

3. Examine the CSTMR and WEBUSRDB tables on the AS/400 system to verifyrecord insertion.

7.2.3 Input data validationHave you ever heard the phrase “Garbage in, garbage out”? Data validation playsan important role in preserving data accuracy and assuring the integrity of yourdatabases. There are two types of data validation: client side (primitive) andserver side (business rules). Client side validation is performed within thebrowser without making any request to the server. Since we use a thin clientmodel, there is no business logic on the client. To ensure business rules arefollowed, input is sent to the server for analysis and feedback is provided via theJSP to the client.

Examples of primitive validation ensure a specific data type, such as numericentry, enforcing mandatory entry, enforcing lower or upper casing, and so forth.Business rules validation means ensuring data entry does not break any businessrules built into the enterprise applications and databases.

For the ABC Company, you perform the following steps:

1. On the client side, complete these tasks:

a. Enforce mandatory entries.

b. Enforce uppercase on the input form.

c. In some cases, specify field lengths according to the server side database.

2. On the server side, ensure that you do not end up with WEBUSRDB recordswithout associated CSTMR records and vice versa (preserving referentialintegrity).

The validation we perform may not be complete. Our goal is to illustrate theconcept and different methods that you can use to perform proper andcomplete validation.

Note

ABC Company Web site design and development 203

We decided to use JavaScript to perform validation within the browser on theclient’s side. Refer to the following Web sites for more information on JavaScript.

• JavaScript Guide:http://developer.netscape.com/docs/manuals/communicator/jsguide4/index.htm

• JavaScript Reference:http://developer.netscape.com/docs/manuals/communicator/jsref/index.htm

7.2.3.1 Validating new user inputIn this section, you modify the custInsertInput.html form to perform the followingtasks:

1. Change users’ input to uppercase.2. Enforce mandatory entries on required fields.3. For some fields, specify field length according to the server side database.

You will use JavaScript functions, form objects, and operators to do most of thework. Field lengths are changed using the Page Designer Attribute dialog box.

Changing user input to uppercasePerform the following tasks to change the user input to uppercase:

1. Open custInsertInput.html for editing within Page Designer.

2. Double-click on the text entry area of the “first” Name field. You should see adisplay like the example in Figure 199.

204 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 199. Changing user-supplied text to uppercase

3. Click the Extended button to access the Extended Attributes dialog box.

4. Click the Event tab to specify an event and associated action.

5. In the Event list, find and highlight the OnChange event as illustrated in Figure200 on page 206.

6. Click the Add button to add the OnChange event to the Event-Action list.

ABC Company Web site design and development 205

Figure 200. Selecting the OnChange event to uppercase entered text

7. Highlight the OnChange event within the Event-Action pane (center), and typethe following text in the Script entry field, as illustrated in Figure 201:

this.value=this.value.toUpperCase();

8. Click Configure.

9. Continue clicking OK until you are back to Page Designer.

Let us analyze the code. We use JavaScript to retrieve the input field’s value.Since we are working at the field level, this means this particular input fieldobject. If you specify this at the form level, it would mean this form object. Then,apply the JavaScript function toUpperCase(); to change the fields value.

Figure 201. Supplying an action for the OnChange event

Once you reach Page Designer, investigate the actual HTML source:

206 Web Enabling AS/400 Applications with IBM WebSphere Studio

1. Click on HTML Source tab.

2. Refer to Figure 202 to see the code in uppercase in the first input field usingthe OnChange event.

Figure 202. HTML source showing uppercasing the first name field with the onchange event

Up to this point, we showed you how to put the input values in uppercase throughthe dialog boxes. To apply the uppercase function to the rest of the fields, thecopy and paste method can be used while within the HTML source view in PageDesigner:

1. Highlight the following code segment:

onchange="this.value=this.value.toUpperCase();"

2. Copy and paste the code segment to the end of the INPUT HTML construct(between the <> symbols) for other input fields. We applied the uppercasefunction to the following fields:

• first• init• last• city• state• login Id• password

Recall that uppercasing occurs within the browser on the client, so you do nothave to click the Submit button to test your work.

Enforcing mandatory entries in the required fieldsSome information elements are critical, without which database integrity cannotbe achieved. The required fields in our example are:

• first• last• addr1• city• state

ABC Company Web site design and development 207

• zip• login Id• password

We create JavaScript function to evaluate field values. If the required field is notpopulated, the alert message box is displayed and the form is not submitted. Thefunction is called when the user presses the Submit button. We specify thefunction call in the OnClick event for the Submit button, and we pass this.formobject.

The validation is performed within the browser on the client’s machine and is notsubmitted to the server. Here are the steps to invoke the validate() function andthe function code itself:

1. Open custInsertInput.html in Page Designer for editing.

2. Double-click the Submit button to change the attributes to insert the validate()function call and function code.

3. Click the Extended button to open the Extended Attributes dialog box.

4. Click the Event tab to specify an event and associated action.

5. In the Event list, find and highlight the OnClick event.

6. Click the Add button to add an OnClick event to the Even-Action list.

7. Highlight the OnClick event within the Event-Action pane (center), and typethe following statement in the Script entry field (Figure 203).

return validate(this.form);

8. Click Configure.

9. Click Script. The window shown in Figure 203 should open.

Figure 203. Inserting validate() function into custInsertInput.html (Part 1)

10.Highlight the text shown in Figure 204.

208 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 204. Inserting the validate() function into custInsertInput.html (Part 2)

11.Type or paste the validate() function on top of the highlighted text in step 10(Figure 205).

Figure 205. The validate() function inserted into custInsertInput.html

12.Click the OK button all the way back to Page Designer. Then savecustInsertInput.html, and close Page Designer.

ABC Company Web site design and development 209

The code and HTML tags shown in Figure 206 were created by Page Designer.

Figure 206. JavaScript code and HTML tags created by Page Designer inside custInsertInput.html

Let us go through the function code shown in the Figure 205 on page 209 andFigure 206.

The following line inside custInsertInput.html contains the validate() function call:

<INPUT type="submit" name="Submit" id="Submit" value="Submit" onclick="returnvalidate(this.form);">

When the user clicks the Submit button, the onClick event is monitored. As aresult of the onClick event, the validate() function is called and the form object ispassed. Notice we call the function using the return keyword. The return keywordgives us the ability to allow or disallow the form to be submitted (sent to theserver). Here is how it works. When the validate() function runs and returns“false”, the form is not submitted (sent to the server). If we omit the return

keyword, the form is submitted regardless of whether the function returns true orfalse.

Let us comment on the validate() function itself. We accept the passed parameteras theform. This parameter is an object with properties. The set of properties alsoincludes the fields on the form and their associated values. We are using a “giant”if...else... construct to go through the required field values, trying to find onewith value less-than blanks, which would mean the field does not contain anytext. Notice we declared return_var to contain true or false values. If all therequired fields have a value, then the function returns true, which causes the formto be submitted. However, if at least one of the fields does not have a value, the

210 Web Enabling AS/400 Applications with IBM WebSphere Studio

function displays an alert window with the proper error message, returns false,and the form is not submitted. The form is submitted to the server if and only if thefunction returns true.

The validate() function can be enhanced to perform many other checks, whichcould be done before the form is submitted. Normally, this kind of function is usedto clean up the user input, stop bad data from being submitted to the server, anddo simple calculations. You should not try to let a function like this evaluate theinput for certain business rules. Keep as many business rules and logic aspossible on the server.

Specifying a specific field lengthDuring the page creation using WebSphere Studio Database Wizard, inputcapable field sizes are given the default number of characters, which may not suityour particular environment. To limit the input to a certain number of characters tocomply with backend database attributes, text entry capable fields may bechanged. In our example, fields, such as middle initial and state fields, have beenchanged to a particular size, CSTMR table attributes. Field sizes can be changedduring page creation using the wizard or using the Page Designer. The InputPage tab in the Database Wizard allows modification of the field’s size. SeeFigure 207 for an example of the dialog box, which appears when the input field ishighlighted and the Change button is clicked.

Figure 207. Changing the size of the state field inside the DB wizard

Inside the Page Designer, you can change a field size via the Attributes dialogbox as illustrated in Figure 208 on page 212. You can even change columns andmaximum length values.

ABC Company Web site design and development 211

Figure 208. Changing field size inside the Page Designer

Cleaning up and testing validation functionality of custInsertInput.htmlIn this section, you clean up custInsertInput.html and perform data validationtesting. Perform the following tasks:

1. Open custInsertInput.html for editing inside the Page Designer.

2. Enter meaningful field captions in the left-most table column.

3. Change the field captions color to red if the field has a mandatory entry.

4. Change the heading of the form as well. The final page is illustrated in Figure209.

212 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 209. Cleaning up the custInsertInput.html

5. Save custInsertInput.html.

6. Publish the project to the AS/400 server. Follow the same steps outlined in4.3.1, “Publishing to the AS/400 system” on page 125.

Unit testing data validation functionalityPerform the following tasks to test data validation functionality:

1. Select the custInsertInput.html. Then, right-click and select Preview file withNetscape or Internet Explorer.

2. When the Web browser appears, enter information in all the fields except theLogin ID and e-mail fields.

3. Verify that the uppercase function is working. You should get the alertmessage box shown in Figure 210 on page 214.

ABC Company Web site design and development 213

Figure 210. Alert message box to indicate a mandatory field entry

7.2.3.2 Data validation summaryThe validation techniques we have demonstrated in this section apply mostly tothe client’s side data validation. JavaScript language can be used to evaluate thetype of input (character or numeric), field’s value, change the casing, and soforth. When using JavaScript, make sure to test the function on as manybrowsers as possible. Not all the Web browsers fully support JavaScriptfunctions.

If the input form passes the primitive validation, it is submitted to the server. Theservlet custInsert.class starts. Recall, first it issues a query to find last andcalculates the next customer number to assign to a new user. Then, we insert therecord into WEBUSRDB table using the new customer ID we calculated. And,finally, we insert the record into CSTMR table. Login ID entered by a new user isthe key field of the WEBUSRDB. Ideally, we should have made sure that this loginID was not used by another user prior to issuing the INSERT SQL statement. Inthis example, if login was found, JSP would have been sent to the user askingthem to specify a new login ID. That would constitute server-side validation.

Since we demonstrated the power of SQL Wizard and Database Wizard, whichgenerate SQL statements, servlets, and beans, we do not check for duplicatelogin IDs first in this case. Instead, we rely on the SQL exception that isgenerated when it tries to insert the record with duplicate key. Database, SQL,database manager, connection manager, and other kinds of exceptions stop theprocess within a try {} block and fall into the catch {} block. Recall that we try toinsert the record into the WEBUSRDB table prior to inserting the record into theCSTMR table. Therefore, having a customer ID inside the WEBUSRDB table,points to a customer record, which does not exist yet. It is considered badpractice, and we are not arguing that the way ABC Web site works is the bestpossible. However, we accomplish the point that: if a duplicate login ID is found

214 Web Enabling AS/400 Applications with IBM WebSphere Studio

(SQL exception generated), the customer record is not inserted as well. Itbecomes a pseudo transaction, in which a principle all or nothing is preserved.Even though a newly created WEBUSRDB table record points to a nonexistentCSTMR table record, it lasts only a split second. The probability that the CSTMRrecord will not get inserted is low and negligible. That is how we ensure databasereferential integrity. Needless to say, we did not perform “new user” functionalitytests with thousands of clients at the same time. Clearly it is outside of the scopeof the book, which focuses on WebSphere tools, concepts, and Web-site creationmethodology.

7.2.4 New user creation summary and final testingThis section concludes new user subsite development. You had a chance toexperience the power of SQL Wizard and Database Wizards, and how easy it isto modify wizard-generated code and pages. You also worked with Page Designertool to modify the look and feel of the pages, insert JavaScript functions, drag anddrop the beans, and so forth. We found WebSphere Studio as an adequate set oftools to do the Web site development, generate simple HTML pages, servlets,database access beans, and JSPs. In 8.5, “Tying it all together” on page 389, and8.7, “Task summary and integration testing” on page 402, we demonstrate how totie different subsites into a complete Web site and perform integration testing.

7.3 Creating the catalog subsite

The catalog subsite allows you to display the catalog to your customer. There areseveral ways in which you can deliver information. But, for this book, we havelimited it to view all catalog items and view items by price range.

7.3.1 Creating the catalog projectTo build the catalog subsite, you need to create a new project. Follow the stepsbelow to create the new catalog project folder:

1. Start WebSphere Studio if not already started.

2. Create a new project by selecting File->New Project from the pull-downmenu.

3. Type Catalog for the project name.

4. Type drive:\subsites\Catalog for the project folder.

5. Select <none> for project template.

A new project is created called Catalog.

7.3.2 Creating the SQL queries for the catalog subsiteBefore beginning this section, you should already be familiar with the SQL Wizarddiscussed in 3.2, “Studio Wizards” on page 28.

7.3.2.1 Selecting all items from the catalogPerform the following tasks that run the SQL Wizard to create an SQL statementthat selects all items from the catalog:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder Catalog.

ABC Company Web site design and development 215

3. Start the SQL Wizard by selecting Tools ->Wizards ->SQL Wizard.

4. Proceed through the tabbed windows of the wizard, and specify theinformation described in Table 17.

Table 17. Creating a select all query for the catalog

Tabbed window Action explanation

Welcome Enter viewAllCatalogItems as the name of the query. Thewizard adds an .sql file in your project.

Click Next.

Logon Enter the information the wizard needs to connect to thedatabase, for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be in uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is APILIB in this case. Click on thelibrary to select it, and click the Add button.

Click OK to return to the Tables window.

Click the Select radio button in the Statement type.

Select the APILIB.ITEM from the list of tables shown.

Click Next.

Join No action is required.

Click Next.

Columns You only want to provide to the user information concerning theproduct name and price.

Select only the ITEM.IName and ITEM.IPrice columns to beincluded in the output result.

Click the Add button.

Click Next.

216 Web Enabling AS/400 Applications with IBM WebSphere Studio

5. Check the generated file viewAllCatalogItems.sql into the Studio Workbench.Select the Catalog folder. Then, right-click, and select the Check In option.

7.3.2.2 Selecting by price range from the catalogPerform the following tasks that run the SQL Wizard to create an SQL statementthat selects items from the catalog by price range:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder Catalog.

3. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

4. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 18.

Table 18. Creating a select by price range query for the catalog

Condition 1 All items will be displayed so there is no condition to be entered.

Click Next.

Sort You want to display all the products in alphabetical order.

Select the APILIB.ITEM.INAME. Click the Add button to add itto our columns to sort on the list box. Make sure the sort order isset to Ascending.

Click Next.

SQL No action required.

This tab shows the complete SQL statement. You can copy thestatement to the clipboard to use it in another application. Alsoyou can test the SQL statement by clicking the Run SQL button.

Click Next.

Finish Click the Finish button.

The completed SQL file should appear in the project asviewAllCatalogItems.sql.

Tabbed window Action explanation

Welcome Enter viewByPriceCatalogItems as the name of the query. Thewizard will add an .sql file in your project.

Click Next.

Tabbed window Action explanation

ABC Company Web site design and development 217

Logon Enter the information the wizard needs to connect to thedatabase, for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be in uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window find the AS/400 library withwhich you want to work, which is APILIB in this case. Click on thelibrary to select it, and click the Add button.

Click the OK button to return to the Tables window.

Click the Select radio button in the Statement type.

Select the APILIB.ITEM from the list of tables shown.

Click Next.

Join No action required.

Click Next.

Columns You only want to provide to the user information concerning theproduct name and price.

Select only the ITEM.IName and ITEM.IPrice columns to beincluded in the output result.

Click the Add button.

Click Next.

Tabbed window Action explanation

218 Web Enabling AS/400 Applications with IBM WebSphere Studio

Condition 1 Select IPrice in the Columns list box. Select the operator to be isgreater than or equal to (>=). Click in the top values field, andclick the Parameter button.

In the Create a new parameter dialog box, enter the variablename minPrice, and click OK.

Now that we have the minimum price condition is set, you need toadd the maximum price. Click the Find on another columnbutton.

Click Next.

Condition 2 Make sure the radio button Find fewer rows (AND) at the top isselected.

Select IPrice in the Columns list box. Select the operator to be isless than or equal to (<=). Click in the top values field, and clickon the Parameter button.

In the Create a new parameter dialog box, enter the variablename maxPrice, and click OK.

You now have your condition to select a price range.

Click Next.

Sort You want to display all the products in order of cheapest to mostexpensive.

Click APILIB.ITEM.IPRICE. Now, click the Add >> button to addit to our columns to sort on list box. Make sure the sort order is setto Ascending.

Click Next.

SQL No action is required.

This tab shows the complete SQL statement. You can copy thestatement to the clipboard to use it in another application. You canalso test the SQL statement by clicking the Run SQL button.

If you choose to test the SQL statement by pressing the Run SQLbutton, you are prompted for two parameters in the SpecifyParameter Value(s) window. For the first parameter, type 2.00and 20.00 for the second parameter. The result should be allitems in the catalog that have the price range between or equal to$2.00 and $20.00. Click OK.

Click the Next button to go to the next tab.

Finish Click the Finish button.

The completed SQL file should appear in the project asviewByPriceCatalogItems.sql.

Tabbed window Action explanation

ABC Company Web site design and development 219

5. Check the generated file viewByPriceCatalogItems.sql into the StudioWorkbench. Select the Catalog folder. Then, right-click, and select the CheckIn option.

7.3.2.3 Selecting a single item from the catalogPerform the following tasks that run the SQL Wizard to create a SQL statementthat selects a single item from the catalog:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder Catalog.

3. Start the SQL Wizard by selecting Tools ->Wizards ->SQL Wizard.

4. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 19.

Table 19. Creating a query to select a single item from the catalog

Tabbed window Action explanation

Welcome Enter viewCatalogItem as the name of the query. The wizardadds an .sql file in your project.

Click Next.

Logon Enter the information the wizard needs to connect to thedatabase, for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password. Bothshould be in uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window find the AS/400 library withwhich you want to work, which is APILIB in this case. Click on thelibrary to select it, and click the Add button.

Click OK to return to the Tables window.

Click the Select radio button in the Statement type.

Select the APILIB.ITEM from the list of tables shown.

Click Next.

Join No action is required.

Click Next.

220 Web Enabling AS/400 Applications with IBM WebSphere Studio

5. Check the generated file viewCatalogItem.sql into the Studio Workbench.Select the Catalog folder. Then, right-click, and select the Check In option.

7.3.2.4 Inserting the selected item into the shopping cartPerform the following tasks that run the SQL Wizard to create an SQL statementthat inserts the selected items into the shopping cart:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder Catalog.

3. Start the SQL Wizard by selecting Tools ->Wizards ->SQL Wizard.

Columns Click the Select All button. Hold down the Control key, and clickon IDATA to deselect it.

Click the Add button.

Click Next.

Condition 1 Click IID in the columns list box. Click the operator is exactlyequal to. Click in the top Values fields, and click the Parameterbutton.

In the Parameter dialog box, type prodID, and click the OKbutton.

Click Next.

Sort No action is required.

There is no sort criteria for the single item.

Click Next.

SQL No action is required.

This tab shows the complete SQL statement. You can copy thestatement to the clipboard to use it in another application. You canalso test the SQL statement by clicking the Run SQL button.

If you choose to test the SQL statement by clicking the Run SQLbutton, type 000001 for the test condition type. You should see allthe product information for that product ID. Click the OK button.

Click Next.

Finish Click Finish.

The completed SQL file should appear in the project asviewCatalogItem.sql.

Tabbed window Action explanation

ABC Company Web site design and development 221

4. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 20.

Table 20. Creating an insert catalog item into shopping cart query

Tabbed window Action explanation

Welcome Enter addToCart as the name of the query. The wizard adds an.sql file in your project.

Click Next.

Logon Enter the information the wizard needs to connect to thedatabase, for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be in uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is APILIB in this case. Click on thelibrary to select it, and click the Add button.

Click the OK button to return to the Tables window.

Click the Insert radio button in the Statement type.

Select APILIB.SHPCART from the list of tables shown.

Click Next.

Insert Select the columns that are to be part of the Insert statement. Foreach column, enter a parameter value by clicking the Parameterbutton and then typing in the name of the parameter:

• For SCID, type custID• For SDSC, type prodName• For SIID, type prodID• For SPRC, type prodPrice• For SQTY, type prodQty

Click Next.

222 Web Enabling AS/400 Applications with IBM WebSphere Studio

5. Check the generated file addToCart.sql into the Studio Workbench.

7.3.3 Creating the Web pages for the catalog subsiteBefore beginning this section, you should already be familiar with the DatabaseWizard that was discussed in 3.2, “Studio Wizards” on page 28.

7.3.3.1 Displaying all items from the catalogPerform the following tasks that run the Database Wizard to create the HTMLform, the servlet, the bean, and resulting JSPs to select all records from the ITEMdatabase table:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder Catalog.

3. Start the SQL Wizard by selecting Tools->Wizards->Database Wizard.

4. Select the appropriate SQL Statement, which you created in 7.3.2.1,“Selecting all items from the catalog” on page 215. It should bedrive:\subsites\NewUser\viewAllCatalogItems.sql.

5. Click Next.

6. Proceed through the tabbed windows of the wizard, and specify theinformation described in Table 21 on page 224.

SQL No action is required.

This tab shows the complete SQL statement. You can copy thestatement to the clipboard to use it in another application. You canalso test the SQL statement by clicking the Run SQL button.

Click Next.

Finish Click Finish.

The completed SQL file should appear in the project asaddToCart.sql.

Tabbed window Action explanation

The previous query only deals with the shopping cart table. However, wehave included it in the catalog section since all the input parameters comefrom the catalog.

Note

ABC Company Web site design and development 223

Table 21. Using the Database Wizard to display all catalog items

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You need an input page to collect the data for insertion,an output page to show the result from the query, and an errorpage if something unforeseen happens. You must also:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.d. Select the no data is returned check box.

Click Next.

Input Page The input page does not require any parameters.

Click Next.

Results Page The results page will already have the output parameters youwanted from the SQL file. These should be APILIB_ITEM_IID,APILIB_ITEM_INAME, and APILIB_ITEM_IPRICE.

Select the parameters by clicking on the row and click theChange button to change the caption to a more meaningfulname. You can also change the field sizes. Repeat this for thefollowing parameters:

• For IID, type Product ID• For INAME, type Product Name• For IPRICE, type Product Price

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click Next.

No Data Page Click Next.

Methods Make sure that the method named execute() is selected.

Click Next.

Session This bean is only to be used one time. We do not need to bind itto the session, so make sure No is selected.

Name the bean viewAllCatalogItemsDBBean.Click Next.

224 Web Enabling AS/400 Applications with IBM WebSphere Studio

You should now see the following added to the Studio Workbench:

• viewAllCatalogItemsError.jsp• viewAllCatalogItemsInput.html• viewAllCatalogItemsNoData.jsp• viewAllCatalogItemsResults.jsp

7. Select the Catalog folder. Then, right-click, and select the Check In option.

If you look inside the servlet directory, you will see that the following files havebeen created:

• viewAllCatalogItems.class• viewAllCatalogItems.java• viewAllCatalogItems.servlet• viewAllCatalogItemsDBBean.class• viewAllCatalogItemsDBBean.java

7.3.3.2 Displaying items from the catalog by price rangePerform the following tasks that run the Database Wizard to create the HTMLform, the servlet, the bean, and resulting JSPs to select items from the ITEMdatabase table by price range:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder Catalog.

3. Start the SQL Wizard by selecting Tools ->Wizards ->Database Wizard.

4. Select the appropriate SQL Statement, which you created in 7.3.2.2,“Selecting by price range from the catalog” on page 217. It should bedrive:\subsites\NewUser\viewByPriceCatalogItems.sql.

5. Click Next.

Finish Give a meaningful name to the generated source files. Click theRename button, and type viewAllCatalogItems into the Prefixdialog. Click OK. Note that all of the files now have the prefix ofviewAllCatalogItems.

Click Finish to generate the code.

The Database Wizard generates and compiles the files. The fileswill be placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

ABC Company Web site design and development 225

6. Proceed through the tabbed windows of the wizard, and specify theinformation described in Table 22.

Table 22. Using the Database Wizard to display the catalog based on a price range

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You need an input page to collect the data forinsertion, an output page to show the result from the query, andan error page if something unforeseen happens. You also needto:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.d. Select the no data is returned check box.

Click Next.

Input Page The user need to be able to search by a price range, so make surethe minPrice and maxPrice check boxes are both selected.

Select the parameters by clicking on the row. Click the Changebutton to change the caption to a more meaningful name. You canalso change the field sizes. Repeat this for the followingparameters:

• For minPrice, type Minimum Product Price• For maxPrice, type Maximum Product Price

Ensure that the Table radio button is selected.

Click Next.

Results Page The results page will already have the output parameters youwanted from the SQL file. These should be APILIB_ITEM_IID,APILIB_ITEM_INAME, and APILIB_ITEM_IPRICE.

Select the parameters by clicking on the row and clicking theChange button to change the caption to a more meaningfulname. You can also change the field sizes. Repeat this for thefollowing parameters:

• For IID, type Product ID• For INAME, type Product Name• For IPRICE, type Product Price

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click Next.

No Data Page Click Next.

Methods Make sure the method named execute() is selected.

Click Next.

226 Web Enabling AS/400 Applications with IBM WebSphere Studio

You should now see the following files added to the Studio Workbench:

• viewByPriceCatalogItemsError.jsp• viewByPriceCatalogItemsInput.html• viewByPriceCatalogItemsNoData.jsp• viewByPriceCatalogItemsResults.jsp

7. Select the Catalog folder. Then, right-click, and select the Check In option.

If you look inside the servlet directory, you see that the following files havebeen created:

• viewByPriceCatalogItems.class• viewByPriceCatalogItems.java• viewByPriceCatalogItems.servlet• viewByPriceCatalogItemsDBBean.class• viewByPriceCatalogItemsDBBean.java

7.3.3.3 Displaying a single item from the catalogPerform the following tasks that run the Database Wizard to create the HTMLform, the servlet, the bean, and resulting JSPs to select a single item from theITEM database table:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder Catalog.

3. Start the SQL Wizard by selecting Tools->Wizards->Database Wizard.

4. Select the appropriate SQL statement, which you created in 7.3.2.3,“Selecting a single item from the catalog” on page 220. It should bedrive:\subsites\NewUser\viewCatalogItem.sql.

Session This bean is only to be used one time. We do not need to bind itto the session so make sure No is selected.

Name the bean viewByPriceCatalogItemsDBBean.

Click Next.

Finish Give a meaningful name to the generated source files. Click theRename button and type viewByPriceCatalogItems into thePrefix dialog. Click the OK button, and note that all of the files willnow have the prefix of viewByPriceCatalogItems.

Click the Finish button to generate the code.

The Database Wizard generates and compiles the files. The fileswill be placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

ABC Company Web site design and development 227

5. Click Next.

6. Proceed through the tabbed windows of the wizard, and specify theinformation described in Table 23.

Table 23. Using the Database Wizard to display a single item from the catalog

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You will need an input page to collect the data forinsertion, an output page to show the result from the query, and anerror page if something unforeseen happens. You also need to:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.d. Select the no data is returned check box.

Click Next.

Input Page The prodID check box should already be checked.

Select the parameter by clicking on the row. Click the Changebutton to change the caption to a more meaningful name. You canalso change the field sizes. For prodID, type Product ID.

Ensure that the Table radio button is selected.

Click Next.

Results Page The results page will already have the output parameters that youwanted from the SQL file. These should be APILIB_ITEM_IID,APILIB_ITEM_INAME, and APILIB_ITEM_IPRICE.

Select the parameters by clicking on the row. Click the Changebutton to change the caption to a more meaningful name. You canalso change the field sizes. Repeat this for the followingparameters:

• For IID, type Product ID• For INAME, type Product Name• For IPRICE, type Product Price

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click the Next button without changing any values.

No Data Page Click Next.

Methods Make sure the method named execute() is checked.

Click Next.

Session This bean is only to be used one time. We do not need to bind itto the session so make sure No is selected.

Name the bean viewCatalogItemDBBean.

Click Next.

228 Web Enabling AS/400 Applications with IBM WebSphere Studio

You should now see the following files added to the Studio Workbench:

• viewCatalogItemError.jsp• viewCatalogItemInput.html• viewCatalogItemNoData.jsp• viewCatalogItemResults.jsp

7. Select the Catalog folder. Then, right-click, and select the Check In option.

If you look inside the servlet directory, you see that the following files havebeen created:

• viewCatalogItem.class• viewCatalogItem.java• viewCatalogItem.servlet• viewCatalogItemDBBean.class• viewCatalogItemDBBean.java

7.3.3.4 Displaying the items listed in the shopping cartPerform the following tasks that run the Database Wizard to create the HTMLform, the servlet, the bean, and resulting JSPs to select a single item from theITEM database table:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder Catalog.

3. Start the SQL Wizard by selecting Tools ->Wizards ->Database Wizard.

4. Select the appropriate SQL statement, which you created in 7.3.2.4, “Insertingthe selected item into the shopping cart” on page 221. It should bedrive:\subsites\NewUser\addToCart.sql.

5. Click Next.

Finish Give a meaningful name to the generated source files. Click theRename button and type viewCatalogItem into the Prefixdialog. Click OK. Note that all of the files now have the prefixviewCatalogItem.

Click the Finish button to generate the code.

The Database Wizard generates and compiles the files. The fileswill be placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

ABC Company Web site design and development 229

6. Proceed through the tabbed windows of the wizard, and specify theinformation described in Table 24.

Table 24. Using the Database Wizard to display the items listed in the shopping cart

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You need an input page to collect the data for insertion,an output page to show the result from the query, and an errorpage if something unforeseen happens. You also need to:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.

Click Next.

Input Page All the input parameters we require should already be selected.

Select the parameters by clicking on the row. Click the Changebutton to change the caption to a more meaningful name. You canalso change the field sizes. Repeat this for the followingparameters:

• For custID, type Customer ID

• For prodName, type Product Name

• For prodID, type Product ID

• For prodPrice, type Product Price

• For prodQty, type Product Quantity

Ensure that the Table radio button is selected.

Click Next.

Results Page On the results page we just want to know if the data was added.Click in the custID check box.

Click Next.

Standard Error Page Click the Next button without changing any values.

Methods Make sure the method named execute() is selected.

Click Next.

Session This bean is only to be used one time. We do not need to bind itto the session so make sure No is selected.

Name the bean addToCartDBBean.

Click Next.

230 Web Enabling AS/400 Applications with IBM WebSphere Studio

You should now see the following files added to the Studio Workbench:

• addToCartError.jsp• addToCartInput.html• addToCartResults.jsp

7. Select the Catalog folder. Right-click, and select the Check In option.

If you look inside the servlet directory, you see that the following files havebeen created:

• addToCart.class• addToCart.java• addToCart.servlet• addToCartDBBean.class• addToCartDBBean.java

7.3.4 Testing the catalog pagesNow that the Catalog Web pages have been built, you should test them to see ifthe results are what you want. It is much easier to fix the pages at this point ifthere is a problem.

Perform the following steps to test the Catalog subsite:

1. Make sure you have your publishing target setup. Refer to 4.3.1, “Publishing tothe AS/400 system” on page 125, if you have not done this yet.

2. Right-click on the Catalog project folder in the Studio Workbench, and selectPublish whole Project. This publishes the entire Catalog project to yourdefined server, which is an AS/400 server in our case.

Finish Give a meaningful name to the generated source files. Click theRename button, and type addToCart into the Prefix dialog. ClickOK. Note that all of the files now have the prefix of addToCart.

Click Finish to generate the code.

The Database Wizard generates and compiles the files. The fileswill be placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

ABC Company Web site design and development 231

3. Once you have published your Web pages, make sure your WebSphereApplication Server and Web server are both started.

4. To test retrieving all items from the catalog, select theviewAllCatalogItemsInput.html file to preview it. Then, right-click, and selectPreview file with Netscape or Internet Explorer. When the Web browserappears, the screen appears as shown in Figure 211.

Figure 211. viewAllCatalogItemsInput.html displayed in Netscape

5. Click the Submit button. You should see a Web page as shown in Figure 212.

At this point, you are only testing subsites. There is still a long way to gobefore you have the completed Web site. You should not deploy the Website to a public production server for people to see until you are finished.You can publish your pages to a public server, but do not tell people aboutthe pages for general viewing until the entire Web site is done.

Reminder

If you get an error page or something that you did not expect, try restartingthe WebSphere Application Server and republishing the site.

Note

232 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 212. viewAllCatalogItemsResult.jsp displayed in Netscape

6. To test retrieving items from the catalog by price range, select theviewByPriceCatalogItemsInput.html file to preview it. Then, right-click, andselect Preview file with Netscape or Internet Explorer. When the Web browserappears as shown in Figure 213.

Figure 213. viewByPriceCatalogItemsInput.html displayed in Netscape

7. Set the minimum price to 2.00 and set the maximum price to 20.00. Click theSubmit button. The result page should appear as shown in Figure 214 onpage 234.

ABC Company Web site design and development 233

Figure 214. viewByPriceCatalogResults.jsp displayed in Netscape

8. To test retrieving a single item from the catalog, select theviewCatalogItemInput.html file to preview it. Then, right-click, and selectPreview file with Netscape or Internet Explorer. When the Web browserappears, the page appears as shown in Figure 215.

Figure 215. viewCatalogItemInput.html displayed in Netscape

9. Type a product ID of 000001. Click the Submit button. The result page shouldappear as shown in Figure 216.

234 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 216. viewCatalogItemResults.jsp displayed in Netscape

10.To test adding an item to the shopping cart, select the addToCartInput.htmlfile to preview it. Then, right-click, and select Preview file with Netscape orInternet Explorer. When the Web browser appears, the page appears asshown in Figure 217.

Figure 217. addToCartInput.html displayed in Netscape

11.Complete the following parameters with the information shown:

• Customer ID: Type 0011

• Product Name: Type Shoe

• Product ID: Type 000005

• Product Price: Type 20.00

• ProdQty: Type 12

12.Click the Submit button. The result page should appear as shown in Figure218 on page 236.

ABC Company Web site design and development 235

Figure 218. addToCartResults.jsp displayed in Netscape

7.3.5 Creating the general catalog areaYou need the catalog to be accessible from two places: inside the registered userarea and outside the registered user area. Follow these steps:

1. Start WebSphere Studio if it is not already started.

2. Create a new project by selecting File->New Project from the pull-downmenu.

a. Type GeneralCatalog for the project name.b. Type drive:\subsites\GeneralCatalog for the project folder.c. Select <none> for the project template.

3. In the Studio Workbench, select Insert->Folder from the pull-down menu.Click the Use Existing tab. For Folder Name, type drive:\subsites\Catalog.Then, click OK.

4. Expand the Catalog directory, and select all the files in the root of the Catalogdirectory. Drag these files to the GeneralCatalog directory.

5. Expand the servlet directory inside the Catalog directory. Drag the Catalog’sservlet directory to the GeneralCatalog’s servlet directory.

6. Right-click on the Catalog directory, and select Delete.

7. Delete the following files from this GeneralCatalog subsite:

• addToCart.sql• addToCartError.jsp• addToCartInput.html• addToCartResults.jsp• viewCatalogItem.sql• viewCatalogItemError.jsp• viewCatalogItemInput.html• viewCatalogItemResults.jsp• viewCatalogItemNoData.jsp• addToCart.class• addToCart.java• addToCart.servlet• addToCartDBBean.class• addToCartDBBean.java• viewCatalogItem.class• viewCatalogItem.java• viewCatalogItem.servlet• viewCatalogItemDBBean.class• viewCatalogItemDBBean.java

236 Web Enabling AS/400 Applications with IBM WebSphere Studio

8. Expand the servlet directory and the Catalog directory inside the servletdirectory.

9. Click on the first file viewAllCatalogItems.class. Holding down the Shift key,click on the last file called viewByPriceCatalogItemsDBBean.java.

10.Select Edit->Find and Replace Text... from the pull-down menu. You shouldsee a dialog box like the example in Figure 219.

Figure 219. WebSphere Studio Find and Replace dialog box.

11.In the Find and Replace dialog box, use the following parameters:

a. For the Find what field, type Catalog.b. From the drop-down list box next to Among, select Selected Files.c. For the Replace with field, type GeneralCatalog.d. Select the Match Case check box.e. Select the Find Now button.f. Once the word is found, click the Replace All (All files) button. If you are

asked about checking the files out, click the Yes to All button. Close thiswindow when completed.

12.Right-click on the Catalog directory in the servlet directory, and selectRename. Type GeneralCatalog for the new directory name.

13.Right-click on the .java files in this directory, and select Compile. You need tocompile the Java beans first.

7.3.6 Linking the catalog pagesNow that you have developed the catalog pages and tested them all to ensurethat they work as expected, it is now time to link all pages together to create acatalog subsite. The final subsite will still not be pretty or have sessionmanagement integrated into it, but it will show us the flow of the catalog.

Open the catalog project by performing the following steps:

1. In the Studio Workbench, select File->Open Project.

2. Open the Catalog.wao file located inside the drive:\subsites\Catalog directory.

ABC Company Web site design and development 237

7.3.6.1 Merging the two input pagesTo merge the two input pages, perform these steps:

1. In the Studio Workbench, double-click on the viewAllCatalogItemsInput.htmlfile. This checks it out and opens it in the Page Designer.

2. In the Studio Workbench, double-click theviewByPriceCatalogItemsInput.html file. This checks it out and opens it inthe Page Designer.

3. While viewing the viewByPriceCatalogItemsInput.html file in the PageDesigner, select Edit->Select All.

4. Select Edit->Copy.

5. Close the viewByPriceCatalogItemsInput.html file. You should see theviewAllCatalogItemsInput.html file. Put the cursor at the top of the page, andselect Edit->Paste. The page should appear as shown in Figure 220.

Figure 220. New viewAllCatalogItemsInput.html page

6. Save this file, and exit the Page Designer.

7. In the Studio Workbench, right-click on the Catalog directory, and select theCheck In option.

8. If you select View->Relations and click on theviewAllCatalogItemsInput.html file, you should see that it now references toviewByPriceCatalogItems.servlet and viewAllCatalogItems.servlet.

9. Right-click on viewByPriceCatalogItemsInput.html, and select Delete.Make sure delete from disk is selected. Then, click the OK button.

Repeat this process for the GeneralCatalog subsite.

7.3.6.2 Modifying the viewAllCatalogItems.jsp pageComplete the following steps:

1. Double-click on viewAllCatalogItems.jsp. This checks out the file and opensit in Page Designer.

2. Where the Product ID heading is, delete it, and type Add item to shopping

cart.

3. Delete the JSP tag in the body cell under the heading “Add item to shoppingcart”.

238 Web Enabling AS/400 Applications with IBM WebSphere Studio

4. With the cursor in the cell under the heading “Add item to shopping cart”,select Insert->Form and Input Fields->Push Button->Submit Button. Youare presented with the dialog shown in Figure 221.

Figure 221. Insert push button dialog box

5. Complete the following parameters in the Push Button dialog box:

a. In the Name field, type AddItem.b. In the Label field, type Add Item.c. Leave the Button Type set to Submit.

6. At this point, your page should look like the example shown in Figure 222.

Figure 222. viewAllCatalogItemsResults.jsp after being modified

Now that you have modified your page, you need to decide what information youneed to pass and to where. The good thing about using the Studio Wizards so faris that you have a reference page to look at for this information. Follow thesesteps:

1. Browse through the Studio Workbench, and double-click the file calledviewCatalogItem.html to open it in the Page Designer. The page should looklike the example in Figure 223 on page 240.

ABC Company Web site design and development 239

Figure 223. viewCatalogItem.html viewed in the Page Designer

2. This page contains information of what servlet to call to view a single item andwhat parameters that servlet takes. Double-click inside the text field next toProduct ID. You should see the dialog box shown in Figure 224.

Figure 224. ProductID attribute dialog box

3. Make note of the name of this text field. This text field is called prodID. You willneed this information later. Click the Cancel button.

4. Get the information about the servlet that you are calling. Double-click insidethe text field next to the Product ID label. You will see the same dialog box asbefore. However, if you click in the drop-down list box next to the Tag caption,you see the caption Form listed in the list box. Select this, so we can see theproperties of the form. The dialog box should look like the example shown inFigure 225.

240 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 225. Product ID form attribute dialog box

5. The parameter that we need to observe in Figure 225 is Action. Make a noteof where this action points to, which is /servlet/Catalog.viewCatalogItem. Thisis the location of the servlet. Submitting the form by clicking the Submitbutton, all form parameters are sent to the servlet.

Now that you have this information, you can return back to theviewAllCatalogItemsResults.jsp page, which should still be open in the PageDesigner. If it is not opened, double-click the file in the Studio Workbench. Followthese steps:

1. Double-click the Add Item button you added last to this page.

2. You are presented with the button dialog box. We want the form properties, soclick in the drop-down list box next to Tag, and select Form.

3. The Form properties should be blank. You are now going to use theinformation from before for this form. For the action, type:

/servlet/catalog.viewCatalogItem.

4. Set the method to Post. The resulting form properties may look like theexample in Figure 226 on page 242.

ABC Company Web site design and development 241

Figure 226. Form attribute dialog box

5. You now need to add some parameters to the form Hidden Fields. These fieldsallow us to pass parameters from one form to a servlet without the user havingto type anything. Click on the Hidden Fields tab. You should see the dialogbox shown in Figure 227.

Figure 227. Form attribute dialog box showing Hidden Fields

242 Web Enabling AS/400 Applications with IBM WebSphere Studio

6. You need to add a hidden field to represent the product ID. Click in the Namefield, and type prodID.

7. For the value of this parameter, you need to specify it from a bean property.Under the Value field, select the Specify by property check box.

8. Click the Browse... button under the Value field. You should see a dialog boxlike the one in Figure 228.

Figure 228. Bean property selection dialog box

9. We need the product ID, so select APILIB_ITEM_IID(). Click the OK button.

10.In the Attribute window on the Hidden Fields tab, click the Add button to addthis parameter.

11.Click the OK button, save your page, and quit Page Designer.

12.Check in all your files in the Studio Workbench.

13.Publish only the modified files.

Repeat the process from in this section for theviewByPriceCatalogItemsResults.jsp page.

7.3.6.3 Adding an item from the catalogYou need to modify the viewCatalogItemResults.jsp page so that you can call theaddToCart servlet. Follow these steps:

1. Double-click the viewCatalogItemResults.jsp file. This checks it out andopens it in the Page Designer. The page should appear as shown in Figure229 on page 244.

The hidden fields can still be viewed by a user if they look at the source ofthe HTML documentation. The hidden fields should Never contain a user’spassword or confidential information.

In our example, we are not too worried if the user finds out their customernumber because they cannot do much with it unless they login successfully.

Note

ABC Company Web site design and development 243

Figure 229. viewCatalogItemResults.jsp page

2. Right-click in the first column, and select Delete. Repeat this in all the cells.

3. We are now left with two JSP tags. Place the cursor between these two tags,and select Insert->Table. Set the columns to 1 and the rows to 1.

4. Double-click inside the table. You should get the table Attribute dialog box.

5. Click the Table tab, and deselect the show border check box.

6. Click the Dynamic tab, and click inside the loop check box. For the loopproperty, click the Browse... button, and select for the loop propertyAPILIB_ITEM_IID(). Click the OK button.

7. Click the OK button inside the Attribute dialog box.

8. Place the cursor inside the table and select Insert->Form and InputFields->Form. Click the OK button in the form Attribute dialog box.

9. Inside the form, type the following text:

Product ID -

Product name -

Product unit price -

Product quantity -

10.We need to display the dynamic properties from the bean. Place the cursor atthe end of the line that has the text Product ID -. Select Insert->DynamicElements->Property Display. You then see the dialog box shown in Figure230.

Figure 230. Dynamic elements Attribute dialog box

11.Click the Browse... button. In the Bean Property Selection dialog box, selectthe property APILIB_ITEM_IID(), and click the OK button.

244 Web Enabling AS/400 Applications with IBM WebSphere Studio

12.Click the OK button in the Attribute dialog box.

13.Repeat the above process for the Product name caption usingAPILIB_ITEM_INAME().

14.Repeat the above process for the Product unit price caption usingAPILIB_ITEM_IPRICE().

15.Place the cursor next to the Product quantity caption, and selectInsert->Form and Input Fields->Text Field. In the Text Field Attribute dialogbox, click the OK button.

16.Add two lines under the Product quantity caption, and select Insert->Formand Input Fields->Push Button->Submit button. In the name field, typeaddItem and in the Label field, type Add to Shopping Cart. Click the OK button.

The viewCatalogItemResults.jsp page should appear as shown in Figure 231.

Figure 231. Modified viewCatalogItemResults.jsp page

We want this page to replace addToCartInput.html, so you need to determinewhat parameters are passed to which servlet. Follow these steps:

1. In the Studio Workbench, double-click the addToCartInput.html file. Thischecks out the file and opens it in Page Designer. The page should appear asshown in Figure 232.

Figure 232. Getting the addToCartInput.htm parameters

2. Double-click in the field next to Customer ID. Note the name in the Text Fielddialog box, which should be custID. Click the Cancel button.

ABC Company Web site design and development 245

3. Repeat the previous process on the field next to Product Name. The Text Fieldname should be prodName.

4. Repeat the process on the field next to Product ID. The Text Field nameshould be prodID.

5. Repeat the process on the field next to Product price. The Text Field nameshould be prodPrice.

6. Repeat the process on the field next to Prod Quantity. The Text Field nameshould be prodQty.

7. Double-click inside the form to get the Form attribute dialog box. Note theaction for this form, which, in this case, is /servlet/catalog.addToCart.

We now return to the viewCatalogItemsResults.jsp page to use the parametersfrom the previous process. Follow these steps:

1. In the Studio Workbench, double-click on the ViewCatalogItemsResults.jsppage. This checks out the file and opens it in Page Designer.

2. Double-click inside the form area. You should get the Form Attribute dialogbox. For the Action, type:

/servlet/catalog.addToCart

3. Set the method to Post.

4. Click the Hidden Fields tab and add the hidden fields listed in Table 25.

Table 25. Hidden field properties for viewCatalogItemsResults

5. Double-click on the text field next to the Product Quantity caption. In the Textfield dialog box, type prodQty for the name, and click the OK button.

6. Save this page, and exit the Page Designer.

7.4 Shopping cart subsite

The shopping cart subsite allows the user to work with their shopping cart. Thereare several ways in which the user could work with their shopping cart, but for thisbook, we have limited it to viewing, deleting, and changing item quantities.

7.4.1 Creating the shopping cart projectWe need to create a new project for the shopping cart subsite. Follow these stepsto create the new Shopping Cart project folder:

1. Start WebSphere Studio if it is not already started.

2. Create the new project by selecting File->New Project.

3. Type ShoppingCart for the project name.

4. Type drive:\subsites\ShoppingCart for the project folder.

5. Select <none> for project template.

Hidden field name Hidden field bean source

prodName viewCatalogItemDBBean.APILIB_ITEM_INAME()

prodID viewCatalogItemDBBean.APILIB_ITEM_IID()

prodPrice viewCatalogItemDBBean.APILIB_ITEM_IPRICE()

246 Web Enabling AS/400 Applications with IBM WebSphere Studio

A new project is created called ShoppingCart.

7.4.2 Creating the SQL queries for the shopping cart subsiteBefore beginning this section, you should already be familiar with the SQL Wizarddiscussed in 3.2, “Studio Wizards” on page 28.

7.4.2.1 Selecting all items from the shopping cartPerform the following tasks that run the SQL Wizard to create an SQL statementthat selects all items from the shopping cart:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder Shopping Cart.

3. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

4. Proceed through the tabbed windows of the wizard, and specify theinformation described in Table 26.

Table 26. Creating a select all query for the shopping cart

Tabbed window Action explanation

Welcome Enter viewAllShoppingCart as the name of the query. Thewizard adds an .sql file in your project.

Click Next.

Logon Enter the information the wizard needs to connect to thedatabase, for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be in uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click on theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is APILIB in this case. Click on thelibrary to select it, and click the Add button.

Click OK to return to the Tables window.

Click the Select radio button in the Statement type.

Select APILIB.SHPCART from the list of tables shown.

Click Next.

ABC Company Web site design and development 247

5. Check in the generated file viewAllShoppingCart.sql to the Studio Workbench.Select the ShoppingCart folder. Then, right-click, and select the Check Inoption.

7.4.2.2 Selecting a single item from the shopping cartPerform the following tasks that run the SQL Wizard to create an SQL statementthat selects a single item from the shopping cart:

1. Start WebSphere Studio it is if not already started.

2. Select the project folder Shopping Cart.

3. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

Join No action is required.

Click Next.

Columns Click the Select All button. Then, click the Add >> button to addthe columns in the list box.

Click Next.

Condition 1 Select SCID in the Columns list box. Select the operator as isexactly equal to. Click in the top values field, and click theParameter button.

In the Create a new parameter dialog box, enter the variable namecustID, and then click OK.

Click Next.

Sort You need to display all the products based on the order of theproduct ID.

Click on APILIB.SHPCART.SIID. Click the Add >> button to addit to the columns to sort on list box. Make sure the sort order is setto Ascending.

Click Next.

SQL At this point, you should have some test data in your shopping carttable.

Click the Run SQL... button, and type 0011. This should give youall the items for that particular customer.

Click the OK button on the SQL Execution Result Set window.

Click Next.

Finish Click the Finish button.

The completed SQL file should appear in the project asviewAllShoppingCart.sql.

Tabbed window Action explanation

248 Web Enabling AS/400 Applications with IBM WebSphere Studio

4. Proceed through the tabbed windows of the wizard, and specify theinformation described in Table 27.

Table 27. Creating a select single item query for the shopping cart

Tabbed window Action explanation

Welcome Enter viewShoppingCartItem as the name of the query. Thewizard adds an .sql file in your project.

Click Next.

Logon Enter the information the wizard needs to connect to thedatabase, for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be in uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is APILIB in this case. Click on thelibrary to select it, and click the Add button.

Click the OK button to return to the Tables window.

Click the Select radio button in the Statement type.

Select APILIB.SHPCART from the list of tables shown.

Click Next.

Join No action is required.

Click Next.

Columns Click the Select All button. Then, click the Add >> button to addthe columns in the list box.

Click Next.

ABC Company Web site design and development 249

5. Check in the generated file viewShoppingCartItem.sql to the StudioWorkbench. Select the ShoppingCart folder. Then, right-click, and select theCheck In option.

7.4.2.3 Updating a single item in the shopping cartPerform the following tasks that run the SQL Wizard to create an SQL statementthat updates a single item in the shopping cart:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder Shopping Cart.

3. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

Condition 1 Select SCID in the Columns list box. Select the operator to be isexactly equal to. Click in the top values field, and click theParameter button.

In the Create a new parameter dialog box, enter the variable namecustID, and then click the OK button.

Click the Find on another column button.

Condition 2 Make sure the radio button Find fewer rows (AND) at the top isselected.

Select SIID in the Columns list box. Select the operator to be isexactly equal to. Click in the top values field, and click on theParameter button.

In the Create a new parameter dialog box, enter the variable nameproductID, and click the OK button.

Click Next.

Sort No action is required.

Click Next.

SQL You should now see your SQL statement. To test if it workscorrectly, click the Run SQL... button.

You are now prompted for two parameters in the SpecifyParameter Value(s) window. For the first parameter, type 0011.Now, type a product ID xxxx. After running this SQL statement,the result should be a single product.

Click Next.

Finish Click Finish.

The completed SQL file should appear in the project asviewShoppingCartItem.sql.

Tabbed window Action explanation

250 Web Enabling AS/400 Applications with IBM WebSphere Studio

4. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 28.

Table 28. Creating an update single item query for the shopping cart

Tabbed window Action explanation

Welcome Enter updateShoppingCartQuantities as the name of thequery. The wizard adds an .sql file in your project.

Click Next.

Logon Enter the information the wizard needs to connect to thedatabase, for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be in uppercase.

Click the Connect button and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is APILIB in this case. Click thelibrary to select it, and click the Add button.

Click the OK button to return to the Tables window.

Click the Update radio button in the Statement type.

Select APILIB.SHPCART from the list of tables shown.

Click Next.

Update Click in the SQTY value field and click the Parameter button.

In the Modify an Existing Parameter window, type newQty, andclick OK.

Click Next.

Condition 1 Select SCID in the Columns list box. Select the operator as isexactly equal to. Click in the top values field, and click theParameter button.

In the Create a new parameter dialog box, enter the variable namecustID, and click OK.

Click Find on another column.

ABC Company Web site design and development 251

5. Check in the generated file updateShoppingCartQuantities.sql to the StudioWorkbench. Select the ShoppingCart folder. Then, right-click, and select theCheck In option.

7.4.2.4 Deleting a single item from the shopping cartPerform the following tasks that run the SQL Wizard to create an SQL statementthat deletes a single item in the shopping cart:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder Shopping Cart.

3. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

4. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 29.

Table 29. Creating a delete single item query for the shopping cart

Condition 2 Make sure the radio button Find fewer rows (AND) at the top isselected.

Select SIID in the Columns list box. Select the operator to be isexactly equal to. Click in the top values field, and click theParameter button.

In the Create a new parameter dialog box, enter the variable nameproductID, and click OK.

Click the Next button to go to the next tab.

SQL Click the Run SQL... button, and type 0011 for the first parameterand xxxx for the product ID. Enter in some value for newQty. Youshould find that the shopping cart is now updated with the newquantity.

Click the OK button on the SQL Execution Result Set window.

Click Next.

Finish Click Finish.

The completed SQL file should appear in the project asupdateShoppingCartQuantities.sql.

Tabbed window Action explanation

Welcome Enter deleteShoppingCartItem as the name of the query. Thewizard adds an .sql file in your project.

Click Next.

Tabbed window Action explanation

252 Web Enabling AS/400 Applications with IBM WebSphere Studio

Logon Enter the information the wizard needs to connect to thedatabase, for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be in uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click on theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is APILIB in this case. Click on thelibrary to select, it and click the Add button.

Click OK to return to the Tables window.

Click the Delete radio button in the Statement type.

Select APILIB.SHPCART from the list of tables shown.

Click Next.

Condition 1 Select SCID in the Columns list box. Select the operator to be isexactly equal to. Click in the top values field, and click theParameter button.

In the Create a new parameter dialog box, enter the variable namecustID, and click OK.

Click Find on another column.

Condition 2 Make sure the radio button Find fewer rows (AND) at the top isselected.

Select SIID in the Columns list box. Select the operator to be isexactly equal to. Click in the top values field, and click theParameter button.

In the Create a new parameter dialog box, enter the variable nameproductID, and click the OK button.

Click Next.

Tabbed window Action explanation

ABC Company Web site design and development 253

5. Check in the generated file deleteShoppingCartItem.sql to the StudioWorkbench. Select the ShoppingCart folder. Then, right-click, and select theCheck In option.

7.4.3 Creating Web pages for the shopping cart subsiteBefore beginning this section, you should already be familiar with the DatabaseWizard which is discussed in 3.2, “Studio Wizards” on page 28.

7.4.3.1 Displaying all items from the shopping cartPerform the following tasks that run the Database Wizard to create the HTMLform, the servlet, the bean, and resulting JSPs to select all records from theSHPCART database table:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder ShoppingCart.

3. Start the SQL Wizard by selecting Tools ->Wizards ->Database Wizard.

4. Select the appropriate SQL Statement, which you created in 7.4.2.1,“Selecting all items from the shopping cart” on page 247. It should bedrive:\subsites\NewUser\viewAllShoppingCart.sql.

5. Click Next.

6. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 30.

Table 30. Using the Database Wizard to display all shopping cart items

SQL Click the Run SQL... button, and type 0011 for the first parameterand xxxx for the product ID. You should now find that theshopping cart does not have that particular entry anymore.

Click the OK button on the SQL Execution Result Set window.

Click Next.

Finish Click Finish.

The completed SQL file should appear in the project asdeleteShoppingCartItem.sql.

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You need an input page to collect the data for insertion,an output page to show the result from the query, and an errorpage if something unforeseen happens. You also need to:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.d. Select the no data is returned check box.

Click Next.

Tabbed window Action explanation

254 Web Enabling AS/400 Applications with IBM WebSphere Studio

Input Page The custID parameter should already be selected. Click thecustID row and click the Change... button. In the Change Detailsdialog box, change the caption to Customer ID.

Ensure that the Table radio button is selected.

Click Next.

Results Page The results page will already have the output parameters youwanted in the SQL file. These should beAPILIB_SHPCART_SCID, APILIB_SHPCART_SDSC,APILIB_SHPCART_SQTY, APILIB_SHPCART_SPRC, andAPILIB_SHPCART_SIID.

Select the parameters by clicking on the row. Click the Changebutton to change the caption to a more meaningful name. You canalso change the field sizes. Perform this for the followingparameters:

• For SCID, type Customer ID• For SDSC, type Product Name• For SQTY, type Product Quantity• For SPRC, type Product Unit Price• For SIID, type Product ID

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click Next.

No Data Page Click Next.

Methods Make sure that the method named execute() is selected.

Click Next.

Session This bean is only to be used one time. You do not need to bind itto the session so make sure No is selected.

Name the bean viewAllShoppingCartDBBean.

Click Next.

Tabbed window Action explanation

ABC Company Web site design and development 255

You should now see the following files added to the Studio Workbench:

• viewAllShoppingCartError.jsp• viewAllShoppingCartInput.html• viewAllShoppingCartNoData.jsp• viewAllShoppingCartResults.jsp

7. Select the ShoppingCart folder. Then, right-click, and select the Check Inoption.

If you look inside the servlet directory, you see that the following files havebeen created:

• viewAllShoppingCart.class• viewAllShoppingCart.java• viewAllShoppingCart.servlet• viewAllShoppingCartDBBean.class• viewAllShoppingCartDBBean.java

7.4.3.2 Displaying a single item from the shopping cartPerform the following tasks that run the Database Wizard to create the HTMLform, the servlet, the bean, and resulting JSPs to select a single record from theSHPCART database table:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder ShoppingCart.

3. Start the SQL Wizard by selecting Tools->Wizards->Database Wizard.

4. Select the appropriate SQL statement, which you created in 7.4.2.2,“Selecting a single item from the shopping cart” on page 248. It should bedrive:\subsites\NewUser\viewShoppingCartItem.sql.

5. Click Next.

Finish Give a meaningful name to the generated source files. Click theRename button, and type viewAllShoppingCart into the Prefixdialog. Click OK. Note that all of the files now have the prefix ofviewAllShoppingCart.

Click Finish to generate the code.

The Database Wizard generates and compiles the files. The filesare placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

256 Web Enabling AS/400 Applications with IBM WebSphere Studio

6. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 31.

Table 31. Using the Database Wizard to display a single shopping cart item

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You need an input page to collect the data for insertion,an output page to show the result from the query, and an errorpage if something unforeseen happens. You also need to:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.d. Select the no data is returned check box.

Click Next.

Input Page The user needs to be able to search by a price range, so makesure custID and productID check boxes are both selected.

Select the parameters by clicking on the row. Click the Changebutton to change the caption to a more meaningful name. You canalso change the field sizes. Perform this for the followingparameters:

• For customerID, type Customer ID• For productID, type Product ID

Ensure that the Table radio button is selected.

Click Next.

Results Page The results page will already have the output parameters youwanted in the SQL file. These should beAPILIB_SHPCART_SCID, APILIB_SHPCART_SDSC,APILIB_SHPCART_SQTY, APILIB_SHPCART_SPRC, andAPILIB_SHPCART_SIID.

Select the parameters by clicking on the row. Click the Changebutton to change the caption to a more meaningful name. You canalso change the field sizes. Perform this for the followingparameters:

• For SCID, type Customer ID

• For SDSC, type Product Name

• For SQTY, type Product Quantity

• For SPRC, type Product Unit Price

• For SIID, type Product ID

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click Next.

No Data Page Click Next.

Methods Make sure that the method named execute() is selected.

Click Next.

ABC Company Web site design and development 257

You should now see the following files added to the Studio Workbench:

• viewShoppingCartItemError.jsp• viewShoppingCartItemInput.html• viewShoppingCartItemNoData.jsp• viewShoppingCartItemResults.jsp

7. Select the ShoppingCart folder. Then, right-click, and select the Check Inoption.

If you look inside the servlet directory, you see that the following files havebeen created:

• viewShoppingCartItem.class• viewShoppingCartItem.java• viewShoppingCartItem.servlet• viewShoppingCartItemDBBean.class• viewShoppingCartItemDBBean.java

7.4.3.3 Displaying the updated item in the shopping cartPerform the following tasks that run the Database Wizard to create the HTMLform, the servlet, the bean, and resulting JSPs to select the updated record fromthe SHPCART database table:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder ShoppingCart.

3. Start the SQL Wizard by selecting Tools ->Wizards ->Database Wizard.

4. Select the appropriate SQL statement, which you created in 7.4.2.3, “Updatinga single item in the shopping cart” on page 250. It should bedrive:\subsites\NewUser\updateShoppingCartQuantities.sql.

Session This bean is only to be used one time. You do not need to bind itto the session so make sure No is selected.

Name the bean viewShoppingCartItemDBBean.

Click Next.

Finish Give a meaningful name to the generated source files. Click theRename button and type viewShoppingCartItem into the Prefixdialog. Click OK. Note that all of the files now have the prefix ofviewShoppingCartItem.

Click the Finish button to generate the code.

The Database Wizard generates and compiles the files. The filesare placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

258 Web Enabling AS/400 Applications with IBM WebSphere Studio

5. Click Next.

6. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 32.

Table 32. Using the Database Wizard to update a single shopping cart item

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You need an input page to collect the data for insertion,an output page to show the result from the query, and an errorpage if something unforeseen happens. You also need to:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.

Click Next.

Input Page The user needs to be able to search by price range, so make surethe newQty, custID, and productID check boxes are selected.

Select the parameters by clicking on the row. Click the Changebutton to change the caption to a more meaningful name. You canalso change the field sizes. Perform this step for the followingparameters:

• For customerID, type Customer ID• For productID, type Product ID• For newQty, type New Input Quantity

Ensure that the Table radio button is selected.

Click Next.

Results Page For this test purpose, you only need one field selected torepresent the output. This is just a sample output, so you can seeif something happened in the testing stage.

Select custID by clicking in the check box. Click the Changebutton, and type Customer ID as the new caption.

Ensure that the Table radio button is selected.

Click the Next button to go to the next tab.

Standard Error Page Click Next.

Methods Make sure that the method named execute() is selected.

Click Next.

Session This bean is only to be used one time. You do not need to bind itto the session so make sure No is selected.

Name the bean updateShoppingCartQuantitiesDBBean.

Click Next.

ABC Company Web site design and development 259

You should now see the following files added to the Studio Workbench:

• updateShoppingCartQuantitiesError.jsp• updateShoppingCartQuantitiesInput.html• updateShoppingCartQuantitiesNoData.jsp• updateShoppingCartQuantitiesResults.jsp

7. Select the ShoppingCart folder. Then, right-click, and select the Check Inoption.

If you look inside the servlet directory, you also see that the following fileshave been created:

• updateShoppingCartQuantities.class• updateShoppingCartQuantities.java• updateShoppingCartQuantities.servlet• updateShoppingCartQuantitiesDBBean.class• updateShoppingCartQuantitiesDBBean.java

7.4.3.4 Verifying a deleted item from the shopping cartPerform the following tasks that run the Database Wizard to create the HTMLform, the servlet, the bean, and resulting JSPs to verify that a deleted record hasbeen removed from the SHPCART database table:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder ShoppingCart.

3. Start the SQL Wizard by selecting Tools->Wizards->Database Wizard.

4. Select the appropriate SQL Statement, which you created in 7.4.2.4, “Deletinga single item from the shopping cart” on page 252. It should bedrive:\subsites\NewUser\deleteShoppingCartItem.sql.

5. Click Next.

Finish Give a meaningful name to the generated source files. Click theRename button, and type updateShoppingCartQuantities intothe Prefix dialog. Click OK. Note that all of the files now have theprefix of updateShoppingCartQuantities.

Click the Finish button to generate the code.

The Database Wizard generates and compiles the files. The filesare placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

260 Web Enabling AS/400 Applications with IBM WebSphere Studio

6. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 33.

Table 33. Using the Database Wizard to delete a single shopping cart item

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You need an input page to collect the data forinsertion, an output page to show the result from the query, andan error page if something unforeseen happens. You also need to:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.

Click Next.

Input Page The user needs to be able to search by price range, so make surethe custID and productID check boxes are both selected.

Select the parameters by clicking on the row. Click the Changebutton to change the caption to a more meaningful name. You canalso change the field sizes. Perform this step for the followingparameters:

• For customerID, type Customer ID• For productID, type Product ID

Ensure that the Table radio button is selected.

Click Next.

Results Page For this test purpose, you only need one field selected torepresent the output. This is just a sample output, so you can seeif something happened in the testing stage.

Select custID by clicking in the check box. Click the Changebutton, and type Customer ID as the new caption.

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click Next.

No Data Page Make sure that the method named execute() is selected.

Click Next.

Methods This bean is only to be used one time. You do not need to bind itto the session so make sure No is selected.

Name the bean deleteShoppingCartItemDBBean.

Click Next.

ABC Company Web site design and development 261

You should now see the following files added to the Studio Workbench:

• deleteShoppingCartItemError.jsp• deleteShoppingCartItem.html• deleteShoppingCartItemNoData.jsp• deleteShoppingCartItemResults.jsp

7. Select the ShoppingCart folder. Then, right-click, and select the Check Inoption.

If you look inside the servlet directory, you see that the following files havebeen created:

• deleteShoppingCartItem.class• deleteShoppingCartItem.java• deleteShoppingCartItem.servlet• deleteShoppingCartItemDBBean.class• deleteShoppingCartItemDBBean.java

7.4.4 Testing the shopping cart pagesNow that the shopping cart pages have been built you should test them to see ifthe results are what you want. It is much easier to fix the pages at this point ifthere is a problem. Follow these steps:

1. Make sure your publishing target is setup. Refer to 4.3.1, “Publishing to theAS/400 system” on page 125, if you have not done this yet.

Session Give a meaningful name to the generated source files. Click theRename button, and type deleteShoppingCartItem to the Prefixdialog. Click OK. Note that all of the files will now have the prefixof deleteShoppingCartItem.

Click Finish to generate the code.

The Database Wizard generates and compiles the files. The filesare placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Finish This tab allows you to specify what HTML and JSP files will begenerated. You need an input page to collect the data forinsertion, an output page to show the result from the query, andan error page if something unforeseen happens. You also need to:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.

Click Next.

Tabbed window Action explanation

262 Web Enabling AS/400 Applications with IBM WebSphere Studio

2. Right-click on the ShoppingCart project folder in the Studio Workbench.Select Publish whole Project. This publishes the entire Catalog project toyour defined server, which is an AS/400 server in our case.

3. Once you have published your Web pages, make sure your WebSphereApplication Server and Web server are both started.

7.4.4.1 Retrieving all items from the shopping cartTo test retrieving all items from the shopping cart, perform the following steps:

1. Select the viewAllShoppingCartInput.html file to preview it. Then,right-click, and select Preview file with Netscape or Internet Explorer. Whenthe Web browser appears, the page appears as shown in Figure 233.

Figure 233. viewAllShoppingCartInput.html displayed in Netscape

2. Type a valid customer ID from the SHOPCART table. For this example, weuse customer ID 0011.

3. Click the Submit button.

The result page should appear as shown in Figure 234.

Figure 234. viewAllShoppingCartResults.jsp displayed in Netscape

Notice that we only have the output for that single customer ID. When looking atthis screen, you can see that there is information that we do not really want topresent to the user. The user does not really need to see their customer ID or the

ABC Company Web site design and development 263

product ID of all the products. They only really need to see product name, price,and quantity. You see the customer ID and product ID because we select to havethese values in the output. It is important to have these values selected for theoutput so the bean has all the getters and setters automatically created. Itbecomes much clearer why we need these later in this section.

7.4.4.2 Retrieving a single item from the shopping cartTo test retrieving a single item from the shopping cart, perform the followingsteps:

1. Select the viewShoppingCartItemInput.html file to preview it. Then,right-click, and select Preview file with Netscape or Internet Explorer. Whenthe Web browser appears, the page appears as shown in Figure 235.

Figure 235. viewShoppingCartItemInput.html displayed in Netscape

2. Type a valid customer ID from the SHPCART table and a product ID thatbelongs to that customer ID. You can get this information fromviewAllShoppingCartResults.jsp. For this example, we use customer ID 0011and product ID 000026.

3. Click Submit.

The result page should appear as shown in Figure 236.

Figure 236. viewAllShoppingCartResults.jsp displayed in Netscape

264 Web Enabling AS/400 Applications with IBM WebSphere Studio

Notice that we only have the output for that single customer ID and product ID.Again, you can see that we have excess information, but we deal with this later inthis chapter.

7.4.4.3 Updating an item quantity in the shopping cartTo test updating an item quantity in the shopping cart, perform the followingsteps:

1. Select the updateShoppingCartQuantitiesInput.html file to preview it. Then,right-click, and select Preview file with Netscape or Internet Explorer. Whenthe Web browser appears, the page appears as shown in Figure 237.

Figure 237. updateShoppingCartQuantitiesInput.html displayed in Netscape

2. Type in a valid customer ID from the SHPCART table and a product ID thatbelongs to that customer ID. You can get this information fromviewAllShoppingCartResults.jsp. For this example, we use customer ID 0011and product ID 000026.

3. Add an item quantity that is different to what this product has. For thisexample, the new quantity is set to 25.

4. Click Submit.

The result page should appear as shown in Figure 238.

Figure 238. updateShoppingCartQuantitiesResults.jsp displayed in Netscape

ABC Company Web site design and development 265

Notice that the returned information does not give us any feedback. But, for thisexample, we needed some form of feedback to know if the update worked orfailed. If the update fails, we see the error page. To check if the update wassuccessful, check the SHPCART table on the AS/400 system, or you can previewthe viewAllShoppingCart.html and enter the same customer ID as before.

7.4.4.4 Verifying a deleted item from the shopping cartTo test if a deleted item has been removed from the shopping cart, perform thefollowing steps:

1. Select the deleteShoppingCartItemInput.html file to preview it. Then,right-click, and select Preview file with Netscape or Internet Explorer. Whenthe Web browser appears, the page appears as shown in Figure 239.

Figure 239. deleteShoppingCartItemInput.html displayed in Netscape

2. Type in a valid customer ID from the SHPCART table and a product ID thatbelongs to that customer ID. You can get this information fromviewAllShoppingCartResults.jsp. For this example, we use customer ID 0011and product ID 000026.

3. Click Submit.

The result page should appear as shown in Figure 240.

Figure 240. deleteShoppingCartResults.jsp

266 Web Enabling AS/400 Applications with IBM WebSphere Studio

Notice that the returned information does not give us any feedback. But, for thisexample, we need some form of feedback to know if the delete worked or failed. Ifthe delete fails, we see an error page. To check if the delete has was successful,check the SHPCART table on the AS/400 system, or you can preview theviewAllShoppingCart.html and enter in the same customer ID as before.

7.4.5 Modifying the shopping cart bean to display item totalsIt was mentioned earlier when we were looking at the output screen of theviewAllShoppingCart that it would be nice to have some item totals. To do this,we need to modify the Java Bean and the .jsp.

7.4.5.1 Modifying the beanPerform the following steps to modify the bean in order to display item totals:

1. In the Studio Workbench, click the plus sign (+) next to the servlet directory.

2. In the servlet directory, click the ShoppingCart directory.

3. Locate the file called viewAllShoppingCartDBBean.java.

Double-click this file. You will be prompted with the dialog box shown in Figure241.

Figure 241. Check-out file with dependencies

4. Click the Check Out and Edit button.

You are now presented with a text editor with your JavaBean source code in it.We need to add a method to this bean which returns the totals each time a rowis processed.

5. Find where setCustID is in the bean and move the cursor to the next line.Insert the following code:

/******************************************************************** Get method for the total price per item* @return the value of the total price per item*/public java.math.BigDecimal getTotalItemPrice(int index)

ABC Company Web site design and development 267

{return (java.math.BigDecimal)getAPILIB_SHPCART_SPRC(index).multiply(getAPILIB_SHPCART_SQTY(index));}

The above code adds a getter to the bean that allows you to retrieve the entiretotal for that item of the shopping cart.

6. Save this bean and close the code. You now need to recompile the bean sothe class file is up to date.

7. Right-click the ShoppingCart root directory. Select Check In.

8. Right-click the viewAllShoppingCartDBBean.java. Select Compile.

9. You are presented with a warning dialog box like the example in Figure 242asking if you wish to check out the .class too. Click Yes To All.

Figure 242. Check-out files Warning dialog box

10.Right-click on the ShoppingCart root directory, and select Check In.

7.4.5.2 Modifying the Shopping Cart Results pageNow that we have the new getter added to our bean and the source code hasbeen compiled, we need some way in which we can add this to our Shopping CartJSP page.

Perform the following steps to add item totals to the Shopping Cart page:

1. Double-click the viewAllShoppingCartResults.jsp. This checks the file outand opens it in Page Designer. Your page should look like the example inFigure 243.

Figure 243. viewAllShoppingCartResults.jsp before modification

268 Web Enabling AS/400 Applications with IBM WebSphere Studio

2. To add the bean property that you created, you need to add a new column tothe table. Click in the ProductID column. Select Table->Add Column->Addto the Right of Cell.

3. You can now see that another column has been added to the table. In the topcell of this new column, type the caption Total Unit Price.

4. Click in the bottom cell of this new column.

5. Insert the new bean property. Select Insert->Dynamic Elements->PropertyDisplay...

You are presented with the dialog box shown in Figure 244.

Figure 244. Property display attribute dialog box

6. Click the Browse button so you can select the property that you want todisplay. You should see a dialog box like the one shown in Figure 245.

Figure 245. Bean property selection dialog box

7. Select the totalItemPrice() getter to get back the total item price which isquantity multiplied by unit price. Click OK to continue.

8. viewAllShoppingCartDBBean.totalItemPrice() should appear in the Propertytext field in the Attribute window. Click OK to continue.

9. You should now see your page with the extra column and the newly addedJSP tag. The page should appear as shown in Figure 246 on page 270.

ABC Company Web site design and development 269

Figure 246. viewAllShoppingCartResults.jsp with total unit price

10.Save your new results page, and close the Page Designer.

11.Right-click the ShoppingCart root directory, and select Check In.

You now need to re-publish the updated files so as you can test the output of yournew Shopping Cart results page:

1. Right-click the ShoppingCart root directory, and select Publish wholeProject.

2. You would have seen the dialog box shown in Figure 247 before but, this time,we only want to publish modified files. Select the check box next to Publishonly modified files. Click OK.

Figure 247. Publishing options set to publish only modified files

3. You may be presented with a dialog box that asks if you want to replace somefiles. Click Yes.

Now that you have published these new files, you should be ready to look atthe resulting page.

270 Web Enabling AS/400 Applications with IBM WebSphere Studio

4. Right-click viewAllshoppingCartInput.html, and select Preview File with->Netscape. You are presented with the same input page you saw earlier inthis section.

5. Type a customer ID that you know exists in the database. After you click theSubmit button, you should be presented with a results page that looks like theexample in Figure 248.

Figure 248. Displaying the updated viewAllShoppingCartResults.jsp page in Netscape

7.4.6 Linking the shopping cart pagesNow that we have developed the shopping cart pages and tested them all toensure that they work as expected, it is time to link all pages together to create ashopping cart subsite. The final subsite will still not be pretty or have sessionmanagement integrated in to it, but it will show us the flow of the shopping cart.

The flow that we want to achieve here is to view the full shopping cart for onecustomer ID and have the user be able to select an individual item for editing ordeleting.

7.4.6.1 Modifying the viewAllShoppingCartResults.jsp pagePerform the following tasks to modify the Shopping Cart results page:

1. Double-click the viewAllShoppingCartResults.jsp. This checks out the fileand opens it in Page Designer.

2. You need to add a way of getting information from each row from this page tothe viewShoppingCartItem page. Click the Total Unit Price heading, andselect Table->Add Column->Add to the Right of Cell.

3. In the top cell of the new column, type Work With Item.

4. In the bottom cell of the new column, you need to add a form and a button.Select Insert->Form and Input Fields->Push Button->Submit Button. Youare presented with the dialog box shown in Figure 249 on page 272.

ABC Company Web site design and development 271

Figure 249. Push button attribute dialog box

5. For the parameters, set Name to editItem and Label to Edit Item. LeaveButton Type set to Submit. Click OK.

Your page should look like the example in Figure 250.

Figure 250. viewAllShoppingCartResults.jsp with modifications

Now that we have modified our page, we need to decide what information weneed to pass and to where we need to pass it. Follow these steps:

1. Browse through the Studio Workbench, and find the file calledviewShoppingCartItemInput.html. Double-click this file to open it in PageDesigner. It should look like the display in Figure 251.

272 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 251. viewShoppingCartItemInput.html

2. This page contains information about what servlet to call to view a single itemand what parameters the servlet takes. Double-click inside the text field nextto Customer ID. You should see the dialog box shown in Figure 252.

Figure 252. Text field attribute dialog box

3. Make note of the name of this text field. This text field is called custID. You willneed this information later. Click Cancel.

4. Do the same again for the text field next to Product ID. You see that the textfield name is productID. Again, you will need this information later.

5. Get the information about which servlet this page calls. Double-click inside thetext field next to the Customer ID label. You will see the same dialog box asbefore but, if you click in the drop-down list box next to Tag, you see thecaption Form in the list box. The form attribute dialog box should look like thedisplay in Figure 253 on page 274.

ABC Company Web site design and development 273

Figure 253. Form attribute dialog box

6. The parameter that you need to observe Figure 253 is Action. Make a note ofwhere this action points to, which is/servlet/ShoppingCart.viewShoppingCartItem.

Now that we have this information, we can return to theviewAllShoppingCartResults.jsp page, which should still be open in the PageDesigner. If it is not opened, double-click the file in the Studio Workbench. Followthese steps:

1. Double-click the Edit button you added last to this page.

2. You are presented with the button dialog box. You want the form properties soclick in the drop-down list box next to Tag, and select Form.

3. The Form properties should be blank. For Action, type:

/servlet/ShoppingCart.viewShoppingCartItem

4. Set Method to Post. The resulting form properties should appear as shown inFigure 254.

274 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 254. Form attribute dialog box

5. You now need to add some parameters to the forms hidden fields. Click theHidden Fields tab. You should see a dialog box like the example in Figure255.

Figure 255. Form attribute dialog box showing hidden fields

ABC Company Web site design and development 275

6. You need to add two hidden fields. The first hidden field represents thecustomer ID. Click the Name field, and type custID.

7. For the value of this parameter, specify it from a bean property. Under thevalue field, select the check box called Specify by property.

8. Click the Browse... button under the Value field. You should see a dialog boxlike the example in Figure 256.

Figure 256. Bean property selection dialog box

9. Select the customer ID property, APILIB_SHPCART_SCID(). Now, click OK.

10.In the Attribute window on the Hidden Fields tab, click Add to add thisparameter.

11.Repeat this process for adding the productID variable. In the Name field, typeproductID.

12.Under the Value field, select the Specify by property check box.

13.Click the Browse button under the Value field, and select theAPILIB_SHPCART_SIID() property. Click OK.

14.Click the Add button.

15.Your final Hidden Fields tabbed page should look like the example in Figure257.

The hidden fields can still be viewed by a user if they look at the source ofthe HTML documentation. The hidden fields should never contain a user’spassword or confidential stuff.

In our example, we are not too worried if they find out their customernumber because they cannot do much with it unless they login successfully.

Hidden fields

276 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 257. Hidden fields dialog box for viewAllShoppingCartResults.jsp

16.Click OK, save your page, and quit Page Designer.

17.Check all your files in the WebSphere Studio.

18.Publish only the modified files.

7.4.6.2 Testing the Shopping Cart pageWe are now ready to test the joining of these pages. When we run this test, weopen the viewAllShoppingCartInput.html file, and enter a customer ID value usedearlier. We should then see our shopping cart with buttons in the far right-handcell of the table. If we click one of these buttons, we should go to theviewShoppingCartItemResults.jsp and skip the input page for this. We are nowdynamically passing variables from one page to another.

Perform the following tasks to test the Shopping Cart page:

1. Right-click viewAllShoppingCartInput.html. Select Preview FileWith->Netscape.

You should see the page shown in Figure 258.

Figure 258. viewAllShoppingCartInput.html displayed in Netscape

ABC Company Web site design and development 277

2. Enter a customer ID for which you know there are shopping cart entries. Type0011. Click Submit.

You should see the page shown in Figure 259.

Figure 259. viewAllShoppingCartItemsResults.jsp displayed in Netscape

3. Click one of the Edit Item buttons. You should see the page shown in Figure260.

Figure 260. viewShoppingCartItemResults.jsp

See how we have used the WebSphere Studio Wizards to generate the pagesand then manually link them together. This makes the WebSphere Studio toolsvery powerful.

7.4.7 Changing the quantities of the items in the shopping cartNow that we have the two shopping cart pages linked together, we can edit theviewShoppingCartItemResults.jsp page so that we can edit and changequantities from our shopping cart.

7.4.7.1 Editing the Shopping Cart Item Results JSPPerform the following tasks to edit the Shopping Cart Item Results page to modifyitem quantities from the shopping cart:

278 Web Enabling AS/400 Applications with IBM WebSphere Studio

1. Double-click on viewShoppingCartItemResults.jsp. This checks out the fileand opens it in Page Designer.

2. Looking at this page, you can see that there is a table with a dynamic propertyloop around the body cells. This is good if we have many items to display, butnot for a single item. Unfortunately, the way the bean is generated from theDatabase Wizard requires a loop index parameter to access the results. Wecan think of this as a “dummy loop” that we know will only iterate through once.The page should appear like the example in Figure 261.

Figure 261. viewShoppingCartItemResults.jsp before modification

3. You need to make this page look better for presenting a single item. Click thetop line of the table so there is a pink border surrounding the table. Thismeans the whole table has been selected.

4. Right-click the pink border, and select Delete. This removes the table, and youare left with two JSP tags. The first tag is to execute the bean and the secondtag is to close the bean.

5. With the cursor between these two tags, press the Enter key a couple of times.This ensures that you do not get confused and accidently delete these tags.

6. You now need to insert a single cell table inside the dynamic loop. Go toTable->Insert Table Body...

7. In the Insert Table dialog box, set the columns to 1 and rows to 1. Click OK.

8. Double-click inside the table. Click the Table tab in the table attribute dialogbox and deselect the check box Show border so the table becomes invisible.

9. Click the Dynamic tab. This tabbed window allows you to set dynamic loopproperties for the table. Click the top loop check box. The direction does notmatter. The dialog box should look like the display in Figure 262 on page 280.

ABC Company Web site design and development 279

Figure 262. Dynamic loop attributes for a table

10.Click the Browse button. You should see the dialog box shown in Figure 263.

Figure 263. Dynamic loop attribute dialog box

11.For the loop property, use the product ID. Click the Browse... button. Thedialog box shown in Figure 264 should appear.

280 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 264. Bean property selection dialog box

12.Click the plus sign (+) next to viewItemShoppingCartDBBean. This displays allthe properties for viewItemShoppingCartDBBean.

13.Select the APILIB_SHPCART_SIID() property, and click OK.

14.Click OK in the Attribute window.

15.Add a form to this dynamic loop. Select Insert->Form and InputFields->Form.

16.Inside this form, type:

User Name :-Product Name :-Product Unit Price :-Product Quantity :-

17.Place the cursor next to User Name, and select Insert->DynamicElements->Property Display...

18.You should see the bean Attribute window. Click the Browse... button.

19.You now see the Bean Property Selection. Select APILIB_SHPCART_SIID(),and click OK.

20.Click the OK button in the Attribute window.

21.The JSP tag for this property is now added to the page. Your page should looklike the display in Figure 265 on page 282.

ABC Company Web site design and development 281

Figure 265. viewShoppingCartItemResults.jsp after slight modification

22.Repeat steps 17 through 20 using APILIB_SHPCART_SDSC() Bean PropertySelection to get the Product Name.

23.Repeat steps 17 through 20 using APILIB_SHPCART_SPRC() Bean PropertySelection to get the Product Name.

24.For the Product Quantity, use a text field so as this parameter can bechanged. Place the cursor next to Product Quantity :- and go to Insert->Formand Input Fields->Text Field.

25.You are presented with a dialog box for the text field attributes. For now, clickOK. You will return to the dialog box later.

26.Press Enter a couple of times after the text field. Click Insert->Form andInput Fields->Push Button->Submit Button.

27.You should see the Attribute window for the button. Give this button a name ofupdateQty and a caption of Update Item Quantity.

28.Click OK. The resulting page should appear as shown in Figure 266.

282 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 266. viewShoppingCartResults.jsp after modifications

We have now completed the modifications to this page to view the information fora shopping cart item. Follow these steps:

1. Browse through the Studio Workbench and find the file calledupdateShoppingCartQuantitiesInput.html. Double-click this file to open it inPage Designer. It should look like the display in Figure 267.

Figure 267. updateShoppingCartQuantitiesInput.html

2. To take the parameters from the text fields on this page and find out whatservlet is being called from the form. Double-click inside the text field next toNew Quantity. In the text field attribute window, note the name of the text field.In this case, it should be named newQty. Click the Cancel button.

3. Double-click in the field next to Customer ID. Again you should see theAttribute window. Make note of the name parameter which in should becustID. Click Cancel.

4. Double-click the field next to Product ID. You should see the Attribute window.Make note of the name parameter which should be productID. Click theCancel button.

ABC Company Web site design and development 283

5. Find the servlet to which this information is being sent. Double-click inside theform area. You will see an Attribute window, but it may not be looking at theform. Click in the drop-down list box next to the Tag caption. Select Form.Make a note of the Action parameter which is/servlet/ShoppingCart.updateShoppingCartQuantities. Click the Cancelbutton.

6. You can now close this file in Page Designer.

You now have all the information you need to go back and complete the ShoppingCart Item Results page. Now, follow these steps:

1. If it is not already open, double-click viewShoppingCartItemResults.jsp.This checks the file out and opens it in Page Designer.

2. You need to add the form parameters. Double-click in the text field next toProduct Quantity. This opens the Attribute dialog box.

3. In the Attribute dialog box, set the name to be newQty since this is the valuewe want to update.

4. For the initial value, click the Specify by property check box located justunder the Initial Value text field.

5. Click the Browse button just under the initial value text field to find the beanparameter to use here.

6. You see a Bean Property Selection window again. Select the propertyAPILIB_SHPCART_SQTY(). Then, click OK.

7. In the Attribute window, click OK.

8. Double-click inside the form. If the form properties are not shown, click thedrop-down list box next to the tag parameter, and select form.

9. For the action parameter, you need to specify the servlet to which this form willpost its information. For the action, type:

/servlet/ShoppingCart.updateShoppingCartQuantities

10.Click the radio button called Post to set the method.

11.Click on the Hidden Fields tab at the top of the Attribute window.

12.Click in the field next to the name caption, and type custID.

13.Click the Specify by Property check box under the value field, and then clickthe Browse button under the value field.

14.You should now see the Bean Property Selection dialog box. From here,select APILIB_SHPCART_SCID(). Then, click OK.

15.Click the Add button back in the Attribute window.

16.Follow steps 12 through 15, but use productID for the name of the hiddenfield and select APILIB_SHPCART_SIID(). Do not forget to click the Addbutton, otherwise the hidden field parameters will not be added.

17.Once you have completed this task, click OK.

18.Save this file, and close Page Designer.

284 Web Enabling AS/400 Applications with IBM WebSphere Studio

You now make one last change to the result page of the change quantity:

1. Double-click updateShoppingCartQuantitiesResults.jsp to check it out andopen it in Page Designer. The page should appear as shown in Figure 268.

Figure 268. updateShoppingCartQuantitiesResults.jsp

2. You can delete the entire contents of this page and write something slightlymore meaningful. Select Edit->Select All, and then click Delete.

3. Type Your update was successful.

4. Save this page, and then exit Page Designer.

5. You can publish and test our pages. In the Studio Workbench, right-click onthe ShoppingCart directory, and select Check In. Right-click again on theShoppingCart directory, and select publish whole directory. Make sure theonly publish modified files option is selected, and click OK. Click Yes for allprompts.

7.4.8 Testing the updated shopping cart for changing item quantitiesPerform the following tasks to test changing item quantities in the shopping cart:

1. In the Studio Workbench, select the file viewAllShoppingCartInput.html andright-click on it. Select Preview File with->Netscape. You should see thepage shown in Figure 269.

Figure 269. viewAllShoppingCartInput.html displayed in Netscape

ABC Company Web site design and development 285

2. Type a customer ID that is valid in your shopping cart table. We are using0011. Click the Submit button. You should see the page shown in Figure 270.

Figure 270. viewAllShoppingCartResults.jsp displayed in Netscape

3. Click the Edit Item button on any of the items shown. Go to the newly editedquantity page. This is the area you need to test. You should see a page similarto the example in Figure 271.

Figure 271. viewShoppingCartItemResults.jsp displayed in Netscape

4. Change the quantity in the Product Quantity field. Try a value of 60. Click theUpdate Item Quantity button. You should see the page shown in Figure 272.

286 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 272. updateShoppingCartQuantitesResults.jsp displayed in Netscape

Provided you see this final page, everything is working. You can check the tableto see if the update has happened. You could look at the table through the ViewShopping Cart Web page or look at the database table on the AS/400 system.

7.4.9 Deleting items from the shopping cartNow that we have the two shopping cart pages linked together, we can edit theviewShoppingCartItemResults.jsp page so that we can edit and delete items fromour shopping cart.

7.4.9.1 Editing the Shopping Cart Item Results JSPPerform the following tasks to edit the Shopping Cart Item Results page to deleteitems from the shopping cart:

1. Double-click viewShoppingCartItemResults.jsp. This checks the file out andopens it in the Page Designer.

You have already modified this page to change quantities, but now you needto add the ability to delete this item from the shopping cart.

2. Add a form in the bottom of the table below the update quantities form andbefore the end of the table. Select Insert->Form and Input Fields->Form.

3. While inside the new form that you have added, select Insert->Form andInput Fields->Push Button->Submit Button.

4. In the Attribute window, click OK.

Now that we have added our new form, we need to get some input parametersand the servlet that we call to do the delete. Follow these steps:

1. Double-click deleteShoppingCartItemInput.html. This checks the file outand opens it in Page Designer. The page should appear as shown in Figure273 on page 288.

ABC Company Web site design and development 287

Figure 273. deleteShoppingCartItemInput.html

2. Double-click in the text field next to the caption Customer ID. In the Attributesdialog box, you should see that it is called custID. Make a note of this. Clickthe Cancel button.

3. Double-click in the text field next to the caption Product ID. In the Attributesdialog box, you should see that the name is called productID. Make a note ofthis, and click the Cancel button.

4. Double-click in the form to open the Forms Attribute dialog box. The actionparameter should be /servlet/ShoppingCart.deleteShoppingCartItem.Make a note of this, and click the Cancel button.

We now have all the information we need to complete the Shopping Cart Itempage. Follow these steps:

1. Open the viewShoppingCartItemResults.jsp page in Page Designer.

2. Double-click the Submit button that is down at the bottom of the page. Thisshould give you the buttons attribute dialog box.

3. Type delete for the name, and type Delete for the label.

4. Select the form from the drop-down list box next to the tag caption.

5. For the action of this form, type:

/servlet/ShoppingCart.deleteShoppingCartItem.

6. Set the method to Post.

7. Click the Hidden Fields tab.

8. Type for the first hidden field custID.

9. For the value, click the Specify by Property button.

10.For the value, click the Browse... button.

11.Select from the bean property selector APILIB_SHPCART_SCID().

12.Click the OK button.

13.Click the Add button.

288 Web Enabling AS/400 Applications with IBM WebSphere Studio

14.Repeat steps 8 through 13, but use product ID for the name of the hidden field,and select APILIB_SHPCART_SIIDC. Do not forget to click the Add button.Otherwise, the hidden field parameters will not be added

15.Click OK.

The page should now look similar to the example in Figure 274.

Figure 274. viewShoppingCartItemResults.jsp with the delete button added

16.Save this page and close Page Designer.

We now make one last change to the result page of the change quantity. Followthese steps:

1. Double-click deleteShoppingCartResults.jsp to check it out and open it inthe Page Designer. The page should appear as shown in Figure 275.

Figure 275. deleteShoppingCartResults.jsp before modifications

2. You can delete the entire contents of this page and write something slightlymore meaningful. Select Edit->Select All, and then click Delete.

3. Now, type Your delete was successful.

ABC Company Web site design and development 289

4. Save this page, and then exit Page Designer.

5. Again, you need to check in all files in WebSphere Studio and publish only themodified files. Once this is done, you are ready for testing.

7.4.10 Testing the updated shopping cart for deleting itemsPerform the following tasks to test deleting items from the shopping cart:

1. In the Studio Workbench, select the file viewAllShoppingCartInput.html andright-click on it. Select Preview File with->Netscape. You should see thepage shown in Figure 276.

Figure 276. viewAllShoppingCartInput.html displayed in Netscape

2. Type a customer ID that is valid in your shopping cart table. We are using0011. Click the Submit button. You should see the page shown in Figure 277.

Figure 277. viewAllShoppingCartResults.jsp

3. Click the Edit Item button on any of the items shown. Now, go to the newlyedited quantity page. This is the area we need to test. You should see a pagesimilar to the display in Figure 278.

290 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 278. viewShoppingCartItemResults.jsp displayed in Netscape

4. Click the Delete button. You should see a final result page that looks like theexample in Figure 279.

Figure 279. deleteShoppingCartItemResults.jsp displayed in Netscape

5. Provided you see this final page, everything should have worked. You cancheck if the item has been deleted by looking at the shopping cart databasetable on the AS/400 system or by looking at the shopping cart again.

7.5 Creating the order purchase subsite

The Purchase function, as represented on the ABC Company Web site, does notincorporate business logic to calculate available inventory, apply discounts, andplace the order records into the company’s enterprise database. As you recallfrom the earlier sections, we keep business logic with rules and policies insideexisting server databases and applications, where we have proper and necessarydata or information, security, and performance to conduct business transactions.Also, rewriting existing order processing and inventory management applicationsdoes not make a lot business sense.

ABC Company Web site design and development 291

The order purchase function on the Web site processes shopping cart contentsand packages them into parameters to be passed to the server program. The laststep is to call the existing AS/400 server program. The AS/400 server programthen takes over with order creation procedures. The server program we arereferring to is not the servlet that packages and calls the RPG program, but theRPG program itself. Our servlets carry little or no business logic. In this particularexample, the servlet knows how to package and submit the AS/400 RPGprogram.

To develop order purchase functionality, we use Studio Wizards and Studio PageDesigner tools. To completely achieve desired functionality, we alter StudioWizards generated servlets, JSPs, and HTML files.

The following is a conceptual representation of what it takes to submit an order:

1. Read the shopping cart contents.

2. Create order objects based on shopping cart contents (optional).

3. Package the order information into two strings to be passed to the AS/400server program.

4. Call the AS/400 server program to process the order with existingapplications.

5. Produce a confirmation page.

7.5.1 Creating the order purchase projectTo build the order purchase subsite, we need to create a new project. Followthese steps to create the new Order Purchase project folder:

1. Start WebSphere Studio if it is not already started.

2. Create a new project by selecting File->New Project from the pull-downmenu.

3. Type OrderPurchase for the project name.

4. Type drive:\subsites\OrderPurchase for the project folder.

5. Select <none> for project template.

6. Click OK.

WebSphere Studio creates the folder \subsites\OrderPurchase and the projectfile called OrderPurchase.wao. Within the project, WebSphere Studio alsocreates the servlet folder.

To accomplish the task of submitting an order and mostly to rely on WebSphereStudio Wizards, we perform the following steps:

1. Create SELECT SQL for the SHPCART table, using the SQL Wizard.

2. Based on the SQL created in step 1, create a servlet, DB access bean, inputHTML and JSPs, using the Database Wizard, to display the shopping cart andaccept user entries for later submission of the order to be processed on theAS/400 server.

3. Modify the resulting JSP from step 2 using Page Designer to add the form tosubmit the order to the AS/400 server for further processing.

292 Web Enabling AS/400 Applications with IBM WebSphere Studio

4. Based on the SQL created in step 1, create a servlet, DB access bean, andJSPs, using the Database Wizard. In doing so, you package the shopping cartcontents into parameters and call the RPG program to create the order onAS/400 server within existing enterprise database.

5. Write the Java code to retrieve the order information from the bean and to callthe application program on the AS/400 system. Insert the code into theshopping cart retrieval servlet.

6. Create SELECT SQL for the ORDERS table, using the SQL Wizard, to retrievethe newly created order record.

7. Based on the SQL created in step 6, create a servlet, DB access bean, andJSPs, using the Database Wizard. In doing so, you display the resulting orderrecord as confirmation of the successful order processing on AS/400 server.

8. Create DELETE SQL for the SHPCART table, using the SQL Wizard, to emptya shopping cart upon successful order processing.

9. Based on the SQL created in step 8, create a servlet, DB access bean, andJSPs, using the Database Wizard. In doing so, you delete the shopping cartcontents upon successful order processing on the AS/400 server.

10.Combine the resulting JSPs from steps 4 and 7.

7.5.2 Creating SELECT SQL for the SHPCART tablePerform the following tasks that run the SQL Wizard to create an SQL statementthat selects all items from the shopping cart:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder Shopping Cart.

3. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

4. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 34.

Table 34. Information to be entered in the SQL Wizard

Tabbed window Action explanation

Welcome Enter selectCart as the name of the query. The wizard addsan .sql file in your project.

Click Next.

ABC Company Web site design and development 293

Logon Enter the information the wizard needs to connect to thedatabase, for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user id and password; bothshould be in uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click on theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is APILIB in this case. Click onthe library to select it, and click the Add button.

Click OK to return to the Tables window.

Click the Select radio button in the Statement type.

Select APILIB.SHPCART from the list of tables shown.

Click Next.

Join No action is required.

Click Next.

Columns Select only the SCID, SCSD, SIID, SPRC, and SQTY columnsto be included in the output result.

Click the Add button.

Click Next.

Condition 1 Specify SCID to be equal to the cust parameter.

Note: The cust parameter is passed to the servlet.

Click Next.

Sort No action is required.

Click Next.

Tabbed window Action explanation

294 Web Enabling AS/400 Applications with IBM WebSphere Studio

5. Check the generated file selectart.sql into the Studio Workbench. Select theOrderPurchase folder. Then, right-click, and select the Check In option.

7.5.3 Creating servlet and DB access bean for SHPCART select queryIn this section, we create the servlet and the DB access bean to get the result ofSHPCART select query, which should return the shopping cart contents found forthe particular customer CSTMR. Follow these steps:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder OrderPurchase.

3. Start the SQL Wizard by selecting Tools->Wizards->Database Wizard.

4. Select the appropriate SQL Statement, which you created in 7.5.2, “CreatingSELECT SQL for the SHPCART table” on page 293. It should bedrive:\subsites\OrderPurchase\selectCart.sql.

5. Click Next.

6. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 35.

Table 35. Information to be completed in the Database Wizard

SQL No action is required.

This tab shows the complete SQL statement. You can copy thestatement to the clipboard to use it in another application. Youcan also test the SQL statement by clicking the Run SQLbutton.

Click Next.

Finish Click Finish.

The completed SQL file should appear in the project asselectCart.sql.

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You need an input page to collect the data forinsertion, an output page to show the result from the query, andan error page if something unforeseen happens. You also needto:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.d. Select the no data is returned check box.

Click Next.

Input Page The input page does not require any parameters.

Click Next.

Tabbed window Action explanation

ABC Company Web site design and development 295

7. Check all of the generated files (all files having the cartSelect prefix) into theStudio Workbench. Select the OrderPurchase folder. Then, right-click, andselect the Check In option.

8. Publish the project to the AS/400 server. Follow the same steps outlined in4.3.1, “Publishing to the AS/400 system” on page 125.

Results Page The results page already has the output parameters you wantedfrom the SQL file. These should be SDSC, SPRC, and SQTY.

Select the parameters by clicking on the row. Click the Changebutton to change the caption to a more meaningful name. You canalso change the field sizes. Repeat this for the followingparameters:

• For SDSC, type Product Description• For SPRC, type Product Price• For SQTY, type Product Quantity

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click Next.

No Data Page Click Next.

Methods Make sure that the method named execute() is selected.

Click Next.

Session There is really no need to store this bean in the session. This beanwill be used just to display shopping cart contents and collectother information from the user. Make sure No is selected.

Name the bean cartSelectDBBean.

Click Next.

Finish Give a meaningful name to the generated source files. Click theRename button, and type cartSelect into the Prefix dialog.Click OK. Note that all of the files now have the prefix ofcartSelect.

Click Finish to generate the code.

The Database Wizard generates and compiles the files. The filesare placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

296 Web Enabling AS/400 Applications with IBM WebSphere Studio

7.5.3.1 Unit testing the shopping cart contents retrievalNow that the Order Purchase Web page has been built, we should test it to see ifthe results are what we want. It is much easier to fix the pages at this point ifthere is a problem.

Perform the following steps to test the order purchase subsite:

1. To perform the unit test, make sure the SHPCART table is not empty. Refer to7.4, “Shopping cart subsite” on page 246, for an explanation on creating andpopulating the shopping cart table with sample records.

2. Make sure you have your publishing target setup. Refer to 4.3.1, “Publishing tothe AS/400 system” on page 125, if you have not done this yet.

3. Right-click on the OrderPurchase project folder in the Studio Workbench andselect Publish whole Project. This publishes the entire Catalog project toyour defined server, which is an AS/400 server in our case.

4. Once you have published your Web pages, make sure your WebSphereApplication Server and Web server are both started.

5. To test retrieving all items from the shopping cart, select thecartSelectInput.html file. Then, right-click, and select Preview file withNetscape or Internet Explorer.

6. When the Web browser appears fill out the form, then click the Submit button.The form appears as shown in Figure 280.

Figure 280. Unit testing SELECT from SHPCART table

7.5.4 Modifying the resulting page of the shopping cart selectionIn this section, we modify cartSelectResult.jsp to add input fields for the user toenter information. We also add the form with the Submit and Reset buttons toinvoke the servlet, which instantiates another bean and calls the AS/400 serverprogram.

7.5.4.1 Modifying the resulting JSP cartSelectResult.jspPerform the following steps to modify the cartSelectResult.jsp file:

1. Double-click cartSelectResult.jsp to open it for editing in Page Designer. Youshould see the window as shown in Figure 281 on page 298.

ABC Company Web site design and development 297

Figure 281. Original look of cartselectResult.jsp

2. Fix the table headings. Highlight the headings and type something a user canread and understand.

3. Add the form (select Insert->Form and Input Fields) with input fields andSubmit and Reset buttons.

4. Examine the page in Figure 282 to get the idea of what the page should looklike after the modifications.

Figure 282. cartselectResult.jsp after modifications

5. Leave the form action blank for now. However, the form method radio buttonshould reflect the Post setting (Figure 283).

298 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 283. Form attributes on cartselectResult.jsp

Note: Credit card information input fields are on the page for illustration purposesonly. It is generally accepted to collect this kind of information in e-commerceapplications. In our scenario, this user entered information that was not taken intoconsideration.

We added the form with the Submit button to have the means to invoke (call) theservlet, which will:

• Instantiate a bean with shopping cart data.

• Upon successful retrieval of the shopping cart contents, format, package, andsubmit the order onto the AS/400 server for further processing.

In the next section, we create the servlet, the bean, and the resulting pages.

7.5.5 Creating the servlet, DB access bean, and JSPs to submit the orderIn this section, we create the servlet and the DB access bean to get the result ofthe shopping cart select query, which should return the shopping cart contentsfound for the particular customer. We then retrieve the data from the bean toformat and package the order to be sent as parameters for the call to the AS/400RPG program. We need to create another bean to hold shopping cart contents,since we cannot use cartSelectDBBean, because we need more information inthe new bean. Follow these steps:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder OrderPurchase.

3. Start the SQL Wizard by selecting Tools->Wizards->Database Wizard.

ABC Company Web site design and development 299

4. Select the appropriate SQL statement, which you created in 7.5.2, “CreatingSELECT SQL for the SHPCART table” on page 293. It should bedrive:\subsites\OrderPurchase\selectCart.sql.

5. Click Next.

6. Proceed through the tabbed windows of the wizard, and specify theinformation in Table 36.

Table 36. Information to be entered in the Database Wizard

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You need an input page to collect the data for insertion,an output page to show the result from the query, and an errorpage if something unforeseen happens. You also need to:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.d. Select the no data is returned check box.

Click Next.

Input Page The input page does not require any parameters.

Click Next.

Results Page Make sure all the fields (columns) from the shopping cart table(SHPCART) are selected.

Select the parameters by clicking on the row. Click the Changebutton to change the captions to a more meaningful names. Youcan also change the field sizes. Repeat this for all the parameters.

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click Next.

No Data Page Click Next.

Methods Make sure that the method named execute() is selected.

Click Next.

Session There is really no need to store this bean in the session. This beanwill be used just to display shopping cart contents and collectother information from the user. Make sure No is selected.

Name the bean sbmOrderDBBean.

Click Next.

300 Web Enabling AS/400 Applications with IBM WebSphere Studio

7. Check all of the generated files (all files having the sbmOrder prefix) into theStudio Workbench. Select the OrderPurchase folder. Then, right-click, andselect the Check In option.

8. Publish the project to the AS/400 server. Follow the same steps outlined in4.3.1, “Publishing to the AS/400 system” on page 125.

9. Unit test is optional since this bean is similar to cartselectDBBean. However,you may still verify your work.

10.To test the order purchase submit, select the sbmOrderInput.html file. Then,right-click, and select Preview file with Netscape or Internet Explorer.

11.Enter a customer ID, which has entries in the shopping cart table. Then, clickSubmit.

Upon successful execution, you should see the shopping cart order contents.

7.5.6 Developing Java code to package and submit the order to the AS/400 serverIn this section, we develop Java code to retrieve shopping cart data from thesbmOrderDBBean, format the data appropriately, package it into two parameters,and finally call the AS/400 server program to take over with the order creationprocess. We show different ways of calling the AS/400 server program using theAS/400 ToolBox for Java. We also explain where to insert the Java code and why.

The functional flow is presented here:

1. The sbmOrder servlet is invoked by the Post method from the form inside thesbmOrderInput.html, with cust as a parameter representing cust ID. Later itwill be called from the cartSelectResults.jsp.

Refer to 7.5.13, “Creating a self-contained order purchase subsite” on page336, for an explanation on how cartSelectResult.jsp calls the sbmOrder servletwith the cust ID parameter.

2. The sbmOrder servlet instantiates sbmOrderDBBean. At this stage, the servletalso executes the bean’s setter methods.

Finish Give a meaningful name to the generated source files. Click theRename button and type sbmOrder into the Prefix dialog. ClickOK. Note that all of the files now have the prefix of sbmOrdert.

Click Finish to generate the code.

The Database Wizard generates and compiles the files. The filesare placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

ABC Company Web site design and development 301

3. The sbmOrder servlet calls the execute() method of sbmOrderDBBean, whichruns the SQL statement and loads the bean’s properties with the shoppingcart data.

4. We insert our order retrieval code (retrieval from the bean) right after theexecute() method. We later explain why precisely after the execute() method

5. We insert the following methods inside the sbmOrder servlet (not inside theperformTask(...) method, where the execute() method is called):

• The prepare_submit_Order() method to package and format order dataaccording to AS/400 server program’s parameters specifications

• The submitOrder() method to call the AS/400 server program and passparameters

Inside the sbmOrder servlet, bean instantiation and the execute() method occurinside the Java language try { } block, which is followed by the catch { } block,all inside the performTask(...) method. Refer to the code extract shown in Figure284.

If we are to insert the code inside the servlet to access the sbmOrderDBBeanbean’s properties and methods, we need to do it inside the try { } block.Otherwise, any reference to the bean’s properties and methods is out of thescope of this redbook. The Java compiler produces a Can’t make static reference

to ... error message if an attempt is made to call a bean’s method.

Our strategy is to insert order processing code, which requires access to thebean’s methods, inside the try { } block, and the rest of the code(prepare_submit_Order() and submitOrder() methods) can be inserted anywhereoutside of performTask(...) method. There will be a couple of exceptions, whichwe will explain in detail.

302 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 284. The performTask() method inside the sbmOrder servlet

/****************************************************************************** Process incoming requests for information** @param request Object that encapsulates the request to the servlet* @param response Object that encapsulates the response from the servlet*/public void performTask(HttpServletRequest request, HttpServletResponse response){

try{

// instantiate the beans and store them so they can be accessed by the called pageOrderPurchase.sbmorderDBBean sbmorderDBBean = null;sbmorderDBBean = (OrderPurchase.sbmorderDBBean)

java.beans.Beans.instantiate(getClass().getClassLoader(), "OrderPurchase.sbmorderDBBean");

setRequestAttribute("sbmorderDBBean", sbmorderDBBean, request);

// Initialize the bean userID property from the parameterssbmorderDBBean.setUserID(getParameter(request, "userID", true, true, false, null));

// Initialize the bean password property from the parameterssbmorderDBBean.setPassword(getParameter(request, "password", true, true, false, null));

// Initialize the bean URL property from the parameterssbmorderDBBean.setURL(getParameter(request, "URL", true, true, false, null));

// Initialize the bean driver property from the parameterssbmorderDBBean.setDriver(getParameter(request, "driver", true, true, false, null));

// Initialize the bean cust property from the parameters

sbmorderDBBean.setCust(getParameter(request, "cust", true, true, true, null));

// Call the execute action on the bean.sbmorderDBBean.execute();

// Call the output page. If the output page is not passed// as part of the URL, the default page is called.callPage(getPageNameFromRequest(request), request, response);

}

// handle com.ibm.webtools.runtime.NoDataExceptioncatch (com.ibm.webtools.runtime.NoDataException theException){try{callPageNamed(getParameter(request, "com.ibm.webtools.runtime.NoDataException", true, true,

false, "com.ibm.webtools.runtime.NoDataException"), request, response);}catch (Throwable e){handleError(request, response, theException);

}}

catch (Throwable theException){handleError(request, response, theException);

}

}

ABC Company Web site design and development 303

You should note that the final code produced may not be the most elegant andstylish. However, we heavily use the Studio Wizards, which tremendously reducethe amount of code to be written, yet provide most of the functionality required.We could have inserted the code straight into the bean. However, it would thenseize being just a bean, since database access beans are only designed toretrieve the data and provide access to the data via the getters.

7.5.6.1 Retrieving the order data from the beanIt is quite easy and straight forward to get the order data from the bean. Callingthe appropriate getter methods achieves the goal. We need to format andpackage the order data to be passed in the form of parameters to the AS/400server program. We could have only formatted and packaged the order data tocomply with parameters’ specifications of the called AS/400 program, but we tookit one step further.

The model we preferred is optional, but it can be extremely useful. Before theorder data gets formatted and packaged for submission (the call to the AS/400server program), we construct Order and OrderDetail objects. The benefit is:

• To demonstrate how to import files into WebSphere Studio and make theclasses not generated by the Studio Wizards work.

• Have the objects available to build upon in the future.

The Order and OrderDetail objects are Order.java and OrderDetail.java classesrespectively. The class files contain constructors and methods associated withmanipulations on the order data.

The Order class is examined here:

public class Order{

private StringBuffer customerId = new StringBuffer(4);private OrderDetail[] entryArray = new OrderDetail[50];private int index = -1;private int cursor = 0;

}

As shown, an Order object contains an array of OrderDetail objects. The size ofthis array is arbitrarily set to 50. You can also use a vector, which avoids having todetermine a size in advance. Vectors allow dynamic allocation, where arrays donot.

The customerId field is declared as a StringBuffer, rather than a String. This isbecause leading zeros may have to be inserted. The AS/400 system program thatis eventually called expects a buffer of character data. Certain fields need to havespecific lengths, so offsets are predictable. The customerId field must always bea length of 4. If the customerId retrieved from the bean is 10, then two leadingzeros must be inserted to yield 0010. This is shown in the constructor:

public Order ( String cid){

// Set the customer id making sure leading zeros are// included.for(int i=0;i<4-cid.length( );i++){

customerId.append('0')}

304 Web Enabling AS/400 Applications with IBM WebSphere Studio

customerId.append(cid);}

The OrderDetail class is shown here:

public class OrderDetail{StringBuffer itemId = new StringBuffer(6);StringBuffer itemDsc = new StringBuffer(24);BigDecimal itemPrice = null;BigDecimal itemQty = null;

}

As in the Order class, certain data members have a specific length. In this case,itemId and itemDsc are declared as StringBuffer types. In some cases, theconstructor must add leading zeros to the itemId. It may also have to add trailingblanks to itemDsc. The constructor, is shown in Figure 285.

Figure 285. OrderDetail class constructor

Now that you have a fair understanding of the Order and OrderDetail classes, letus examine the code to create and initialize the Order and OrderDetail objectsusing the bean’s data.

7.5.6.2 Inserting Order and OrderDetail files into WebSphere StudioFirst of all, we import the Order.java and OrderDetail.java classes into theWebSphere’s OrderPurchase project. Follow these steps:

1. Copy the Order.java and the OrderDetail.java files into the\subsites\OrderPurchase\servlet\OrderPurchase folder using the WindowsExplorer or a copy command issued from command prompt.

public OrderDetail( String itemId,String itemDsc,BigDecimal itemPrice,BigDecimal itemQty)

{// set the itemId making sure leading zeros are therefor(int i=0;i<6-itemId.length();i++){

this.itemId.append('0');}this.itemId.append(itemId);

// set the description making sure trailing blanks are therethis.itemDsc.append(itemDsc);for(int j=itemDsc.length()+1;j<25;j++){

this.itemDsc.append(' ');}

this.itemPrice = itemPrice;this.itemQty = itemQty;

}

ABC Company Web site design and development 305

2. Highlight the OrderPurchase package under the servlet folder inside theStudio Workbench to make sure the Order.java will be inserted there.

3. Inside the Studio Workbench, click Insert->File.

4. Click the Use Existing tab to insert the existing Order.java file, rather thangenerate one based on a template.

5. Click the Browse button to select the Order.java file, and then click the OKbutton.

The Order.java file should now be visible inside Studio Workbench. Repeat thesame steps for the OrderDetail.java file.

Make sure, the Order and OrderDetail classes contain the following statement toindicate the package name:

package OrderPurchase;

7.5.6.3 Modifying the sbmOrder servlet to create and package orderobjectsPerform the following tasks to edit and modify the sbmOrder servlet:

1. Open the sbmOrder servlet for editing.

2. Specify the import statements to import the Order and OrderDetail classes intothe sbmOrder servlet. Type the following statements into the sbmOrder.java

servlet:

// Order objects and math package to use for data type conversionsimport OrderPurchase.Order;import OrderPurchase.OrderDetail;import java.math.*;

3. Insert the code to get the data from sbmOrderDBBean to instantiate andinitialize the Order and the OrderDetail objects. Immediately after the followinglines, in sbmOrder.java, enter:

// Call the execute action on the bean.sbmorderDBBean.execute();

4. Insert the code segment shown in Figure 286.

306 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 286. Retrieving order data from the bean to the package and submit order

Let us examine the code segment in Figure 286 to retrieve the order data fromsbmOrderDBBean. First, we find out how many rows are in the result set of theSQL run by sbmOrderDBBean. The bean has the following instance variable:

/*** Variable for the SelectResult - the SQL result set*/protected SelectResult result;

One of the methods in the result object is getNumRowsInCache(), which returnsthe number of rows in the SQL result set as an integer. To call the method, wefully qualify its name:

int numEntries = sbmorderDBBean.result.getNumRowsInCache();

Next, we construct the Order object by passing the cust Id, which we get from thebean via the getter method:

// Instantiate the Order objectOrder theOrder = new Order(sbmorderDBBean.getCust());

Then, we construct the OrderDetail objects for every row (detail record) retrievedfrom the bean. Therefore, we do it inside the loop. To get the data elements fromthe result set in the bean, we call the getter methods. We take whatever thegetter method returns and convert it to the string by running the toString()

method.

Since the Order object contains the array of OrderDetail objects, we execute thefollowing line (the method from the Order object), also in the loop:

theOrder.addEntry(detail);

Finally, in the inserted code block, we call a method to prepare the parametersand call the AS/400 server program:

// Retrieve data from the bean

// Get the number of rows retrieved from shopping cartint numEntries = sbmorderDBBean.result.getNumRowsInCache();

// Instantiate the Order objectOrder theOrder = new Order(sbmorderDBBean.getCust());

// Instantiate the OrderDetail objects and add them to the Order object// The number of iterations in the loop depends on the number of records in the shopping cartfor (int i = 0; i < numEntries; i++) {OrderDetail detail = new OrderDetail(sbmorderDBBean.getAPILIB_SHPCART_SIID(i).toString(),

sbmorderDBBean.getAPILIB_SHPCART_SDSC(i).toString(),new

BigDecimal(sbmorderDBBean.getAPILIB_SHPCART_SPRC(i).toString()),new

BigDecimal(sbmorderDBBean.getAPILIB_SHPCART_SQTY(i).toString()));theOrder.addEntry(detail);

}// Prepare and submit an order to the AS/400 to processif (prepare_submit_Order(theOrder) == true) {

}

ABC Company Web site design and development 307

// Prepare the order and call AS/400 programprepare_submit_Order(theOrder);

Let us recall the flow up to this point in the code. The sbmOrder servlet instantiatesthe sbmOrderDBBean bean and calls the sbmOrderDBBean.execute() method,which executes the SQL statement and loads the bean with order data from theshopping cart table (SHPCART) on the AS/400 system. We inserted the code tocreate the Order and the OrderDetail objects. Next, we call theprepare_submit_Order() method and pass the Order object as a parameter. Thecode in Figure 287 should be inserted after “}” of the following method:

public void performTask(HttpServletRequest request, HttpServletResponseresponse)

Figure 287. prepare_submit_Order method to be inserted into the sbmorder servlet

The prepare_submit_Order() method builds the constructs that are used asparameters when starting the AS/400 server program, which processes orders(ORDENTR), but in reality we call ORDENTRCL. This program requires twoparameters.

The first parameter is a string that is a concatenation of the customer ID and thenumber of entries in the order. This data is fixed in length. The first 4 bytes aredesignated for the customer ID, while the last 5 bytes are for the number ofentries. The ORDENTR program moves the customer ID data into a characterfield that has a length of 4 bytes. The last 5 bytes are moved to a zoned numericfield. These 9 bytes of data are the first 9 bytes in the string that is returned byOrder.toString().

The second parameter is a block of character data that represents all of the detailentries in the order. This data is sent as one contiguous block of character data tothe ORDENTR program that parses the data. This block of data is also part of thestring that is returned by Order.toString(). It begins at offset 9 of the string.

Since the AS/400 server program that processes orders (ORDENTR) expects allcharacter data, a toString() method is provided in the Order class. This methodconverts the Order object into one contiguous string. The string may be viewedas a buffer with the following breakdown:

/* This method builds the constructs that are used as parameters when invoking the AS/400program that processes orders. One parameter is required by this method, the Order object,which contains the cust Id and order detail data.*/void prepare_submit_Order(Order theOrder) {

String orderString = theOrder.toString();StringBuffer headerBuffer = new StringBuffer(9);headerBuffer.append(orderString.substring(0, 9));StringBuffer detailBuffer = new StringBuffer(orderString.length() - 9);detailBuffer.append(orderString.substring(9));

// now invoke submitOrder() and pass the 2 parmssubmitOrder(headerBuffer.toString(), detailBuffer.toString());return;

}

308 Web Enabling AS/400 Applications with IBM WebSphere Studio

• Starting at offset 0 for a length of 4 bytes: The customer ID• Starting at offset 4 for a length of 5 bytes: The number of detail entries• Starting at offset 9 with varying length: Multiple 40-byte segments

Each 40-byte segment represents a single detail record that consists of an itemID, name, price, and quantity. See the OrderDetail.toString() method for agranular breakdown of a detail record. Figure 288 shows the toString() methodfor the Order class.

Figure 288. The toString() method of the Order class

The OrderDetail class also provides a toString() method. Once again, thisfacilitates the call to the AS/400 server program that accepts parameters ascharacter data. The toString() method converts the orderDetail object to a bufferof 40 characters with certain offsets that are designated as starting points ofcertain data members. The breakdown of the orderDetail buffer is:

• Starting at offset 0 for 6 bytes: The item ID• Starting at offset 6 for 24 bytes: The item name (description)• Starting at offset 30 for 5 bytes: The price• Starting at offset 35 for 5 bytes: The quantity ordered

public String toString(){// declare a StringBufferStringBuffer orderBuffer =

new SringBuffer(9+(40*getNumEntries()));// append the customerId to the bufferorderBuffer.append(customerId);// convert the number of entries to a string of 5 bytes// and be sure to include leading zerosStringBuffer numEntryBuffer = new StringBuffer(5);String numEntryString = Integer.toString(getNumEntries( ));

for(int i=0;i<5-numEntryString.length( );i++){

numEntryBuffer.append('0');}numEntryBuffer.append(numEntryString);

// append the number of entries string to the order bufferorderBuffer.append(numEntryBuffer);

// now append a string representation of all entries to// the bufferOrderDetail entry = getFirstEntry();

while(entry != null){

// append a string representation of the detail entry// this is done by invoking the toString( ) method that// is provided by the OrderDetail classorderBuffer.append(entry.toString( ));entry = getNextEntry( );

}

// return the complete StringBuffer as a String// this is done by invoking the toString( ) method that is// provided by Java's StringBuffer classreturn orderBuffer.toString( );

}

ABC Company Web site design and development 309

Figure 289 shows the toString() method for the OrderDetail class.

Figure 289. The toString() method of the OrderDetail class

In the next section, we examine the method that is responsible for calling anAS/400 server program, passing parameters, and some error handling.

7.5.7 Calling the AS/400 server program to submit the orderAfter setting up the two parameters, prepare_submit_Order() calls thesubmitOrder() method. We demonstrate two ways to call the AS/400 serverprograms:

• Using the Distributed Program Call (DPC) class provided by the AS/400Toolbox for Java

public String toString( ){

StringBuffer entryBuffer = new StringBuffer(40);entryBuffer.append(itemId);entryBuffer.append(itemDsc);

// convert price field to String, remove// decimal point, and make sure leading// zeros are thereStringBuffer priceBuffer = new StringBuffer(5);String priceString = itemPrice.toString();// find out the position of the decimal pointint decimalPosition = priceString.indexOf('.');// create a new string that contains the digits// before the decimal pointString priceString1=

priceString.substring(0,decimalPosition);// create a new string that contains the digits// after the decimal pointString priceString2 = priceString.substring(decimalPosition+1)// now combine the 2priceString = priceString1 + priceString2;

// insert any needed leading zerosfor(int i=0;i<5-priceString.length();i++){

priceBuffer.append('0');}priceBuffer.append(priceString);// now append it to the entry bufferentryBuffer.append(priceBuffer);

// convert the quantity field to String and make sure// it is 5 bytesStringBuffer qtyBuffer = new StringBuffer(5);String qtyString = itemQty.toString();for(int i=0;i<5-qtyString.length();i++){qtyBuffer.append('0');

}qtyBuffer.append(qtyString);// now append it to the entry bufferentryBuffer.append(qtyBuffer);

// now return the whole entry as a Stringreturn entryBuffer.toString();

}

310 Web Enabling AS/400 Applications with IBM WebSphere Studio

• Using PCML classes also provided by the AS/400 Toolbox for Java

To use AS/400 Toolbox for Java DPC and PCML classes to call a program onAS/400 server, the following import statements are needed inside the sbmorderservlet:

// Creating AS400 object to call AS/400 programimport com.ibm.as400.access.*;

// PCML Example importsimport com.ibm.as400.data.ProgramCallDocument;import com.ibm.as400.data.PcmlException;

Both DPC and PCML methods require the creation of the object of AS/400 type toaccess the AS/400 server. Creation of the object of the AS/400 type requires thefollowing parameters: system name, user ID and password. Declare the followingvariables to have the global scope (at the sbmOrder.java class level):

String pgmcallURL;String pgmcallUserID;String pgmcallpwd;

At some point during execution, the variables need to be initialized. We initializethe variables inside the try {} block of the performTask() method right after thecall to execute() method. Recall the reason we have to do it inside the try {}

block after the execute() method. We do it inside the try {} block to be in thesame scope to access the bean’s methods and properties. We do it after theexecute() method because it loads the bean’s properties with data from thedatabase or passed parameters.

// Initialize this variables to be used by submitOrder() method to create as400objectpgmcallURL = sbmorderDBBean.getURL();pgmcallUserID = sbmorderDBBean.getUserID();pgmcallpwd = getParameter(request, "password", true, true, false, null);

In the following section, we examine the submitOrder() method using DPC.

7.5.7.1 Calling the AS/400 server program using the DPC classThe submitOrder() method calls the ORDENTCL program on the AS/400 systemusing the Distributed ProgramCall class (DPC). Figure 290 on page 312 showsthe code listing and analysis for the submitOrder() method to be inserted after theprepareOrder() method.

First, we do a couple of declarations. We declare and initialize an AS/400 objectusing system name, user ID and password. We call the object as400System.Recall the global variables from the previous section. We use them to create theas400System object of AS/400 type. Also, in case a call fails, we declare msgIdand msgText to hold the values to output them to standard out.

When a servlet issues output to stdout, the WebSphere Application Serverplaces the output inside the jvm_stdout.log file located inside applicationserver’s logs folder. While troubleshooting or debugging the servlet call, youcan issue System.out.println statements to output debugging text.

Note

ABC Company Web site design and development 311

Figure 290. The submitOrder() method using DPC to call the AS/400 program

The value of the pgmcallURL variable in our case is jdbc:as400://AS20. AS20 is asystem name.

private boolean submitOrder(String header, String detail) {

String msgId, msgText;// Messages returned from AS/400

// Get system name from the URL string (system name starts after "//" characters)String systemName = pgmcallURL.substring(pgmcallURL.lastIndexOf("/") + 1);

AS400 as400System = new AS400(systemName, pgmcallUserID, pgmcallpwd);try{

as400System.connectService(AS400.COMMAND);ProgramCall ordEntrPgm = new ProgramCall(as400System);QSYSObjectPathName pgmName = new QSYSObjectPathName

("APILIB","ORDENTRCL","PGM");

ProgramParameter[] parmList = new ProgramParameter[2];

// set the first parameter which is the order headerAS400Text text1 = new AS400Text(9);byte[] headerInfo = text1.toBytes(header);parmList[0] = new ProgramParameter(headerInfo);

// set the first parameter which is the order headerAS400Text text2 = new AS400Text(detail.length());byte[] detailInfo = text2.toBytes(detail);parmList[1] = new ProgramParameter(detailInfo);

ordEntrPgm.setProgram(pgmName.getPath(),parmList);

// if you hang here - the AS/400 server job (QZRCSRVS)// may be waiting on an inquiry message and control// will never return. Check the QZRCSRVS joblogif (ordEntrPgm.run() != true){

// If you get here, the program failed to run.// Get the list of messages to determine why// the program didn't run.

AS400Message[] msgs = ordEntrPgm.getMessageList();

// write them to standard outputfor (int m = 0; m < msgs.length; m++) {msgId = msgs[m].getID();msgText = msgs[m].getText();System.out.println(" " + msgId + " - " + msgText);

}System.out.println("** Call to ORDENTRCL failed. See messages above **");return false;

}else

{System.out.println("Order successfully submitted");

}}catch(Exception e){System.out.println("Error submitting order");

// Uncomment the following lines to print uncaught exceptions to stdoutSystem.out.println("--------- UNCAUGHT EXCEPTION ---------");e.printStackTrace(System.out);return false;

}return true;}

312 Web Enabling AS/400 Applications with IBM WebSphere Studio

Then, we start the AS400.COMMAND service for the as400System object.

We declare a ProgramCall object called ordEntrPgm. Then, we set the name ofthe AS/400 system program associated with this object by declaring andinitializing a QSYSObjectPathName object:

ProgramCall ordEntrPgm = new ProgramCall(as400System);QSYSObjectPathName pgmName =new QSYSObjectPathName("APILIB","ORDENTRCL","PGM");

Once this is done, you must set the parameters for this program. To set theparameters, perform these steps:

1. Declare an array of ProgramParameter objects. We declare an array of two,since the program requires two parameters, by entering:

ProgramParameter[] parmList = new ProgramParameter[2];

2. Construct the individual ProgramParameter elements to fill the array. TheProgramParameter constructor must be passed an array of bytes. Beforeinstantiating a ProgramParameter object, we must first generate the appropriatearray of bytes. To create the array of bytes, follow these steps:

a. Declare an appropriate AS/400 system data type object. In this case, weare passing string data, so we declare an AS400Text object.

b. Start the toBytes() method on this AS400Text object and pass the stringthat is being converted to bytes. Here are the two steps that you need:

AS400Text text1 = new AS400Text(9);byte[] headerBytes = text1.toBytes(header);

3. Start the constructor for the ProgramParameter class by entering:

parmList[0] = new ProgramParameter(headerBytes);

Now, the same scenario is followed for each additional parameter that you need.Once the parameters have been instantiated, the ProgramCall object must beinitialized with the actual name of the AS/400 program that is being called. Theparameter list must also be specified by starting the setProgram() method:

ordEntrPgm.setProgram(pgmName.getPath(),parmList);

We are now ready to run the program. The run() method starts the program. Inthis example, it is done inside an "if" construct, so any errors may be processedand the return value for the submitOrder() method determined:

if (ordEntrPgm.run() != true){

If the code gets here (inside the if construct), the program failed to run. We thenget the list of messages to determine why. It all happens inside the if construct.

AS400Message[] msgs = ordEntrPgm.getMessageList();

// write them to standard output

The AS/400 Toolbox for Java implicitly starts this if it needs to be started. It isshown here for clarification:

as400.connectService(AS400.COMMAND);

Note

ABC Company Web site design and development 313

for (int m = 0; m < msgs.length; m++) {msgId = msgs[m].getID();msgText = msgs[m].getText();System.out.println(" " + msgId + " - " + msgText);}System.out.println("** Call to ORDENTRCL failed. See messages above **");return false;}

We left the code to output the messages to stdout uncommented for illustrationpurposes.

One important fact should be noted here. If the program on the AS/400 systemissues a message that waits for a response (an inquiry message), then control isnever returned. The submitOrder() method hangs on the ordEntrPgm.run()

method. If this occurs, you must check the server job that is handling the requeston the host AS/400 system. This job has a name of QZRCSRVS, and its job logshould be viewed. If the program runs successfully, the submitOrder() methodreturns a true boolean value.

If the submitOrder() method returns a true boolean value, prepare_submit_Order()method returns a true boolean value. That is how we know whether the order issubmitted successfully, and we could empty the shopping cart and produceappropriate confirmation page for the user.

7.5.7.2 Calling the AS/400 server program using PCML classesProgram Call Markup Language (PCML) is an alternative way to call AS/400programs. It allows you to define an interface using PCML, which is anotherextension to XML. PCML simplifies calling AS/400 objects since it performsoperations such as the parameter conversions that are required when using aProgramCall method.

XMLeXtensible Markup Language (XML) is a tag-based language based on StandardGeneralized Markup Language (SGML). SGML is a document language intendedfor creating large complex documents. XML provides a format for describing dataand information. It presents an application with data and describes what the datarepresents at the same time. Many industries, noticeably publishing and scientificresearch, are finding that XML provides them a solution to the age-old problem ofdescribing data in an application-neutral format. XML looks similar to HTML in thesense that they are both tag-based languages. However, HTML is moreconcerned about how to lay out information to present it to a user rather than themeaning of the data. XML provides the possibility of attaching style information toan XML data file so that it can be rendered in a desired fashion. Its primaryconcern is data, not display.

The real power of XML is the ability to create tags that have meaning to eachparticular application. It allows the separation of the data from the presentation ofthe data, so the data can remain intelligent. The AS/400 Toolbox for Javaprovides two implementations using XML, which are:

• Panel Definition Markup Language (PDML)• Program Call Markup Language (PCML)

314 Web Enabling AS/400 Applications with IBM WebSphere Studio

PCML is a way to describe program call interfaces. The Java to AS/400implementation for PCML automatically converts data between AS/400 datatypes and Java Object classes (such as Integer, String, Float, and so on). Inaddition, you only need to define the program interface in a single PCML file. Thisencourages reuse and makes maintaining the interface between legacy programsand Java easier.

PCMLPCML enables you to define tags that fully describe AS/400 programs that will becalled by your Java application. PCML was created to simplify calling AS/400programs from Java. It performs the following functions:

• It converts data types between the AS/400 format and the Java format.

• It simplifies Java programs by handling complex relationships in AS/400 data:

– Varying length character strings and structures– Varying size arrays of fields and structures and nested arrays– Strings with runtime CCSID tagging

• PCML is implemented as a package of Java classes:

– com.ibm.as400.data(data400.jar)

Figure 291 shows how PCML works.

Figure 291. PCML architecture

To build AS/400 program calls with PCML, you must start by creating:

• A Java application (can be a application, servlet, or bean)• A PCML source file

Depending on your application design, you must write one or more PCML sourcefiles where you describe the interfaces to the AS/400 programs that will be called

ABC Company Web site design and development 315

by your Java application. When your application constructs aProgramCallDocument object, the IBM XML parser reads and parses the PCMLsource file. After the ProgramCallDocument class is created, the applicationprogram uses the ProgramCallDocument class methods to retrieve the necessaryinformation from the AS/400 system through the AS/400 distributed program call(DPC) server.

To increase runtime performance, the ProgramCallDocument class can beserialized. The ProgramCallDocument class is then constructed using the serializedfile. In this case, the IBM XML parser is not used at runtime.

PCML filePCML consists of the following tags, each of which has its own attribute tags:

• Program tag: Begins and ends code that describes one program.

• Struct tag: Defines a named structure, which can be specified as anargument to a program or as a field within another named structure. A structtag contains a data or a struct tag for each field in the structure.

• Data tag: Defines a field within a program or structure.

Figure 292 shows the PcmlPgmCall PCML file, which is used when we call theORDENTRCL program from sbmorder servlet. The Java application uses PCMLby constructing a ProgramCallDocument object with a reference to the PCMLsource file. The ProgramCallDocument considers the PCML source file to be aJava resource. Consequently, the PCML source file is found using the JavaCLASSPATH.

We import the PcmlPgmCall.pcml file into WebSphere’s OrderPurchase project.Follow these steps:

1. Copy the PcmlPgmCall.pcml file (can be created using any text editor) into the\subsites\OrderPurchase\servlet\OrderPurchase folder using WindowsExplorer or a copy command issued from command prompt.

2. Highlight the OrderPurchase package under the servlet folder inside theStudio Workbench to make sure PcmlPgmCall.pcml will be inserted there.

3. Inside the Studio Workbench, click Insert->File.

4. Click the Use Existing tab to insert the existing PcmlPgmCall.pcml file ratherthan generate one based on a template.

5. Click the Browse button to select the PcmlPgmCall.pcml file. Then, click theOK button.

The PcmlPgmCall.pcml file should now be visible inside the Studio Workbench.Make the file publishable (Figure 292).

316 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 292. PCML source file PcmlPgmCall.pcml

The name of the AS/400 program that we call is named ORDENTRCL. It is foundin the library named APILIB. ORDENTRCL accepts two parameters. To sendinformation to the AS/400 program, we set two “input/output” parameters:

• asHeader• asDetail

Notice that we specify the usage as “input/output” for all the parameters. This isin case we change the AS/400 program to put something back inside theparameters for the servlet to evaluate (confirmation message for example). If weenhance the sbmOrder.java servlet to interpret parameters, we can use the samePCML file.

How does it all work? We create a ProgramCallDocument object by passing it anAS/400 object and the name of the PCML source file. When an applicationconstructs a ProgramCallDocument object, the IBM XML parser reads andparses the PCML source file. We use the setValue() method of theProgramCallDocument object to set the values for the parameters. We use thecallProgram() method to actually call the AS/400 program. When the call to theAS/400 program is complete, we use the getValue() method to retrieve the valuesof the parameters returned. Notice that we did not have to handle any dataconversions.

Examining the submitOrder() method with PCML objectsFigure 293 on page 318 shows the listing of the submitOrder() method inside thesbmorder servlet.

Some declarations are the same as with using DPC. In case a call fails, we needmsgId and msgText to hold the values to output them to standard out.

<pcml version="1.0">

<!-- PCML source for calling "ORDENTRCL" Program -->

<!-- Program PgmCall and its parameter list for retrieving part records --><program name="PcmlPgmCall" path="/QSYS.lib/APILIB.lib/ORDENTRCL.pgm">

<data name="asHeader" type="char" length="9" usage="inputoutput"init=" "/>

<data name="asDetail" type="char" length="2000" usage="inputoutput"init=" "/>

</program>

</pcml>

When a servlet issues output to stdout, the WebSphere Application Serverplaces the output inside the jvm_stdout.log file located inside the applicationserver logs folder. While troubleshooting or debugging the servlet call, you canissue System.out.println statements to output debugging text.

Note

ABC Company Web site design and development 317

Figure 293. submitOrder() method with PCML (Part 1 of 2)

private boolean submitOrder(String header, String detail) {

// Get system name from the URL string (system name starts after "//" characters)String systemName = pgmcallURL.substring(pgmcallURL.lastIndexOf("/") + 1);

AS400 as400System = new AS400(systemName, pgmcallUserID, pgmcallpwd);

ProgramCallDocument pcml;// com.ibm.as400.data.ProgramCallDocumentboolean rc = false; // Return code from ProgramCallDocument.callProgram()String msgId, msgText;// Messages returned from AS/400// Object value; // Return value from ProgramCallDocument.getValue()

System.setErr(System.out);

try {// Uncomment the following to get debugging information// com.ibm.as400.data.PcmlMessageLog.setTraceEnabled(true);

// When running from VisualAge uncomment System.out.println ... to see stdoutSystem.out.println("Beginning PCML Example..");System.out.println(" Constructing ProgramCallDocument for ORDENTRCL API...");

// Construct ProgramCallDocument// First parameter is system to connect to// Second parameter is pcml resource name. In this example,// serialized PCML file "PcmlPgmCall.pcml.ser" or// PCML source file "PcmlPgmCall.pcml" must be found in the classpath.pcml = new ProgramCallDocument(as400System, "OrderPurchase.PcmlPgmCall");// pcml.serialize();// uncomment to serialize

// Set input parameters. Several parameters have default values// specified in the PCML source. Do not need to set them using Java code.System.out.println(" Setting input parameters...");

// Request to call the APISystem.out.println(" Calling ORDENTRCL API requesting information for the sign-on user.");

pcml.setValue("PcmlPgmCall.asHeader", header);pcml.setValue("PcmlPgmCall.asDetail", detail);rc = pcml.callProgram("PcmlPgmCall");

// If return code is false, we received messages from the AS/400if (rc == false) {

// Retrieve list of AS/400 messagesSystem.out.println("error occurred");

AS400Message[] msgs = pcml.getMessageList("PcmlPgmCall");

// write them to standard outputfor (int m = 0; m < msgs.length; m++) {msgId = msgs[m].getID();msgText = msgs[m].getText();System.out.println(" " + msgId + " - " + msgText);

}System.out.println("** Call to ORDENTRCL failed. See messages above **");// System.exit(0);return false;

}}

318 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 294. submitOrder() method with PCML (Part 2 of 2)

We also need to declare and initialize an AS/400 object using the system name,user ID and password. We called it as400System. Recall the global variablesfrom the previous sections. We use them to create the as400System object ofAS400 type.

The following Java code constructs as400System and ProgramCallDocumentobjects:

AS400 as400System = new AS400(systemName, pgmcallUserID, pgmcallpwd);ProgramCallDocument pcml;

Inside the try {} block, we instantiate a PCML object:

pcml = new ProgramCallDocument(as400System, "OrderPurchase.PcmlPgmCall");

The ProgramCallDocument object looks for the PCML source in a file calledPcmlPgmCall.pcml. Notice that the .pcml extension is not specified on theconstructor. We also need to package qualify the name of the PCML resource.The PCML source file PcmlPgmCall.pcml must be found in the class path, and itis since it is inside the servlet directory under the WebSphere Application Serverdirectories.

Next, we set the parameters required by the called application program:

pcml.setValue("PcmlPgmCall.asHeader", header);pcml.setValue("PcmlPgmCall.asDetail", detail);

Now, we call the program by running the following statement:

rc = pcml.callProgram("PcmlPgmCall");

The actual program name is stored inside the PcmlPgmCall.pcml file. We thenevaluate the value of the return code variable rc. In the if construct, we performsome error handling and error messages output to stdout. Depending on the rc

code, the submitOrder() method returns true or false. The last two paragraphs of7.5.7.1, “Calling the AS/400 server program using the DPC class” on page 311,apply to the PCML submitOrder() method as well.

PCML conclusionCalling AS/400 programs from Java applications can require a large amount ofprogramming effort. Ordinarily, you have to write additional lines of code toconstruct AS/400 Toolbox for Java class objects for connecting to and retrievinginformation from an AS/400 program and for performing the appropriate datatranslation.

// Write some of the results to standard outputcatch (PcmlException e) {

System.out.println(e.getLocalizedMessage());e.printStackTrace();System.out.println("*** Call to ORDENTRCL failed. ***");return false;

}return true;

}

ABC Company Web site design and development 319

Using PCML, calls to AS/400 program are handled by PCML class objects. ThePCML class objects are generated from PCML tags, which is the PCML codeddescription of AS/400 programs calls. This minimizes the amount of code youneed to write in order to call AS/400 programs from your application.

PCML provides a powerful way to call existing AS/400 programs. It can run in any1.1.6 JVM that has the AS/400 Toolbox for Java Modification 2 and the PCML andXML parser archives available. You can write one PCML definition to use in allyour Java programs. This allows you to reuse it and makes it easier to maintain. Itcan also serialize the PCML file for improved runtime performance. To serialize aPCML file, use the ProgramCallDocument class with the -serialize option:

Java com.ibm.ProgramCallDocument -serialize pcmlfile

The system uses the serialized file if it exists. Also, the IBM XML parserpackages are not required at runtime.

While PCML was designed to support distributed program calls to AS/400program objects from a Java client platform, you can also use PCML to makecalls to an AS/400 program from within an AS/400 environment.

SummaryWe include both methods inside the sbmorder servlet. One of them will becommented out. Do not forget to compile Order.java and OrderDetail.java prior tocompiling sbmOrder.java. Also, set the *.pcml file to be eligible for publishing.

It may be a good idea to stop and test the order creation process beforedeveloping an order confirmation function, which described in the next section.

7.5.8 Order confirmation: Creating SELECT SQL for the ORDERS tableIn this section, we are going to create the SELECT statement for the ORDERStable using the SQL Wizard to retrieve a newly created order number, date, andtime to be displayed on the confirmation page. Follow these steps:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder OrderPurchase.

3. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

4. Proceed through the tabbed windows of the wizard, and specify theinformation in Table 37.

Table 37. Information to be entered in the SQL Wizard

Tabbed window Action explanation

Welcome Enter lastOrder as the name of the query. The wizard adds an.sql file in your project.

Click Next.

320 Web Enabling AS/400 Applications with IBM WebSphere Studio

Logon Enter the information the wizard needs to connect to thedatabase, for example:

• Database URL: jdbc:as400://system name

• Userid: user ID

• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be in uppercase.

Click the Connect button and the wizard connects you to thespecified database.

Click the Next button to go to the next tab.

Tables If the Schema(s) to View window does not appear, click on theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is APILIB In this case. Click on thelibrary to select it, and click the Add button.

Click OK to return to the Tables window.

Click the Select radio button in the Statement type.

Select APILIB.ORDERS from the list of tables shown.

Click Next.

Join No action is required.

Click Next.

Columns Select only the OID, OENTDT, and OENTTM columns to beincluded in the output result.

Click the Add button.

Click Next.

Condition 1 Specify OCID to be equal to the cust parameter.

Note: The cust parameter will be passed to the servlet.

Click Next.

Sort No action is required.

Click Next.

Tabbed window Action explanation

ABC Company Web site design and development 321

5. Check the generated file lastOrder.sql into the Studio Workbench. Select theOrderPurchase folder. Then, right-click, and select the Check In option.

7.5.9 Creating servlet and DB access bean for the ORDERS select queryIn this section, we create the servlet and the DB access bean to get the result ofORDERS select query, which should return the last order record created for theparticular customer. However, the SQL we created in the previous section doesnot return only the last order record. In fact, it returns all the orders. We have theability to modify the SQL statement that the bean will use to get the data from thedatabase on AS/400 server. We discuss this in detail later in this section.

Perform the following tasks that run the Database Wizard to create the HTMLform, the servlet, the bean, and resulting JSPs to select all records from the ITEMdatabase table:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder OrderPurchase.

3. Start the SQL Wizard by selecting Tools ->Wizards ->Database Wizard.

4. Select the appropriate SQL Statement, which you created in 7.5.8, “Orderconfirmation: Creating SELECT SQL for the ORDERS table” on page 320. Itshould be drive:\subsites\OrderPurchase\lastOrder.sql.

5. Click Next.

6. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 38.

SQL No action is required.

This tab shows the complete SQL statement. You can copy thestatement to the clipboard to use it in another application. Also youcan test the SQL statement by pressing the Run SQL button.

Click Next.

Finish Click Finish.

The completed SQL file should appear in the project aslastOrder.sql.

Tabbed window Action explanation

322 Web Enabling AS/400 Applications with IBM WebSphere Studio

Table 38. Information to be entered in the Database Wizard

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that willbe generated. You need an input page to collect the data forinsertion, an output page to show the result from the query, andan error page if something unforeseen happens. You also needto:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.d. Select the no data is returned check box.

Click Next.

Input Page The input page does not require any parameters.

Click Next.

Results Page The results page already has the output parameters you wantedfrom the SQL file. These should be OID, OENTDT, andOENTTM.

Select the parameters by clicking on the row, and click theChange button to change the caption to a more meaningfulname. You can also change the field sizes. Repeat this for thefollowing parameters:

• For OID, type Order ID• For OENTDT, type Order Date• For OENTTM, type Order Time

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click Next.

No Data Page Click Next.

Methods Make sure that the method named execute() is selected.

Click Next.

Session This bean is only to be used one time. We do not need to bind itto the session so make sure No is selected.

Name the bean lastOrderDBBean.

Click Next.

ABC Company Web site design and development 323

7. Check all of the generated files (all files having lastOrder prefix) into theStudio Workbench. Select the OrderPurchase folder. Then, right-click, andselect the Check In option.

8. Publish the project to the AS/400 server. Follow the same steps outlined in4.3.1, “Publishing to the AS/400 system” on page 125.

Recall that the lastOrderDBBean executes the SQL statement to get all the orderrecords for the particular customer. Let us change the SQL statement inside thebean to retrieve only the last order. Here is the original commented out SQLstatement followed by the new one:

/*** Instance variable for SQL statement property*/

// protected java.lang.String SQLString = "SELECT APILIB.ORDERS.OID,APILIB.ORDERS.OENTDT, APILIB.ORDERS.OENTTM FROM APILIB.ORDERS WHERE ( (APILIB.ORDERS.OCID = ? ) ) ORDER BY APILIB.ORDERS.OID DESC";

protected java.lang.String SQLString = "SELECT APILIB.ORDERS.OID,APILIB.ORDERS.OENTDT, APILIB.ORDERS.OENTTM FROM APILIB.ORDERS WHERE ( (APILIB.ORDERS.OCID = ? ) AND (APILIB.ORDERS.OID IN (SELECTMAX(APILIB.ORDERS.OID) FROM APILIB.ORDERS WHERE (APILIB.ORDERS.OCID = ? )) ))";

In plain text, first, we find the last order ID created for the particular customer.Then, we select the necessary columns from the ORDERS table based on thecustomer ID and the last order ID returned in the subquery. As a result of ourchanges, the SQL statement needs two parameters instead of one (notice the “?”(question marks) inside the SQL statement).

Find the following lines inside the initialize() method:

// Create placeholders for the parametersmetaData.addParameter("cust", String.class, 1);

Add the following line right after the previous lines:

metaData.addParameter("cust2", String.class, 1);

Finish Give a meaningful name to the generated source files. Click theRename button, and type lastOrder into the Prefix dialog.Click OK. Note that all of the files now have the prefix oflastOrder.

Click Finish to generate the code.

The Database Wizard generates and compiles the files. The filesare placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If itcontains a comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

324 Web Enabling AS/400 Applications with IBM WebSphere Studio

Find the following lines inside the execute() method:

// Initialize the parameters for the querysqlStatement.setParameter("cust", getCust());

Add the following line right after the previous lines:

sqlStatement.setParameter("cust2", getCust());

Save, check in, and compile the bean to test the last order record retrieval.

Unit testing the last order record retrievalTo perform the unit test, make sure ORDERS table is not empty. Refer to 7.5.2,“Creating SELECT SQL for the SHPCART table” on page 293, through 7.5.6,“Developing Java code to package and submit the order to the AS/400 server” onpage 301, for information on placing orders.

Perform the following steps to test retrieving the last order information:

1. Select the lastOrderInput.html file. Then, right-click, and select Preview filewith Netscape or Internet Explorer. When the Web browser appears, the pageappears as shown in Figure 295.

Figure 295. Last Order record retrieval test: Input form

2. Complete the form, and click the Submit button. The result page shouldappear as shown in Figure 296 on page 326.

ABC Company Web site design and development 325

Figure 296. Last Order record retrieval test: Resulting JSP

If the call to AS/400 server application program was successful, meaning theorder records are created, and we can produce a confirmation page, then wehave no use for the shopping cart records. The next two sections deal withemptying the shopping cart.

7.5.10 Creating the DELETE SQL for the SHPCART tableIn this section, we create the DELETE SQL statement to delete records from theSHPCART database table using the SQL Wizard. Follow these steps:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder OrderPurchase.

3. Start the SQL Wizard by selecting Tools ->Wizards ->SQL Wizard.

4. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 39.

Table 39. Information to be entered in the SQL Wizard

Tabbed window Action explanation

Welcome Enter deleteCartas the name of the query. The wizard adds an.sql file in your project.

Click Next.

326 Web Enabling AS/400 Applications with IBM WebSphere Studio

5. Check the generated file deleteCart.sql into the Studio Workbench. Select theOrderPurchase folder. Then, right-click, and select the Check In option.

Logon Enter the information the wizard needs to connect to thedatabase, for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be in uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is APILIB in this case. Click onthe library to select it, and click the Add button.

Click OK to return to the Tables window.

Click the Delete radio button in the Statement type.

Select APILIB.SHPCART from the list of tables shown.

Click Next.

Condition Specify SCID to be equal to cust parameter.

Click Next.

SQL No action is required.

This tab shows the complete SQL statement. You can copy thestatement to the clipboard to use it in another application. Youcan also test the SQL statement by clickinging the Run SQLbutton.

Click Next.

Finish Click Finish.

The completed SQL file should appear in the project asdeleteCart.sql.

Tabbed window Action explanation

ABC Company Web site design and development 327

7.5.11 Creating the servlet and DB access bean for the SHPCART deleteIn this section, we create the servlet and the DB access bean to delete recordsfrom the SHPCART table.

Perform the following tasks to create the servlet, the bean, and the resultingJSPs:

1. Start WebSphere Studio if not already started.

2. Select the project folder OrderPurchase.

3. Start the SQL Wizard by selecting Tools->Wizards->Database Wizard.

4. Select the appropriate SQL statement that you created in Section 7.5.8,“Order confirmation: Creating SELECT SQL for the ORDERS table” on page320. It should be drive:\subsites\OrderPurchase\deleteCart.sql.

5. Click Next.

6. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 40.

Table 40. Information to be entered in the Database Wizard

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files will begenerated. You need an input page to collect the data forinsertion, an output page to show the result from the query, andan error page if something unforeseen happens. You also needto:

a. Select the input page check box.b. Select the result page check box.c. Select the error page check box.d. Select the no data is returned check box.

Click Next.

Input Page The input page does not require any parameters.

Click Next.

Result Page The result page does not require any parameters.

Click Next.

Standard Error Page Click Next.

No Data Page Click Next.

Methods Make sure that the method named execute() is selected.

Click Next.

Session This bean is only to be used one time. We do not need to bind itto the session so make sure No is selected.

Name the bean deleteOrderDBBean.

Click Next.

328 Web Enabling AS/400 Applications with IBM WebSphere Studio

7. Check all of the generated files (all files having deleteOrder prefix) into theStudio Workbench. Select the OrderPurchase folder. Then, right-click, andselect the Check In option.

8. Publish the project to the AS/400 server. Follow the same steps outlined in4.3.1, “Publishing to the AS/400 system” on page 125.

You may test the SHPCART records deletion, or you can delay the test until wetie it all together.

In the next section, we finally put together the shopping cart retrieval, orderplacement, confirmation, and shopping cart deletion.

7.5.11.1 Order packaging and submission: Tying it all togetherSo far, for the order packaging and submission functionality, we developedstandalone functions. The time has come to tie these separate functions togetherto have functional flow. In this section we modify the sbmOrder servlet, andsbmOrderResult and sbmOrderError JSPs. In 7.5.6, “Developing Java code topackage and submit the order to the AS/400 server” on page 301, we inserted thecode into the sbmorder servlet to:

• Retrieve the order data from the sbmOrderDBBean bean• Package the order data into two parameters• Call the AS/400 server application program

Recall that the prepare_submit_Order() method, called inside sbmorder servlet,calls the submitOrder() method. Both methods return a boolean value. If theAS/400 server program (ORDENTRCL) is called successfully, the submitOrder()

method returns true. Consequently, the prepare_submit_Order() method returnstrue as well. The return value of the prepare_submit_Order() method alwaysequals the return value of the submitOrder() method.

If the call to AS/400 server application program is successful, then the order iscreated. This allows instantiation of the bean to retrieve the last order recordcreated to be displayed for the user in the form of confirmation.

Finish Give a meaningful name to the generated source files. Click theRename button, and type lastOrder into the Prefix dialog. ClickOK. Note that all of the files now have the prefix of lastOrder.

Click Finish to generate the code.

The Database Wizard generates and compiles the files. The filesare placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

ABC Company Web site design and development 329

Tying together the order submission and order confirmationIn 7.5.8, “Order confirmation: Creating SELECT SQL for the ORDERS table” onpage 320, and 7.5.9, “Creating servlet and DB access bean for the ORDERSselect query” on page 322, we created the servlet, bean, and JSPs to retrieveand display the last order record created for a particular customer. Let us insertlastOrderDBBean instantiation code inside the sbmOrder servlet and merge thelastOrderResult JSP into the sbmOrderResult JSP.

Before inserting the lastOrderDBBean instantiation code into the sbmOrder servlet,insert the following import statement into sbmOrder.java:

import OrderPurchase.lastorderDBBean;

Open sbmOrder.java for editing and lastOrder.java for read only. We copy andpaste the lastOrderDBBean instantiation code into the sbmOrder.java. Copy thelines of code shown in Figure 297 from lastOrder.java.

Figure 297. lastorderDBBean instantiation code to be inserted into the sbmorder.java servlet

Paste the code in Figure 297 inside sbmorder.java after the following lines ofcode:

// Prepare and submit an order to the AS/400 to processif (prepare_submit_Order(theOrder) == true) {

lastOrderDBBean will be instantiated only if prepare_submit_Order() returns true.

Finally, let us merge lastOrderResult.jsp into sbmOrderResult.jsp to produce asingle confirmation page with shopping cart and order number information.

// instantiate the beans and store them so they can be accessed by the called pageOrderPurchase.lastorderDBBean lastorderDBBean = null;lastorderDBBean = (OrderPurchase.lastorderDBBean)

java.beans.Beans.instantiate(getClass().getClassLoader(), "OrderPurchase.lastorderDBBean");

setRequestAttribute("lastorderDBBean", lastorderDBBean, request);

// Initialize the bean userID property from the parameterslastorderDBBean.setUserID(getParameter(request, "userID", true, true, false, null));

// Initialize the bean password property from the parameterslastorderDBBean.setPassword(getParameter(request, "password", true, true, false, null));

// Initialize the bean URL property from the parameterslastorderDBBean.setURL(getParameter(request, "URL", true, true, false, null));

// Initialize the bean driver property from the parameterslastorderDBBean.setDriver(getParameter(request, "driver", true, true, false, null));

// Initialize the bean cust property from the parameters

lastorderDBBean.setCust(getParameter(request, "cust", true, true, true, null));

// Call the execute action on the bean.lastorderDBBean.execute();

330 Web Enabling AS/400 Applications with IBM WebSphere Studio

Open lastOrderResult.jsp in Page Designer to select all, and copy and paste intosbmOrderResult.jsp. Now, open sbmOrderResult.jsp, position the cursor after thelast “J” and select paste. The result is shown in Figure 298.

Figure 298. Merging lastorderResult.jsp into sbmorderResult.jsp (Part 1)

Enhance the confirmation page look to present it in a more readable form.Remove the customer ID and item ID columns from shopping cart table, andchange the table headings. See the Figure 299.

Figure 299. Merging lastorderResult.jsp into sbmorderResult.jsp (Part 2)

Displaying order total on the confirmation pageAnybody who places an order wants to see an order total. Let us describe themethod we used to put the order total on the confirmation page. AS/400 databasetables ORDERS and ORDLIN do not contain a field holding an order total value.

ABC Company Web site design and development 331

Consequently, we need to calculate it ourselves. In the process, we modifysbmOrderDBBean, the sbmOrder servlet, and sbmOrderResults.jsp.

First, we modify the sbmOrderDBBean bean to have the orderTotal propertyholding order total value. We also include setter and getter methods.

Insert the following lines to be together with other bean’s instance variablesdeclarations.

/*** Instance variable for orderTotal property*/protected java.math.BigDecimal orderTotal;

Next, insert the following two methods, getter and setter respectively:

/* ***************************************************************************** Get method for the orderTotal property* @return the value of the orderTotal property

*/public java.math.BigDecimal getOrderTotal()

{

return orderTotal;

}

/* ***************************************************************************** Set method for the orderTotal property* @param value the new value for the orderTotal property

*/public void setOrderTotal(java.math.BigDecimal value)

{

this.orderTotal = value;

}

Save, close, check in, compile, and publish the bean.

Let us now modify the sbmOrder servlet. Insert the following line of code rightbefore the for loop construct, where we retrieve the order data from the bean,inside the performTaks() method:

BigDecimal orderTotal = new BigDecimal(0);

This line declares the variable we will increment in the process of retrieving thedata from the bean inside the loop.

Next, insert the following line of code inside the for loop construct, where weretrieve the order data from the bean, inside the performTaks() method:

orderTotal = orderTotal.add((sbmorderDBBean.getAPILIB_SHPCART_SPRC(i).multiply(sbmorderDBBean.getAPILIB_SHPCART_SQTY(i)) ) );

This line multiplies quantity by price and increments the orderTotal variable.

Next, insert the following line of code also inside the sbmOrder servlet:

sbmorderDBBean.setOrderTotal(orderTotal);

332 Web Enabling AS/400 Applications with IBM WebSphere Studio

inside the if construct, where we test for successful order submission before thefollowing line:

callPage(getPageNameFromRequest(request), request, response);

The line we inserted sets the bean property with the value we calculated, so itcan be later retrieved by the JSP via the getter method. Save, close, check in,compile, and publish the servlet.

Lastly, let us modify sbmOrderResults.jsp. Open sbmOrderResults.jsp in PageDesigner. Click Insert->Dynamic Elements->Property Display... to select thesbmOrderDBBean’s property to be displayed on the page. Refer to the methoddescribed in 7.2.2.11, “Creating a final resulting JSP” on page 196. In the result,you should see a “J” symbol representing the orderTotal property (Figure 300).We highlighted the order total line on the figure, so you can see where we placedthe “J”.

Figure 300. Adding the order total to sbmorderResults.jsp

Tying together order submission and shop cart deletionIn 7.5.10, “Creating the DELETE SQL for the SHPCART table” on page 326, and7.5.11, “Creating the servlet and DB access bean for the SHPCART delete” onpage 328, we created the servlet, bean, and JSPs to delete the shopping cartcontents for a particular customer. Let us insert deleteCartDBBean instantiationcode inside the sbmOrder servlet.

Before inserting deleteCartDBBean instantiation code into sbmorder servlet,insert the following import statement into sbmOrder.java:

import OrderPurchase.dltCartDBBean;

ABC Company Web site design and development 333

Open sbmOrder.java for editing and deleteCart.java for read only. We copy andpaste deleteCartDBBean instantiation code into sbmOrder.java. Copy the lines ofcode shown in Figure 301 from deleteCart.java.

Figure 301. The dltCartDBBean instantiation code to be inserted into the sbmorder.java servlet

Paste the code shown in Figure 301 inside sbmOrder.java after the following linesof code:

// Prepare and submit an order to the AS/400 to processif (prepare_submit_Order(theOrder) == true) {

Only if prepare_submit_Order() returns true, then deleteCartDBBean isinstantiated (deletes SHPCART table records), and proceeds to lastorderDBBeaninstantiation.

7.5.12 Error handling on order submission to the AS/400 serverWe inserted instantiations of the dltCartDBBean and lastorderDBBean beansinside the if construct (Figure 302).

Figure 302. ‘if’ construct to evaluate successful order submission

// instantiate the beans and store them so they can be accessed by the called pageOrderPurchase.dltCartDBBean dltCartDBBean = null;

dltCartDBBean = (OrderPurchase.dltCartDBBean)java.beans.Beans.instantiate(getClass().getClassLoader(), "OrderPurchase.dltCartDBBean");

setRequestAttribute("dltCartDBBean", dltCartDBBean, request);

// Initialize the bean userID property from the parametersdltCartDBBean.setUserID(getParameter(request, "userID", true, true, false, null));

// Initialize the bean password property from the parametersdltCartDBBean.setPassword(getParameter(request, "password", true, true, false, null));

// Initialize the bean URL property from the parametersdltCartDBBean.setURL(getParameter(request, "URL", true, true, false, null));

// Initialize the bean driver property from the parametersdltCartDBBean.setDriver(getParameter(request, "driver", true, true, false, null));

// Initialize the bean cust property from the parameters

dltCartDBBean.setCust(getParameter(request, "cust", true, true, true, null));

// Call the execute action on the bean.dltCartDBBean.execute();

// Prepare and submit an order to the AS/400 to processif (prepare_submit_Order(theOrder) == true) {

}

334 Web Enabling AS/400 Applications with IBM WebSphere Studio

We are not going to delete the shopping cart contents nor retrieve the last ordercreated unless order submission is successful. However, the following line ofcode (Figure 303), which displays the confirmation page, is executed regardless.

Figure 303. Displaying the confirmation page in the sbmorder servlet

We need to move this line to be the last line inside the if construct, see Figure302, to ensure the confirmation JSP will be returned only upon successfulexecution of the order submission.

What about if the order submission fails? We specify the else statement clauseand to execute the line of code to return error notification page, in this case, “Nodata returned” JSP. Refer to Figure 304.

Figure 304. ‘else’ clause to return an error notification page

If, for some reason, a call to AS/400 application program fails, the user sees thepage shown in Figure 305.

Figure 305. Order Purchase error page

It is important to understand the distinction between system error handling andapplication error handling. The type of error handling we have in our Web siteapplication protects us from the system failures, for example:

• The AS/400 system is not accessible.• A program object is not accessible.• A program object cannot be called for some reason.

// Call the output page. If the output page is not passed// as part of the URL, the default page is called.callPage(getPageNameFromRequest(request), request, response);

elsecallPageNamed(getParameter(request,

"com.ibm.webtools.runtime.NoDataException", true, true, false,"com.ibm.webtools.runtime.NoDataException"), request, response);

ABC Company Web site design and development 335

However, if the call to the program (ORDENTRCL in our case) is successful, thenwe are not monitoring for (catching) application errors, such as:

• A certain file is missing.• Certain data elements are missing.• Business rules are broken, so order records are not written.

To support application error handling, RPG or other types of application programsshould return the parameter to the servlet, which called it, so servlet code canevaluate the return parameter to decide if the order submission is successful.

7.5.13 Creating a self-contained order purchase subsiteThe objective of this section is to produce a self-contained subsite with one entrypoint. Let us explain.

Let us refer to 7.5.2, “Creating SELECT SQL for the SHPCART table” on page293, through 7.5.4, “Modifying the resulting page of the shopping cart selection”on page 297. We developed a shopping cart retrieval function, which producesintermediate result page, where the users have a chance to review the shoppingcart contents and provide credit card information before they actually commit toan order purchase. To start the shopping cart retrieval function(cartselectInput.html), we enter a cust ID parameter to know which shopping cartrecords to select. This is an entry point into the order purchase subsite. We needthis entry point to test the order purchase subsite functionality from the beginningto the end.

We also recall 7.5.5, “Creating the servlet, DB access bean, and JSPs to submitthe order” on page 299, through 7.5.11, “Creating the servlet and DB accessbean for the SHPCART delete” on page 328. We developed order packaging andsubmission functionality to invoke the AS/400 server program to commit the orderdata to the database. The order packaging and submission function representsthe subset of our subsite. It also has an entry point in sbmorderInput.html, wherewe enter cust ID.

In this section, we remove the order packaging and submission entry point, so wehave continuous flow from shopping cart retrieval to the order packaging andsubmission functions. This means, we have to pass the cust ID parameter withouthaving to enter it through sbmorderInput.html. Let us explain one of the ways itcan be done.

So far, the order purchase subsite contains:

• Shopping cart retrieval:

– cartselectInput.html to get the cust Id parameter

– cartselect servlet to instantiate the cartselectDBBean and produce JSPs

– resulting JSPs: cartselectResults.jsp, csrtselectNoData.jsp, andcartselectError.jsp

• Packaging and submitting order data to the AS/400 server for furtherprocessing:

– sbmorderInput.html to get the cust Id parameter

– sbmorder servlet to instantiate the sbmorderDBBean, lastorderDBBean,dltCartDBBean beans and produce JSPs

336 Web Enabling AS/400 Applications with IBM WebSphere Studio

– resulting JSPs: sbmorderResults.jsp, sbmorderNoData.jsp, andsbmorderError.jsp

We need to modify cartselectResult.jsp, so that when the user clicks thePurchase button, the sbmorder servlet is called and cust Id is passed as aparameter.

7.5.13.1 Retrieving form properties from selectcartInput.htmlBefore we start modifying selectcartResults.jsp to invoke order packaging andthe submission function, we need to find out which servlet to call and whatparameters to pass to that servlet. Since we used the wizards to generate most ofthe pages, we can easily find the information we need. Follow these steps:

1. Double-click sbmorderInput.html. This checks the file out and opens it in thePage Designer (Figure 306).

Figure 306. sbmorderInput.html in Page Designer

This page contains information about which servlet to call to invoke orderpackaging and the submission function and which parameters to pass to thatservlet.

2. Double-click inside the input area of the Cust field. You should see the dialogbox (Figure 307).

Figure 307. sbmorderInput.html name of the customer ID input field

ABC Company Web site design and development 337

3. Make note of the name of this text field. This text field is called cust. You willneed this information later. Click Cancel.

Next, we find out which servlet sbmorderInput.html calls.

4. Double-click the Submit button inside sbmorderInput.html. You see the pushbutton attributes dialog box.

5. Click in the drop-down list box next to the Tag caption to select the Formattributes dialog box and see the properties of the form. Refer to Figure 308.

Figure 308. Form properties in sbmorderInput.html

We need to observe the Action parameter in Figure 308. Make a note of wherethis action points to, which is /servlet/OrderPurchase.sbmorder. This is thelocation and the name of the servlet, which is called and accepts the parametersas a result of the form submission.

7.5.13.2 Modifying selectcartResults.jspKnowing the servlet name, location, name of the parameter, which is passed tothe servlet, we can modify the selectcartResults.jsp page. Follow these steps:

1. Double-click on selectcartResults.jsp. This checks the file out and opens it inthe Page Designer (Figure 309).

338 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 309. Modifying cartselectResults.jsp to call sbmorder servlet (Part 1)

2. Double-click on the Purchase button. You see the push button attributesdialog box.

3. Click in the drop-down list box next to the Tag caption to select the Formattributes dialog box and see the properties of the form. Refer to Figure 310.

Figure 310. Form properties in cartselectResults.jsp

4. Type in /servlet/OrderPurchase.sbmorder for the Action. Recall that weacquired this information from sbmorderInput.html.

5. Set the method radio button to Post, and click OK. So far, the resulting formproperties should be as shown in Figure 311 on page 340.

ABC Company Web site design and development 339

Figure 311. Modifying the cartselectResults.jsp form properties

We specified which servlet to call the location of the called servlet. Next, wespecify the parameters to pass to the sbmorder servlet. In this case, we have onlyone parameter, which is cust ID, named cust.

One way of passing parameters is using hidden fields on the form. These fieldsallow us to pass parameters from the form to a servlet without the having the usertype anything. Follow these steps:

1. Open the cartselectResults.jsp form Attributes dialog box.

2. Click the Hidden Fields tab inside the dialog box (Figure 312).

Figure 312. Adding hidden fields to the cartselectResults.jsp

340 Web Enabling AS/400 Applications with IBM WebSphere Studio

3. Add one hidden field. The hidden field will represent the customer ID. Click inthe Name field, and type cust. This has to be typed exactly the same way asyou noted it on the cartselectInput.html page. By setting this parameter, wecan have our form call the sbmorder servlet.

4. Recall that cartselectResults.jsp contains cartselectDBBean properties, so thevalue for the cust parameter will come from cartselectDBBean. Under theValue field, select the check box called Specify by property. Click on Browseto select from bean’s properties (Figure 313).

Figure 313. Selecting a bean property to supply the parameter value

5. Select the cust bean property to supply the value for the cust parameter. ClickOK.

6. In the Attribute dialog, back on the Hidden Fields tab, click the Add button toadd this parameter (Figure 314 on page 342).

The hidden fields can still be viewed by the user if they look at the source ofthe HTML page in the browser. The hidden fields should never contain auser’s password or confidential information. In our example, we are not tooworried if they find out their customer ID, because they can not do muchwith it unless they log in successfully.

Note

ABC Company Web site design and development 341

Figure 314. Adding a parameter as a hidden field to be passed to the servlet

7. Click OK. Save your page, and quit Page Designer.

8. Check in all your files in the WebSphere Studio.

9. Publish only the modified files.

7.5.14 Order purchase subsite: Final testingIn this section, we test all the steps within the order purchase subsite, including:

• The shopping cart contents display to give the users a chance to review theirshopping cart and supply credit card information

• Shopping cart retrieval to package the order in the subsequent steps

• Packaging and submitting order data to the AS/400 server for furtherprocessing

• Producing the confirmation page

• Deleting shopping cart entries if order submission is successful

In WebSphere Studio Project Workbench, check in the entire project, and thenpublish the entire project. Stop and restart the WebSphere Application Serverand the HTTP server.

Verify that SHPCART table contains records and note the customer ID. Verify thatthis customer ID exists in the CSTMR table and the redit status fields contains“GC” (if it does not, the order will not be created).

Preview cartselectInput.html, enter the customer ID, click the Submit button.Upon successful execution, the page shown in Figure 315 is displayed.

342 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 315. Order Purchase: Successful execution

Verify the presence of new order records written into the ORDERS and ORDLINtables. Also, verify that the SHPCART table does not contain records for thecustomer ID we processed.

7.6 Changes to the Host Order Entry application

This section contains details about the transition of the RPG code on the host.The changes are made so the application can run in one of two modes: as anative application with 5250 screen interaction or in conjunction with the newlycreated Web site, where the application program is called from the servlet. Forthe most part, the changes are examined in the same sequence as the clientapplication flow.

7.6.1 Processing the submitted orderAs previously discussed, the AS/400 system program that handles a request tosubmit an order is ORDENTR. We had to create the CL program ORDENTRCL tocall ORDENTR with the proper library list. Another benefit of calling theORDENTR program from a CL program is that when an application problemoccurs and the error message issued, there are more options available as far aserror handling, including the option to restart ORDENTR.

When the Order Entry application is run from an AS/400 system 5250 session (noJava client), ORDENTR is the entry point of the application. The ORDENTRprogram must be changed to separate the presentation and the business logic.

ABC Company Web site design and development 343

ORDENTR program has to recognize the fact that it was invoked from the servletand only has to create order records based on passed parameters.

First, the number of parameters are ascertained through the program status datastructure:

D PgmStsDS SDSD NbrParms *PARMS

If the number of parameters is greater than zero, it is assumed that the programhas been started as a distributed program.

Since the Java client passes in two parameters, two data structures are declaredthat map to the parameters. As discussed earlier, the client passes two strings.The first string is nine characters that represent the customer ID (4 characters)and the number of detail entries (five characters).

A data structure named CustDS is declared for this first parameter:

D CustDS DSD CustNbr LIKE(CID)D OrdLinCnt 5 0

The second parameter is a string that represents a contiguous grouping of detailentries. Each entry has a length of 40, and there are a maximum of 50 entries. Adata structure named OrderMODS is declared for this parameter:

D OrderMODS DS OCCURS(50)D PartNbrX LIKE(IID)D PartDscX LIKE(INAME)D PartPriceX 5 2D PartQtyX 5 0

An entry parameter list is added to the initialization subroutine. This ensures thatthe data structures are loaded with the parameter values passed in:

C *ENTRY PLISTC PARM CustDSC PARM OrderMODS

As in other RPG programs, the USROPN keyword is added to the filespecification, since the file is not opened when started as a distributed program.Here is the portion of the file specification with the USROPN keyword added:

...WORKSTN SFILE(ORDSFL:SflRrn) USROPN

The mainline logic of the program is changed to check the number of parameters.If there are parameters, a new subroutine, called CmtOrder2, starts and alldisplay file processing is bypassed:

C IF NbrParms > *ZEROC EXSR CmtOrder2C EXSR EndPgmC ENDIF

The CmtOrder2 subroutine is similar to the original CmtOrder subroutine.However, it retrieves the order information from the CustDS and OrderMODSdata structures, rather than from the display file and subfile records:

CSR CmtOrder2 BEGSR* ----------

344 Web Enabling AS/400 Applications with IBM WebSphere Studio

* Get the next order numberC EXSR GetOrdNbr** Get the order date and timeC TIME DateTimeC Z-ADD *ZERO OrdTot** Get the customer informationC MOVE CustNbr CustomerIdC CustKey CHAIN CSRCD** For each order line in the passed structure ...C 1 DO OrdLinCnt OrdCntC OrdCnt OCCUR OrderMODS* Set up the fields so the existing DB routines workC MOVE PartNbrX PARTNBR_OC MOVE PartDscX PARTDSC_OC MOVE PartQtyX PARTQTY_OC MOVE PartPriceX ITEMPRICE* Add an order detail record ...C EXSR AddOrdLin* Update stock record ...C StockKey CHAIN STRCDC EXSR UpdStock* Accumulate order total ...C EVAL OrdTot = OrdTot + OLAMNTC ENDDO** Add an order header record ...C EXSR AddOrdHdr** Update customer record ...C EXSR UpdCust** Commit the database changes ...C IF CmtActive = $TrueC COMMITC ENDIF** Request batch print server to print orderC EXSR WrtDtaQ*CSR ENDSR

The subroutine is built, so all other existing subroutines can be used as in theprior version. Once again, the only significant change is that the information forthe order is retrieved from the parameters that are passed in.

7.6.2 SummaryThe common thread pervasive across all the changes in the host RPG code dealswith display file processing. When ORDENTR starts as a distributed program, alldisplay file processing is bypassed. The information normally received from thedisplay files and subfiles is now made available through parameters.

Different approaches can be taken. The scenario shown here is not the only validone. For example, the detail order entries can be passed to the AS/400 system asdata queue entries. However, this approach entails more changes in the hostapplication. The amount of change needed at the host end is largely affected bydesign decisions made for the client side. Keep in mind, to follow a three-tiermodel, you should have as much business logic on the server as possible and avery thin client running mostly presentation logic.

ABC Company Web site design and development 345

7.7 Creating the order status subsite

To build the order status subsite, we must first create a new project.

7.7.1 Creating the order status projectTo build the order status subsite, we need to create a new project. Complete thefollowing steps to create the new Order Status project folder:

1. Start WebSphere Studio if it is not already started.2. Create a new project by selecting File->New Project.3. Type OrderStatus for the project name.4. Type drive:\subsites\OrderStatus for the project folder.5. Select <none> for project template.

A new project is created called OrderSatus.

7.7.2 Building the SQL queries for the order status subsiteAfter a user purchases their products, we want them to be able to see what theyhave ordered. This section takes you through the process of viewing the orderstatus information. You should already be familiar with the SQL Wizard and theDatabase Wizard which are discussed in 3.2, “Studio Wizards” on page 28.

7.7.2.1 Using the SQL Wizard to check customers ordersPerform the following tasks that run the SQL Wizard to create an SQL statementthat selects order status:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder OrderStatus.

3. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

4. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 41.

Table 41. Building a select all query for the order status

Tabbed window Action explanation

Welcome Enter orderStatus as the name of the query. The wizard addsan .sql file in your project.

Click Next.

346 Web Enabling AS/400 Applications with IBM WebSphere Studio

Logon Enter the information the wizard need to connect to the database,for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be in uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is APILIB in this case. Click on thelibrary to select it, and click the Add button.

Click OK to return to the Tables window.

Click the Select radio button in the Statement type.

Select APILIB.ORDERS from the list of tables shown.

Click Next.

Join No action is required.

Click Next.

Columns You need to provide the user with sufficient information so theycan identify their order. Select the OCARID, OENTDT, OENTTM,OID, and OLINES elements.

Click on the Add button to add them to the columns to include inlist box.

Click Next.

Condition 1 Select OCID in the Columns list box. Select the operator to be isexactly equal to. Click in the top values field, and click theParameter button.

In the Create a new parameter dialog box, enter the variablename custID, and click OK.

Click Next.

Tabbed window Action explanation

ABC Company Web site design and development 347

5. Check in the generated file orderStatus.sql to the Studio Workbench. Selectthe OrderStatus folder. Then, right-click, and select the Check In option.

7.7.2.2 Using the SQL Wizard to view order line detailsPerform the following tasks that run the SQL Wizard to create an SQL statementthat selects order line details:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder OrderStatus.

3. Start the SQL Wizard by selecting Tools->Wizards->SQL Wizard.

4. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 42.

Table 42. Building a select items in price range query with the catalog

Sort You want to display all the orders based on the order date.

Click on APILIB.ORDERS.OENTDT. Click the Add button to addit to our columns to sort in the list box. Make sure the sort order isset to Ascending.

Click Next.

SQL You should now see your SQL statement. To test that it workscorrectly, click on the Run SQL... button.

You are now prompted for one parameter in the SpecifyParameter Value(s) window. For the first parameter, type 001 forthe custID. Click the OK button. You should see all orders for thatcustomer ID.

Click on the Next button, or click the Finish button.

Finish Click the Finish button.

The completed SQL file should appear in the project asordrerStatus.sql.

Tabbed window Action explanation

Welcome Enter orderLine as the name of the query. The wizard adds an.sql file in your project.

Click Next.

Tabbed window Action explanation

348 Web Enabling AS/400 Applications with IBM WebSphere Studio

Logon Enter the information the wizard need to connect to the database,for example:

• Database URL: jdbc:as400://system name• Userid: user ID• Password: password• Driver: AS/400 ToolBox for Java

Note: For the database URL parameter, you can supply a hostname or the IP address of the AS/400 system.

Note: Case is important for the user ID and password; bothshould be in uppercase.

Click the Connect button, and the wizard connects you to thespecified database.

Click Next.

Tables If the Schema(s) to View window does not appear, click theView Schema(s) button. Complete the following steps:

In the Schema(s) to View window, find the AS/400 library withwhich you want to work, which is APILIB in this case. Click on thelibrary to select it, and click the Add button.

Click OK to return to the Tables window.

Click the Select radio button in the Statement type.

Select APILIB.ORDLIN and APILIB.ITEM from the list of tablesshown.

Click Next.

Join In the ITEM table, click the IID element, and in the ORDLIN table,click the OLIID element. Both items should be highlighted. Clickthe Join button. A red line should appear between the twoelements.

Click Next.

Columns Make sure the Selected table(s) list box is set on the ORDLINelement. Select from the Columns list OLAMNT, OLQTY,OLDLVD, and OLNBR.

Now select ITEM from the Selected table(s) list box. SelectINAME and IPRICE from the Columns table.

Click Next.

Condition 1 Select OLOID in the Columns list box. Select the operator to beis exactly equal to. Click in the top values field, and click theParameter button.

In the Create a new parameter dialog box, enter the variablename orderID, and click the OK button.

Click Next.

Tabbed window Action explanation

ABC Company Web site design and development 349

5. Check the generated file orderLine.sql into the Studio Workbench. Select theOrderStatus folder. Then, right-click, and select the Check In option.

7.7.3 Using the SQL queries in the Database WizardNow that we have developed our SQL files, we can use them to generate ourdynamic JSP pages and servlets. We use the Database Wizard, which wasexplained in 3.2, “Studio Wizards” on page 28.

7.7.3.1 Using the Database Wizard on orderStatus.sqlFollow these steps:

1. Start WebSphere Studio if it is not already started.

2. Select the project folder OrderStatus.

3. Start the SQL Wizard by selecting Tools->Wizards->Database Wizard.

4. Select the appropriate SQL statement, which you created in 7.7.2.1, “Usingthe SQL Wizard to check customers orders” on page 346. It should bedrive:\subsites\OrderStatus\orderStatus.sql.

5. Click Next.

Sort No action is required.

Click Next.

SQL You should now see your SQL statement. To test that it workscorrectly, click the Run SQL... button.

We are now prompted for one parameter in the Specify ParameterValue(s) window. For this parameter, type 3479 for the orderID.Click the OK button. You should see all order lines for that orderID.

Click on the Next button, or just click the Finish button.

Finish Click Finish.

The completed SQL file should appear in the project asordrerLine.sql.

Tabbed window Action explanation

350 Web Enabling AS/400 Applications with IBM WebSphere Studio

6. Proceed through the tabbed windows of the wizard, and specify theinformation described in Table 43.

Table 43. Creating dynamic pages from the Database Wizard

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You need an input page to collect the data for insertion,an output page to show the result from the query, and an errorpage if something unforeseen happens. You also need to:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.d. Select the no data is returned check box.

Click Next.

Input Page Make sure the custID check box is selected. This should be doneby default since it was the query parameter in the SQL Wizard.

Click Next.

Results Page The results page will already have the output parameters youwanted from the SQL file. These should beAPILIB_ORDERS_OCARID, APILIB_ORDERS_OENTDT,APILIB_ORDERS_OENTTM, APILIB_ORDERS_OLINES, andAPILIB_ORDERS_OID.

To change the caption displayed in the output file, select OCARID,and click the Change button.

A change details dialog box appears. Enter the caption you wantto be associated with the OCARID field. Enter the caption CarrierNumber.

Do the same for OENTDT. Enter Order Date.

Now do the same for OENTTM. Enter Order Time.

Do the same for OLINES. Enter Number of items ordered.

Do the same for OID. Enter Order ID.

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click Next.

No Data Page Click Next.

Methods Make sure that the method named execute() is selected.

Click Next.

Session This bean is only to be used one time. We do not need to bind itto the session so make sure No is selected.

Name the bean orderStatusDBBean.

Click Next.

ABC Company Web site design and development 351

7. You should now see the following files added to the Studio Workbench:

• ordersError.jsp• ordersInput.html• ordersNoData.jsp• ordersResults.jsp

8. Select the OrderStatus folder. Then, right-click, and select the Check Inoption.

If you look inside the servlet directory, you see that the following files arecreated:

• orders.class• orders.java• orders.servlet• ordersDBBean.class• ordersDBBean.java

7.7.3.2 Using the Database Wizard on orderLine.sqlFollow these steps:

1. Start WebSphere Studio if not already started.

2. Select the project folder OrderStatus.

3. Start the SQL Wizard by selecting Tools->Wizards->Database Wizard.

4. Select the appropriate SQL Statement, which you created in 7.7.2.2, “Usingthe SQL Wizard to view order line details” on page 348. It should bedrive:\subsites\OrderStatus\orderLine.sql.

5. Click Next.

Finish Give a meaningful name to the generated source files. Click theRename button, and type orderStatus into the Prefix dialog.Click OK. Note that all of the files now have the prefix oforderStatus.

Click the Finish button to generate the code.

The Database Wizard generates and compiles the files. The fileswill be placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

352 Web Enabling AS/400 Applications with IBM WebSphere Studio

6. Proceed through the tabbed windows of the wizard, and specify theinformation shown in Table 44.

Table 44. Creating dynamic pages that require input from the Database Wizard

Tabbed window Action explanation

Web Pages This tab allows you to specify the HTML and JSP files that will begenerated. You need an input page to collect the data forinsertion, an output page to show the result from the query, andan error page if something unforeseen happens. You also need to:

a. Select the input page check box.b. Select the results page check box.c. Select the error page check box.d. Select the no data is returned check box.

Click Next.

Input Page Make sure the productID check box is selected. This should bedone by default since it was the query parameter in the SQLWizard.

Click Next.

Results Page The results page will already have the output parameters youwanted from the SQL file. These should beAPILIB_ORDERS_OLAMNT, APILIB_ORDERS_OLQTY,APILIB_ORDERS_OLDLVD, APILIB_ORDERS_OLNBR,APILIB_ITEMS_INAME, and APILIB_ITEMS_IPRICE.

To change the caption displayed in the output file, select theOLAMNT. Click the Change button.

A change details dialog box appears. Enter the caption you wantto be associated with the OLAMNT field. Enter the captionAmount.

Do the same for OLQTY. Enter Quantity Ordered.

Do the same for OLDLVD. Enter Delivery Date.

Do the same for OLNBR. Enter Item number.

Do the same for INAME. Enter Product Name.

Do the same for IPRICE. Enter Product Unit Price.

Ensure that the Table radio button is selected.

Click Next.

Standard Error Page Click Next.

No Data Page Click Next.

Methods Make sure that the method named execute() is selected.

Click Next.

ABC Company Web site design and development 353

7. You should now see the following files added to the Studio Workbench:

• orderLineError.jsp• orderLineInput.html• orderLineNoData.jsp• orderLineResults.jsp

8. Select the OrderStatus folder. Then, right-click, and select the Check Inoption.

If you look inside the servlet directory, you also see that the following files arecreated:

• orderLine.class• orderLine.java• orderLine.servlet• orderLineDBBean.class• orderLineDBBean.java

7.7.4 Testing the Order Status pagesNow that the order status pages have been built, we can test then to see if theresult is what we want. It is much easier to fix the pages at this point.

Make sure you have a publishing target setup. Refer to 4.3.1, “Publishing to theAS/400 system” on page 125, if you have not done this yet. At this point, it is justfor testing. We recommend that you use a directory that has been allocated toyou on the AS/400 system. Or, test locally on a Windows NT machine that isrunning WebSphere Application Server and the Apache Web server.

Session This bean is only to be used one time. We do not need to bind itto the session so make sure No is selected.

Name the bean orderLineDBBean.

Click Next.

Finish Give a meaningful name to the generated source files. Click theRename button, and type orderLine into the Prefix dialog. ClickOK. Note that all of the files now have the prefix of orderLine.

Click the Finish button to generate the code.

The Database Wizard generates and compiles the files. The filesare placed in a checked out state in the Studio Workbench. Youmay receive the warning:

Issued 1 system warning:*** Warning: "%CLASSPATH%" is either not a valid zipfile or it contains a zip file comment. If it containsa comment, rezip it without the comment.

You can ignore this warning.

Tabbed window Action explanation

354 Web Enabling AS/400 Applications with IBM WebSphere Studio

Follow these steps:

1. Once you have published your pages, make sure your WebSphere ApplicationServer and Web server are both started.

2. Inside the WebSphere Studio, right-click the ordersInput.html, and selectPreview File with->Netscape. Your page should look similar to the examplein Figure 316.

Figure 316. ordersInput.html displayed in Netscape

3. Enter a valid customer ID. Type 0011.

4. Click the Submit button, and you should see a page that looks like theexample in Figure 317.

Figure 317. ordersResults.jsp displayed in Netscape

If you get an error page or something that you did not expect, try restarting theWebSphere Application Server and republishing the site.

Now we should test the orderLine page. Follow these steps:

1. Right-click on the orderLineInput.html, and select Preview File with->Netscape. The input page should look like the display in Figure 318 on page356.

ABC Company Web site design and development 355

Figure 318. orderLineInput.html displayed in Netscape

2. For orderID, type in a value of 3479.

3. Click the Submit button. The result page should look like the display in Figure319.

Figure 319. orderLineResults.jsp displayed in Netscape

7.7.5 Joining the order status with the order lineIn this section, we join the ordersResults.jsp file to the orderLineResults.jsp.Follow these steps:

1. In the WebSphere Studio, double-click on the ordersResults.jsp file. Thischecks it out and opens it in the Page Designer. The page should look like thedisplay in Figure 320.

Figure 320. ordersResults.jsp open for editing

2. You do not need to display the Order ID to the customer. Right-click on theJSP tag inside this column, and select Delete.

356 Web Enabling AS/400 Applications with IBM WebSphere Studio

3. Select the Order ID heading text, and press the Delete key.

4. Type View Order in the top right heading cell of the table.

5. Select Insert->Form and Input Fields->Push Button->Submit button. EnterView order details for the label and orderLine for the name. In the Submitbutton attribute dialog box, click OK.

We now need to get the parameters that we need to pass to theorderLineResults.jsp page. Complete these tasks:

1. In the WebSphere Studio, double-click on the orderLineInput.html file. Thischecks the file out and opens it in Page Designer. The page should appear asshown in Figure 321.

Figure 321. orderLineInput.html open for editing

2. Double-click on the field next to the orderID caption. This opens the Text FieldAttribute box.

3. Make a note of the name listed. The name should be orderID. You will needthis information later in this section.

4. Click in the drop-down list box next to the Tag caption, and select Form. Thistakes you to the form properties.

5. Make note of the Action field. The action should be/servlet/orderStatus.orderLine, provided you followed the wizards correctlyearlier. Click OK.

We now have the information we need to be able to join the ordersResults.jsp fileto the orderLineResults.jsp file. Follow these steps:

1. Return to the Page Designer where the ordersResults.jsp page should still beopen. If it is not, double-click on the ordersResults.jsp file in the WebSphereStudio.

2. Double-click on the View order details button. Click the drop-down list boxnext to the Tag caption at the top of the Push Button Attribute dialog box, andselect Form.

3. For the action of this form, type /servlet/orderStatus.orderLine (noted earlier).

4. Set Method to Post.

5. Click on the Hidden Fields tab at the top of the page.

6. Enter orderID for the hidden field name.

ABC Company Web site design and development 357

7. For the value field, select the Specify by property check box, and click theBrowse... button.

8. In the Bean Property Selection, select the bean propertyAPILIB_ORDERS_OID(). Click OK.

9. Click the ADD button. You should see your parameter added as a hidden field.

10.Click OK in the Form Attributes dialog box. Your page should now look like theexample in Figure 322.

Figure 322. ordersResults.jsp after modification

11.Save this page and exit Page Designer. In WebSphere Studio, right-click onthe orderStatus directory, and select Check In.

12.Right-click on the orderStatus directory, and select Publish whole project.

7.7.6 Testing the order status subsiteWe are now ready to test the two pages that we joined. We use this process:

1. Right-click on the ordersInput.html file, and select Preview File with->Netscape. You should see a page like the example in Figure 323.

Figure 323. ordersInput.html displayed in Netscape

2. Enter 0011 for the custID parameter. Click Submit. You should see the pageshown in Figure 324.

358 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 324. ordersResults.jsp displayed in Netscape

3. Click on the first View order details button. You should see the page shown inFigure 325.

Figure 325. orderLineResults.jsp displayed in Netscape

ABC Company Web site design and development 359

360 Web Enabling AS/400 Applications with IBM WebSphere Studio

Chapter 8. Creating the complete ABC Company Web site

In Chapter 7, “ABC Company Web site design and development” on page 157, wedeveloped the subsites to be integrated into the complete ABC Company Website. Now that we have the subsites and navigation, we need to develop the lookand feel of the Web site.

8.1 Web site development: Issues and pitfalls

This section discusses the issues involved in Web-site design and production,and how to avoid common mistakes. The main goal is to give users a reason tokeep visiting the Web site. The key points to creating a good Web site includeseveral design objectives.

8.1.1 Design objectivesThis section discusses Web site development issues in regard to design.

8.1.1.1 Information architectureWebSphere Studio can be used to create storyboards and show the Web sitestructure. You may want to consider having an index for the Web site. The pagesdirectly below the main page can act as categories. Then, each page under oneof these pages will describe this area of the Web site in more detail. Exampleguidelines include:

• Create a Web site branching diagram or storyboard that shows what pagesthe Web site includes.

• Consider how the information will be organized and how it will be accessed bythe user.

• Group information into categories.

8.1.1.2 Design issuesUsers can usually connect to the Web site through any page. This can be limitedthrough cookies, scripts, and access control. Users do not always follow aparticular linear path through the Web site. Make sure that each page has enoughinformation about the company or the Web site so that when a user arrives at apage in the Web site, they know what to do and how the page may serve them.Example guidelines include:

• Users can choose their own path though the Web site:

– May revisit the Web site via a bookmark– Can mark areas to be navigated to and from any page

• The contents of a Web site should changed at a regular and predictable time.

• Give users a reason to keep visiting your site.

8.1.1.3 Interface designThe right impression is not necessarily a good impression. Example guidelinesare:

• Consider how your Web site is presented to the user.

• Make the right impression.

© Copyright IBM Corp. 2000 361

• Use standard Web navigation techniques:

– Icons: Home, Search, Mailbox

– Typical company information, such as Home, News, Products,Employment, About

• Be consistent in the format for the Web site.

WebSphere Studio will help.

• Page architecture considerations:

– Create the look and feel

– Lay out the contents on the page

– Provide navigation to other pages through buttons or icons in the documentthat link back to the parent document or forward to the next topic

8.1.1.4 Content negotiationEach time a browser requests a page from a Web server, the browser sendsinformation about itself (User Agent) along with the request. This information canbe used to send the appropriate page for a given browser.

You can design versions of the Web site based on particular browser capabilities,such as frames or text only. You can also design versions of the Web site forconnection speeds, such as low bandwidth or high bandwidth. However, the usermust pick the version of the Web site, the server has no easy way of determiningthe connection speed. An example guideline is content negotiation, which is theprocess of creating versions of pages in the Web site. It includes:

• Supporting different browser features• Different network bandwidth (text only versus rich media)• User preferences• Regionalization (NLS)• Authentication and security

8.1.1.5 LinkingYou can also use HTML tags to specify alternative actions. ALT tags show up asfly-over help in some browsers so you should always use them. Exampleguidelines are:

• The initial page of information should be high level.

– TOC, headlines, attractive– Linking should be used to get more detailed information

• Content of a document should be able to be read without the links or theimages:

– Usually avoid such phrases as "Click here”.– Use ALT tags where appropriate.

• Instead of copying information, link to it.

362 Web Enabling AS/400 Applications with IBM WebSphere Studio

8.1.2 ProductionThis section discusses Web site development issues in regard to production.

8.1.2.1 Form and contentExample guidelines are:

• The information is displayed and read on paper, so keep it simple.• Make information easy to read.• Create chunks of information that are organized and grouped.• Other guidelines include:

– Compare style guides.– Many HTML and Web style guides available.– Use ordered lists for procedures and unordered lists for a set of choices.

8.1.2.2 ContentExample Guidelines are:

• Avoid:

– Making the user scroll– Welcome messages– Introductory paragraphs

• Concentrate on providing facts.

8.1.2.3 View on paperExample guidelines are:

• Consider providing a PostScript or Acrobat file if users will typically print theinformation.

• If users want to print a group of pages at once, create an Acrobat orPostScript version of the file.

8.1.2.4 Production issuesExample guidelines are:

• Consider images and other media:

– Require more bandwidth; should have high-impact content.– Consider providing a text-only alternative.– Use industry standard formats (GIF, JPEG, MP3)

• Consider users with special needs:

– Consider media to improve accessibility.

– Investigate IBM Special Needs Solutions to improve accessibility. It islocated on the Web at: http://www.austin.ibm.com/sns/access.html

8.1.2.5 ImagesExample guidelines are:

• Interlaced images let the user see portions of the image sooner.

• Multipart GIFs provide simple animation.

• Trade-offs in image size and quality need to be made.

• Browsers cache images on the client machine’s disk and memory.

Creating the complete ABC Company Web site 363

• Provide a textual alternative to image maps, and avoid using a large imagemap for the initial page (performance).

• Use ALT, HEIGHT, and width elements in the IMG tag:

– ALT string shows up if images are disabled– ALT string appears as fly-over help– HEIGHT and width permits layout prior to image loading

8.1.2.6 MultimediaMany media types are supported by browser plug-ins. Example guidelines are:

• Audio and video can enhance the Web site.

Should be central to the Web site goals (due to performance impact), forexample, music (CD) stores, real estate (house walk-throughs).

• Streaming audio and video formats are most appropriate on the Web.

Only a portion of the clip is required at the browser at any time.

8.1.2.7 TestingThe staging server should duplicate the server environment as much as possible,including a firewall, if applicable. Example guidelines are:

• Create a staging server that duplicates the server structure.

• Test, test, and test some more:

– Different platforms and different browsers– Graphics on and off– HTML verification– Prepare graphics and other media for low-bandwidth transmission– Create and test links– Test over the Internet

8.1.3 PublicizingExample guidelines are:

• Register memorable domain names.

• Register common variants of the company name.

• Register with such search services as Yahoo.

• Look for other sites on the Web that attract the same audience and let themknow about your Web site.

• Modify HTML for Web crawlers; can be set to not allow a bookmark(META-TAG).

• Propose that the Web site be listed as a cool or new site.

8.1.4 Evaluating the Web siteExample guidelines include asking these questions:

• Is there a logical structure of the Web site?

One page should equal one topic.

• Is the information grouped into meaningful categories?

Show a list of content categories, typically no more than about seven.

364 Web Enabling AS/400 Applications with IBM WebSphere Studio

• Does the home page tell the user what the Web site has to offer?

Trade-off: Link to all Web site content versus keeping the home page simple.

• Can information be found and retrieved easily and quickly?

The user should be able to get to the information in three clicks or less.

We have tried to employ these simple and easy to follow ideas across all pages inthe ABC Company Web site sample project.

8.2 Creating static pages

This section discusses static page creation techniques using WebSphere Studio.

8.2.1 Content of static HTML pagesAs explained earlier, we have a few pages that are static and represent who thecompany is and try to build credibility with new customers. It is good to give thecompany history and establish that the company is real.

Another good item to put on every single page is the company address andcontact number. This allows people to find out who the company is and speak tosomeone if they have questions, comments, or concerns.

We need to create a new project for the static subsites. Follow the same processoutlined in 3.1.1, “Creating a new project” on page 24, for creating a new project,but use these parameters:

1. Type Static as the name of the name of the project.2. Enter C:\Static as the name of the project folder.3. Select <none> for the project template.

A new project will be created called Static.

8.2.2 Working with existing pagesSome static pages were created earlier in 3.3.2, “Constructing the Logon page”on page 97. This was done to give you a feel for how to use Page Designer andWebArt Designer. We use the techniques covered in those sections to build ourstatic pages. To import these files, complete the following steps:

1. Click on the Static folder in the WebSphere Studio.

2. Select Insert->File.

3. Click on the Use Existing tab. You are presented with the Insert File dialogbox shown in Figure 326 on page 366.

Creating the complete ABC Company Web site 365

Figure 326. Inserting existing files into a new project

4. Click the Browse button.

5. You should now see an Open dialog box window. Browse to select the filesused in 3.3.2, “Constructing the Logon page” on page 97. Then, click theOpen button. The files should be:

• \DemoCompany\ABC_Comapny\Logon.html• \DemoCompany\Images\banner.html• \DemoCompany\Images\general.mif

6. Deselect the Remove the original file after copying check box. Then, clickOK.

7. The files should now be entered into your static subsite. Double-click onLogon.html. It should be checked out and opened in Page Designer. Thepage should look like the example in Figure 327.

366 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 327. Page Designer: Logon page template

8. Close the Page Designer window.

8.2.2.1 Creating the Web site template fileWe now need to take this sample page and change it in to a template so we canwork with it later. Follow these steps:

1. In WebSphere Studio, right-click the Logon.html file, and select Copy.

2. Right-click on the Static folder, and select Paste. You should be given a filecalled Copy-1-of-Logon.html.

3. Select the Logon.htm file. Right-click on it, and select Delete.... The dialogbox shown in Figure 328 appears.

Figure 328. Delete files dialog box

4. Leave the option Delete from disk selected, and click the OK button.

5. Click Yes to All if you are asked about breaking any links.

6. Right-click on the Copy-1-of-Logon.html file, and select Rename. For thenew name of this file, type WebsiteTemplate.html.

Creating the complete ABC Company Web site 367

You should now have a project that looks like the example in Figure 329.

Figure 329. WebSphere Studio project after creating the template file

8.2.2.2 Modifying the HTML fileWe now need to modify the WebsiteTemplate.html file and store it as a template.The technique for making a HTML file available as a template is covered in 3.3.3,“Creating a page template” on page 102. Follow these steps:

1. Double-click the WebsiteTemplate.html file. This checks it out and opens it inPage Designer.

2. You should see that all the images for this file are missing. Do not worry aboutthis for now since we are really only interested in the table layout on this page.The page should look like the example in Figure 330.

Figure 330. Page Designer: Template page before modifications

3. Right-click on one of the broken images. These are the boxes that have thebig red cross through them. Select Delete.

368 Web Enabling AS/400 Applications with IBM WebSphere Studio

4. Repeat step 3 for all of the broken images.

5. Right-click on the table that contains the Submit and Reset buttons. SelectDelete.

6. Right-click on the table that contains the user ID and password fields. SelectDelete.

7. You are now left with the element inside the bottom right cell. Right-click onthe form, and select Delete.

8. Double-click inside the bottom right cell to view the Attributes of this cell.Select Left for the Horizontal Alignment and Top for Vertical Alignment.

9. Double-click inside the table in the bottom left. Be careful to select the outsidetable and not the inside button layout table. In the cell Attribute window, selectLeft for the Horizontal Alignment and Top for the Vertical Alignment.

The page should contain two empty tables and look like the example in Figure331.

Figure 331. Page Designer: Empty template file

10.Click in the top left cell of the page, and select Insert->Image. Select thebook.gif image from the Open dialog box, and click the OK button.

11.Click in the bottom right cell, and select Table->Add Row->Add Below Cell.

12.Click in one of the newly added cells. Hold down the Shift key, and click in theother newly created cell. They should both be highlighted.

13.Right-click in either of the highlighted cells, and select Join Selected Cells.

14.Double-click in the new long cell at the bottom of the table. Inside the Attributedialog box on the cell attribute page, select Center for horizontal alignmentand Top for vertical alignment. Close this dialog box.

15.Enter the company details in the bottom cell. Type the following information:

ABC Company1234 Main StAnywhere USA 12345Phone (111) 111 1234 Fax (111) 111 2345

Creating the complete ABC Company Web site 369

16.Save this file, and exit the Page Designer.

17.Right-click on the Static folder in the Studio Workbench, and select Check In.

We are now ready to make this file into our first template for our Web site. Followthe process described in 3.3.3, “Creating a page template” on page 102, to makethis page in to a page template. Rename the page to ABCCompanyTemplate.html.

We use this template to create more specific templates for the subsites. This is aslightly clumsy process, but it forces our Web site to be consistent across allpages.

8.2.3 Creating images for all linksAfter looking at the subsite requirements, we can determine the links we need tohave. All the links are navigated with images so we need an image for each link.We already discussed how to use the WebSphere WebArt Designer to create theimages for the links. Now we decide on the captions for these images.

In 8.2.2, “Working with existing pages” on page 365, we imported the templatenavigation image files called general.mif and banner.mif. In this section, we editthe general.mif file to give us all our links that we will use. Follow this process:

1. In the Studio Workbench, click on the Static folder, and select Insert->Folder.

2. In the text field under folder name, type Images, and click the OK button. Thiscreates an Images folder inside the Studio Workbench.

3. In the Studio Workbench, double-click the general.mif file. This checks it outand opens it in the WebSphere WebArt Designer. The general.mif file shouldhave a small blue circle and a caption which looks similar to the exampleFigure 332.

Figure 332. WebArt Designer: Opening the general.mif file

370 Web Enabling AS/400 Applications with IBM WebSphere Studio

4. Double-click the About Us caption to open the Edit Logo Object dialogwindow. Then, in the text field, type Welcome.

5. Close the Edit Logo Object dialog window.

6. Select File->Save Wizard. Make sure the Object Only option is selected, andclick the Next button.

7. In the next wizard page, make sure the GIF option is selected. Then, click theNext button.

8. Click Finish.

9. In the Save As dialog box, find the \Static\Images project folder. Typewelcome.gif for the file name.

10.Make sure both the Add to WebSphere Studio and Make source link checkboxes are selected. Click the Save button.

11.Repeat steps 4 through 10, changing only the caption and the GIF file name.The information is provided in Table 45.

Table 45. Input information for creating the button images

12.Close the WebArt Designer window.

13.From the Studio Workbench, select the Images folder. Then, selectInsert->File from the pull-down menu. From the Insert File dialog window,click the Use Existing tab, browse to the location where you stored the bookanimation GIF file (bookani.gif). Select it, and click the OK button.

Now we modify the banner.mif file to produce two different banners. One of thebanners identifies to the user that they are on the registered user page. The otherbanner identifies the normal site. Follow these steps:

Button Input information

Welcome Caption: WelcomeFile: welcome.gif

About Us Caption: About UsFile: aboutUs.gif

Catalog Caption: CatalogFile: catalog.gif

Login Caption: LoginFile: login.gif

Logout Caption: LogoutFile: logout.gif

Generate New User Caption: Generate New UserFile: newUser.gif

Shopping Cart Caption: Shopping CartFile: shoppingCart.gif.

Purchase Caption: PurchaseFile: purchase.gif

Order Status Caption: Order StatusFile: orderStatus.gif.

Creating the complete ABC Company Web site 371

1. In the Studio Workbench, double-click the banner.mif file. This checks it outand opens it in the WebSphere WebArt Designer. The banner.mif file shouldhave a small blue circle and a caption that looks similar to the example inFigure 333.

Figure 333. WebArt Designer: ABC Company general area banner

2. Double-click on the bottom ABC Company text to open the Edit Logo Objectproperties window. Set the font size to 56.

3. Close the Edit Logo Object dialog window.

4. Resize the blue cycle, so the ABC text fits into it.

5. Select File->Save Wizard. Make sure the Object Only option is selected, andclick the Next button.

6. In the next wizard page, make sure the GIF option is selected. Then, click theNext button.

7. Click Finish.

8. In the Save As dialog box, find the \Static\Images project folder. Typebanner.gif for the file name.

9. Make sure both the Add to WebSphere Studio and Make source link checkboxes are selected. Then, click the Save button.

We now need to modify this image so that we have an alternative banner. Thealternative banner will indicate to the user they are in the registered user area ofthe ABC Company Web site. We use this process:

1. Click on the ABC Company text, and select Edit->Copy.

2. Select Edit->Paste. Now move the image that has just been pasted andposition it underneath the existing ABC Company word. The window shouldlook like the display in Figure 334.

372 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 334. WebArt Designer: Creating the ABC Company user area banner

3. Double-click on the bottom ABC Company text to open the Edit Logo Objectproperties window. Type Registered User Area. Set the font size to 25.

4. Click the Color tab. From the group-drop down list box, select Gradation.From the type list, select monotone.

5. Click the Outline tab, and select None for Type.

6. Click on the Logo Effect tab, and select Drop Shadow. Set Direction to Left,Strength to 1 notch from the left, the X and Y distances are both to 1 pixel, andColor to black. All of this information is shown in Figure 335.

Figure 335. WebArt Designer: Logo effect properties

7. Close the Edit Logo Object window, and position the new label to theright-hand side under ABC Company text. The final result should look like thedisplay in Figure 336 on page 374.

Creating the complete ABC Company Web site 373

Figure 336. WebArt Designer: ABC Company registered user area banner

8. Select File->Save Wizard. Make sure the Object Only option is selected, andclick the Next button.

9. In the next wizard page, make sure the GIF option is selected. Then, click theNext button.

10.Click Finish.

11.In the Save As dialog box, find the \Static\Images project folder. TyperegisteredBanner.gif for the file name.

12.Make sure both the Add to WebSphere Studio and Make source link checkboxes are selected. Then, click the Save button.

13.Close the Page Designer window.

14.From the Studio Workbench, check in all files in the Static project folder.

We now have all the images we are going to use to produce the ABC CompanyWeb site templates.

8.3 Creating the normal and registered user templates

This section explains how to create templates for normal and registered userareas. Normal pages are HTML files, and registered user pages are JSPs.

8.3.1 Normal page templatesAt this point, the Static project in the Studio Workbench should look like thedisplay in Figure 337.

374 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 337. Studio Workbench: Static project status

Make sure all the GIF files have been checked in. This means that the files canbe published.

We are going to use this current directory structure throughout the entire Website. This is important to remember because once we start to build templates thathave images in them, we can only use those templates inside of a Web site thathas the same image directory structure. We now see how to build thesetemplates:

1. Click on the Static folder in the Studio Workbench, and select Insert->File.You should see the ABCCompanyTemplate.html file. If you do not see this file,review 8.2.2, “Working with existing pages” on page 365, to see how to createthis file.

2. Click on this file, and type staticPageTemplate.html for the file title. Click OK.The file should be added to the Studio Workbench.

3. Double-click the staticPageTemplate.html file. This checks it out and opens itin the Page Designer. The page should look similar to the example in Figure338 on page 376.

Creating the complete ABC Company Web site 375

Figure 338. Page Designer: Empty template page

4. Try to set up your monitor so that you can see the Studio Workbench and thePage Designer. Select the image in the Studio Workbench called banner.gif.Drag it across to the top right cell of the table in the Page Designer. If you havedifficulty dragging between Studio Workbench and the Page Designer, you canselect Insert->Image inside the Page Designer.

5. In the Studio Workbench, select the image called welcome.gif. Drag thisacross to the Page Designer and drop it in the second cell of the inside table.The page should look like the example in Figure 339.

Figure 339. Page Designer: Creating the static template

376 Web Enabling AS/400 Applications with IBM WebSphere Studio

6. We now want to repeat step 5 for the following files:

• aboutUs.gif• history.gif• catalog.gif• login.gif• newUser.gif.

If you run out of cells on the inner table, click on the bottom cell, and selectTable->Add Row->Add Below Cell.

7. The final image to add is the book animation. Drag the bookani.gif imagefrom the Studio Workbench, and drop it in the top left cell of the table.

8. Set the spacer cell at the top of this table to give the first image some spacefrom the top. Double-click in the first cell on the inner table, which is just abovethe welcome image. On the Cell Attribute window, set the height to 30. Yourpage should look like the example in Figure 340.

Figure 340. Page Designer: Completed static template page

9. Save this file, and exit the Page Designer. In the Studio Workbench, right-clickon the Static folder, and select Check In.

You are now ready to make this file a template for the ABC Company Web site.Follow the process described in 3.3.3, “Creating a page template” on page 102, tomake this page a template. Leave the file name as staticPageTemplate.html.

8.3.2 Registered user templatesWe now need to generate a template that we can easily use for all our registereduser subsites. We follow a similar process to what we did in the last section, butthere are some variations:

Creating the complete ABC Company Web site 377

1. Click on the Static folder in the Studio Workbench, and select Insert->File.You should see the ABCCompanyTemplate.html. If you do not see this file,review 8.2.2, “Working with existing pages” on page 365, on how to create thisfile.

2. Click on this file, and type dynamicPageTemplate.html for the file title. Click OK.The file should be added to the Studio Workbench.

3. Change the file extension since all the registered users are JSPs. Right-clickon the dynamicPageTemplate.html file, and select Check In.

4. Right-click on the dynamicPageTemplate.html file again, and selectRename. Enter the new file name dynamicPageTemplate.jsp. You should bepresented with the dialog box shown in Figure 341. Click the Yes button. It isimportant that you change the MIME type.

Figure 341. MIME type change warning

5. In the Studio Workbench, double-click on the dynamicPageTemplate.jsp file.This checks the file out and opens it in Page Designer.

6. Drag the image called registeredBanner.gif from the Studio Workbench tothe Page Designer. This image goes in the top right cell. This new bannertakes the place of the banner.gif in the static pages.

7. In Page Designer, click in the second cell of the inner table. SelectInsert->Form and Input Fields->Push Button->Image Button. You arepresented with the dialog box shown in Figure 342.

378 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 342. Push button attribute dialog box

8. Click on the Browse... button next to the Image File field. You need tonavigate to the Images directory inside the Static project directory. Select theshoppingCart.gif file, and then click the OK button.

9. Click in the Name field, and type shoppingCart.

10.Click OK in the Push Button Attribute window. The page should now look likethe example in Figure 343.

Figure 343. Page Designer: ABC Company registered user template page in progress

Creating the complete ABC Company Web site 379

11.Click on the HTML Source tab at the bottom of the Page Designer. You nowsee the HTML code that makes up this page. Find the line of HTML that lookslike:

<INPUT type="image" name="shoppingCart"src="file:///F:/redbook/Static/images/shoppingCart.gif">

Change it to look like:

<INPUT type="image" name="shoppingCart"src="file:///F:/redbook/Static/images/shoppingCart.gif" border="0">.

This ensures there is no border around your image when people look at thepage.

12.Repeat step 7 through step 11 for the following images:

• catalog.gif• purchase.gif• orderStatus.gif• logout.gif.

Set the names of these files to the file names but without the GIF extension.Do not forget to set the border to 0 for each item.

13.The final image to add is the book animation. Drag the bookani.gif imagefrom the Studio Workbench, and drop it in the top left cell of the table.

14.Set the top cell of the inner table to have a height of 30 just as you did before.The final page should look like the example in Figure 344.

Figure 344. Page Designer: ABC Company registered user area page

15.Save this file, and close Page Designer.

380 Web Enabling AS/400 Applications with IBM WebSphere Studio

16.Right-click on dynamicPageTemplate.jsp, and select Check In.

We are now ready to make this file a template for the ABC Company Web site.Follow the process described in 3.3.3, “Creating a page template” on page 102, tomake this page a template. Leave the file name as dynamicPageTemplate.jsp.

8.3.3 Session management servlet, login servlet, and custID beanThe servlets used here will get their configuration information from theWebSphere Application Server. We refer to the servlets by alias. Follow thesesteps:

1. Place the cursor at the top of the page. Select Insert->Servlet. You shouldsee the dialog box shown in Figure 345.

Figure 345. Servlet attribute dialog box

2. In the Name field, type check. In the Code field, type check. This calls the aliasthat does the user validation on each page. Click OK.

3. Next to the first JSP tag, select Insert->JSP Tags->Insert a Bean. You shouldsee a dialog box like the one in Figure 346 on page 382.

Creating the complete ABC Company Web site 381

Figure 346. JSP attribute dialog box

4. For the name field, type custIDBean. In the Type field, enter Session.CustIDBean.Select the No Introspection and Create radio buttons. Make sure the scope isset to session, and click the OK button.

8.4 Assembling the ABC Company Web site

Now that the templates have been developed, we can use them to begin thegeneration of the static pages. Follow these steps:

1. To create a new project for the ABC Company Web site. Follow the sameprocess described in 3.1.1, “Creating a new project” on page 24, for creating anew project, but use the following parameters:

a. Type ABCCompany for the name of the name of the project.b. Enter C:\ABCCompany as the project folder.c. Leave project template as <none>.

A new project is created called ABCCompany.

2. In the Studio Workbench, click on the ABCCompany folder. SelectInsert->Folder...

3. In the Insert Folder dialog box, click on the Use Existing tab. The dialog boxshould look like the one in Figure 347.

382 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 347. Studio Workbench: Insert folder dialog box

4. Click the Browse... button, and navigate to the Static folder that we used inthe previous section. Inside the Static folder, click on the Images folder, andclick the OK button.

5. The folder name should now be displayed in the Folder Name field. Click theAdd button, and then click the OK button.

We should now have the Images folder added to the ABCCompany project folder.This allows us to work with our existing templates without breaking any imagelinks. Follow these steps:

1. In the Studio Workbench, click on the ABCCompany folder. SelectInsert->Folder.

2. In the Insert Folder dialog box, type StaticPages for the folder name. You arenow ready to begin adding some pages that you are going to use.

3. Click on the ABCCompany folder in the Studio Workbench. SelectInsert->File.

4. In the Insert File dialog box, select the staticPageTemplate.html file. If this isnot present, review 8.3, “Creating the normal and registered user templates”on page 374. For the file name, type index.html, and click the OK button.

5. Select View->Relations, and then click on the index.html file. There shouldnot be any broken links between this file and the images. The StudioWorkbench should look like the display in Figure 348 on page 384.

Creating the complete ABC Company Web site 383

Figure 348. Studio Workbench: ABC Company project with files and relations view

6. Add all the other files that you want to use in the static section of the Web site.Repeat steps 3 and 4 using the following parameters for the page names:

• aboutUs.html• history.html• catalog.html• login.html• logout.html• newUser.html

7. Select all of these .html files, and drag them to the StaticPages folder. Allimage links will be updated automatically. If you put the files directly in thatfolder, then the WebSphere Studio would not have known the correct imagesto use.

8. Select View->Relations. Then, browse through the StaticPage folder makingsure there are no broken links. You should even note the correct reference tothe Master.css file.

8.4.1 Adjusting the links on the static pagesThis information is to be applied across all of the static pages that have just beencreated. Follow these steps:

1. Double-click the index.html file in the Studio Workbench to open it in PageDesigner.

2. Right-click on the image that has the caption Welcome, and select DeleteRow.

3. Click the About Us image, and select Insert->Link. You are presented withthe Link Attribute dialog box. Click on the To URL tab, and you should see thedialog box shown in Figure 349.

384 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 349. Link Attribute dialog box

4. Go back to the Studio Workbench, and right-click on aboutUs.html, which canbe found in the StaticPages folder. Select Copy as URL text.

5. Return to the Page Designer, and right-click inside the URL field next to theBrowse button. Select Paste.

6. Click the OK button once you have the URL in place.

7. Repeat the process for all the links using the information given in Table 46.

Table 46. Linking static HTML pages

Page What to do with the links

index.html Welcome - Delete rowAbout Us - /StaticPages/aboutUs.htmlhistory - /StaticPages/history.htmlcatalog - /StaticPages/catalog.htmlLogin - /StaticPages/login.htmlNew Users - /StaticPages/newUsers.html

aboutUs.html Welcome - /StaticPages/index.htmlAbout Us - Delete rowhistory - /StaticPages/history.htmlcatalog - /StaticPages/catalog.htmlLogin - /StaticPages/login.htmlNew Users - /StaticPages/newUsers.htm

catalog.html Welcome - /StaticPages/index.htmlAbout Us - /StaticPages/aboutUs.htmlhistory - /StaticPages/history.htmlcatalog - Delete rowLogin - /StaticPages/login.htmlNew Users - /StaticPages/newUsers.htm

Creating the complete ABC Company Web site 385

8. Once this is completed, look through the Studio Workbench with the relationsview selected. Check each of the pages, and make sure all the links areconnected. You should look for a view like the one shown in Figure 350.

history.html Welcome - /StaticPages/index.htmlAbout Us - /StaticPages/aboutUs.htmlhistory - Delete rowcatalog - /StaticPages/catalog.htmlLogin - /StaticPages/login.htmlNew Users - /StaticPages/newUsers.htm

login.html Welcome - /StaticPages/index.htmlAbout Us - /StaticPages/aboutUs.htmlhistory - /StaticPages/history.htmlcatalog - /StaticPages/catalog.htmlLogin - Delete rowNew Users - /StaticPages/newUsers.htm

logout.html Welcome - /StaticPages/index.htmlAbout Us - /StaticPages/aboutUs.htmlhistory - /StaticPages/history.htmlcatalog - /StaticPages/catalog.htmlLogin - /StaticPages/login.htmlNew Users - /StaticPages/newUsers.htm

newUser.html Welcome - /StaticPages/index.htmlAbout Us - /StaticPages/aboutUs.htmlhistory - /StaticPages/history.htmlcatalog - /StaticPages/catalog.htmlLogin - /StaticPages/login.htmlNew Users - Delete row

Page What to do with the links

386 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 350. Studio Workbench: ABC Company project with a relations view

Notice how all the lines between all the files are solid. Now that the pages arelinked, the WebSphere Studio will manage these links. You can move files whereever you choose inside the WebSphere Studio and the links are automaticallyupdated.

8.4.2 Modifying the Welcome pageTo modify the Welcome page, follow these steps:

1. In the Studio Workbench, double-click the index.html file. This checks out thefile and opens it in the Page Designer.

2. Double-click in the middle right cell of the table. This shows the Attributestable. Select Center for the horizontal alignment. Click OK.

3. Press Enter once in the same cell, and then type Welcome.

4. Double-click the text you just entered. This opens the Physical EmphasisAttribute dialog box shown in Figure 351 on page 388.

We could have defined all the links in the templates and then we would haveonly needed to delete the rows for the links we did not need. This can make thejob much faster, but you need to plan ahead to make it a worthwhile venture. Ifyou do not plan ahead sufficiently, you can spend more time fixing the Web sitebroken links.

Hint

Creating the complete ABC Company Web site 387

Figure 351. Physical emphasis attribute dialog box

5. Select +2 for the font size from the drop-down list box.

6. Select the Bold check box. Then click the OK button.

7. Press Enter twice, and then enter the following text:

Welcome to the ABC Company. We hope that you enjoy your visit with us. Ifyou need to contact us for anything, do not hesitate to call us at thetelephone number listed at the bottom of every page.

This text tries to establish some form of trust with the user by telling them thatthey can find out who you are and that you are not trying to hide from them.

8. Press Enter three times, and then enter the following text:

If you have already registered with us, you can simply click on the Loginlink on the left-hand side.

This text tells existing users how to navigate the ABC Company Web sitesimply if they do not understand what the links mean down the side.

9. Press Enter twice, and then enter the following text:

If you are new to our Web site, we recommend that you click on the New Userslink.

This text tells the new users where to begin if they are not too sure.

10.Select Edit->Spelling. This spell checks your document.

8.4.3 Modifying the About Us pageComplete the following steps to modify the About Us page:

1. In the Studio Workbench, double-click aboutUs.html. This checks out the fileand opens it in Page Designer.

2. Set the aboutUs.html file the same way as the index.html page with theheading in bold and everything centered. Remember to type About Us, insteadof “welcome”.

388 Web Enabling AS/400 Applications with IBM WebSphere Studio

3. Type the following text:

About Us

We are an American company that has been distributing our products to peoplefor over the past 100 years. We take pride in our work and thrive oncustomer satisfaction.

The ABC Company is a wholesale supplier with our warehouse located at:

1234 Main St

Anywhere USA 12345

The ABC Company wants to deliver huge discounts directly to the publicthrough our Internet initiative scheme.

This text tells the user again where the warehouse is and what the company istrying to do. It is always good to have company mission statements andobjectives here and even comments and feedback that have come from thecustomers.

8.4.4 Modifying the History pageTo modify the History page, follow these steps:

1. In the Studio Workbench, double-click on history.html. This checks out thefile and opens it in Page Designer.

2. Set the history.html file the same way as the index.html page with theheading in bold and everything centered. Remember to type History instead of“welcome”.

3. Type the information about the history of the company. Refer to Chapter 4,“Restoring the ABC Company Web site sample project” on page 121, if youwant sample text.

8.4.5 Modifying the Logout pageComplete these tasks to modify the Logout page:

1. In the Studio Workbench, double-click on the logout.html. This checks out thefile and opens it in the Page Designer.

2. Set the logout.html file the same way as the index.html page with the headingin bold and everything centered. Remember to type Logout instead of“welcome”.

3. Type the following text:

Thank you for shopping with the ABC Company.

Any orders that you placed should be shipped within two working days.

This indicates to the user when they should expect their items that they mayhave purchased. It would be better to convert this page to a JSP and give theuser specific information about their actual purchase. For this example, it wasnot necessary.

8.5 Tying it all together

We now have all of the subsites. This section links all of the subsites together andadds some presentation. This can take a little bit of time, but some of the featuresin the WebSphere Studio make it very easy.

Creating the complete ABC Company Web site 389

8.5.1 Importing the subsitesFollow these steps to import all subsites into the ABC Company project:

1. In the Studio Workbench, select File->Open Project. Go to the\ABCCompany folder, and select the ABCCompany.wao file.

2. Click the Open button. You should see a project that looks similar to thedisplay in Figure 352.

Figure 352. Studio Workbench: ABC Company project before adding the subsites

3. The first stage for updating this project is to import the directories you havealready created. In the Studio Workbench, select the project folderABCCompany.

4. Select the menu Insert->Folder. In the Insert Folder dialog box, click the UseExisting tab.

5. Click the Browse button, and find the following subsites:

• \subsites\catalog• \subsites\generalCatalog• \subsites\newuser• \subsites\orderPurchase• \subsites\orderStatus• \subsites\ShoppingCart• \subsites\session

The Insert Folder dialog box should look like the example in Figure 353.

390 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 353. IStudio Workbench: Insert Folder dialog box

6. Do not add the Static subsite since it has already been added to theABCCompany project. Click the OK button.

8.5.2 Cleaning up subsitesWe now need to move some folders around inside the WebSphere Studio anddelete some folders. Follow these steps:

1. Select View->Relations, and click on viewAllCatalogItemsError.jsp. Youcan see that it has a relationship with master.css and\servlet\catalog\viewAllCatalogItemsDBBean.class.

2. Right-click on the master.css link, and select Edit Link.

You get an Edit Link dialog box that should show \theme\Master.css. Thismeans that the theme folder is referenced in the root structure and not insidethe catalog folder.

3. Go through all of the subsite folders, right-click on the theme folder, and selectDelete. You see the dialog box shown in Figure 354.

Figure 354. Delete file dialog box

4. Click the Yes button, and the theme folder is deleted.

5. You should now have only one theme folder in the entire ABCCompanyproject.

Repeat the above process and delete the _libraries folder also found in each ofthe subsite folders.

Creating the complete ABC Company Web site 391

8.5.3 Organizing the servlet foldersWe now need to move the servlet folders to their correct location. You may recallthat the servlet folder when published goes to a different location than the HTMLpages. Follow these steps:

1. In the Studio Workbench, click and expand the catalog folder. There shouldbe a folder called “servlet” inside.

2. Click and expand the servlet folder. There should be another “catalog” folder.This folder contains all of the servlets for the catalog subsite.

3. Click and drag the catalog folder down to the colored servlet folder as shownin Figure 355.

Figure 355. Studio Workbench: Dragging files in the ABC Company project

4. Right-click the servlet folder inside the catalog folder, and select Delete. Clickthe Yes button in the Warning dialog box.

5. Click on each of the .HTML and JSP files inside the catalog folder making surethat all the files have solid links to the files they reference.

Repeat this process for all the other folders that contain servlets.

8.5.4 Fixing broken referencesUntil now, we have not had any broken references to deal with. If, by somechance, you had broken links earlier in this section, we now explain how to fixthem. Here are the steps you need to follow:

1. In the Studio Workbench, expand the servlet folder, and then expand thecatalog folder.

2. Select View->Relations. Click on each of the files in this folder looking forbroken links. You should find that only the .servlet files have broken links asshown in Figure 356.

Drag this directory

To the servlet directory

392 Web Enabling AS/400 Applications with IBM WebSphere Studio

Figure 356. Viewing broken links for servlet files in the ABC Company project

3. Click on viewAllCatalogItems.servlet, and inspect the links. Make sure thisitem is not checked out.

4. In the Relations view, look at the first broken link. It should read\viewAllCatalogItemsResults.jsp. This is the file that will be called for the resultof the JSP. Right-click on the box with the ? (question mark), and select EditLink.

5. Inside the Edit Link dialog box, add \catalog. Click the Yes button. The fullpath should now read \catalog\viewAllCatalogItemsResults.jsp. If you get awarning box, click the Yes button.

6. The link should now be solid. Repeat the above process for all of the otherservlet configuration files listed inside the “catalog” servlet folder.

7. Modify all the other servlet configuration files. Repeat the above process but,instead of using \catalog at the start of the path, use the subsite name. Forexample, in the orderStatus folder, use \orderStatus.

There should be no pages left with broken relationships.

8.5.5 Adding registered user templatesWe now need to format our pages to have a common look and feel. This isachieved by using the dynamic templates that were created earlier in 8.3.2,“Registered user templates” on page 377. Follow these steps:

1. In the Studio Workbench, click on the catalog subsite.

2. Select Insert->File. From the Insert File dialog box, click ondynamicPageTemplate.jsp. Click OK.

Creating the complete ABC Company Web site 393

3. The dynamicPageTemplate.jsp will now be added to the catalog subsite.Double-click the dynamicPageTemplate.jsp file to check it out and open it inPage Designer.

4. Go back to the Studio Workbench, and double-clickviewAllCatalogItemsError.jsp to check it out and open it in Page Designer.

5. In Page Designer, while looking at viewAllCatalogItemsError.jsp, selectEdit->Select All.

6. Select Edit->Copy. Close this file. If you are asked whether you want to savethis page, click the No button.

7. After closing the previous page, you should now seedynamicPageTemplate.jsp. Click inside the middle right cell, and selectEdit->Paste. The top of the page should look like the display in Figure 357.

Figure 357. viewAllCatalogItemsError.jsp converted to dynamicPageTemplate.jsp

8. Save this file, and exit Page Designer.

9. Check in the checked out files in the Studio Workbench by right-clicking onthem and selecting Check In.

10.Take note of the file that we just copied the information out of and delete thatfile. Right-click on viewAllCatalogItemsError.jsp, and select Delete. Selectthe option to delete from disk, and click the OK button.

11.Right-click the dynamicPageTemplate.jsp, and select Rename. Change thisfile name to viewAllCatalogItemsError.jsp.

12.Looking at the relationship view in the Studio Workbench, you can see thatthis new page has taken the place of the old page. Unfortunately, this is a bit ofa clumsy technique, but it is the best way to use the wizards.

Repeat this process for every page in the ABCCompany project except for theStaticPages folder.

8.5.6 Restructuring directoriesNow that all the folders we are going to use have been put in to the project, wecan restructure the project to be more friendly.

394 Web Enabling AS/400 Applications with IBM WebSphere Studio

The default page on our Web server is index.html. We should make this fileavailable in the root of the file system. We also want the simple information pagesavailable in the root directory. This will be the directory where we do not have toworry about security so we will keep low security files together. Complete thesetasks:

1. In the Studio Workbench, go to the StaticPages folder, and select theIndex.html file.

2. Drag this file to the root ABCCompany folder.

3. Repeat the first two steps for all the other files in the StaticPages folder.

4. Right-click the StaticPages folder, and select Delete.

5. Click the Yes option in the Confirmation dialog box.

8.5.7 Login pageIf we look at our Login page, we see that it is missing all the items that were onthe Login page shown in 3.3.2, “Constructing the Logon page” on page 97. Wewill put these items back on this page so it fits the style of the current Web site.Follow this process:

1. Right-click the ABCCompany root directory, and select Insert->File. From theInsert File dialog box, select the ABCCompanyTemplate.html file, and nameit loginContent.html.

2. Double-click the loginContent.html file in the Studio Workbench. This checksthe file out and opens it in the Page Designer.

3. We are just interested in the login table on this page. Select the content of thebottom right cell, and select Edit->Copy.

4. Go to the Studio Workbench, and double-click the file login.html. This checksit out and opens it in Page Designer.

5. Click in the middle right cell, and select Edit->Paste. Your page should looklike the one in Figure 358 on page 396.

Creating the complete ABC Company Web site 395

Figure 358. Page Designer: ABC Company Login page

6. Save this file, and exit from Page Designer.

7. In the Studio Workbench, right-click on the login.html file, and select CheckIn.

8. Right-click on the loginContent.html file, and select Delete. Make sure theDelete from disk option is selected, and click OK.

9. After the Login page is complete, copy the page into loginError.html. Changethe loginError.html file to display an error message. If the login was invalid, theuser will be redirected to the loginError.html page, which functions exactly thesame as the Login page and also displays error message.

8.5.8 The Welcome Registered User pageThe final page that needs to be created is the Welcome Registered User page.We do not know where the user intends to go on the Web site so we need towelcome them as a registered user. Follow these steps:

1. In the Studio Workbench, right-click on the ABCCompany root directory, andselect Insert->File.

2. In the Insert File dialog box, select the template dyanmicPageTemplate.jsp.For the name, type loginIndex.jsp, and click the OK button.

3. In the Studio Workbench, double-click loginIndex.jsp. This checks out the fileand opens it in Page Designer.

4. Double-click in the middle right cell, and set the Horizontal Alignment toCenter. Then, click OK.

5. Press the Enter key twice, and then type Welcome.

6. Highlight the word Welcome, and select Format->Physical Emphasis->Font.

7. For the font size attribute, select +2. Click the OK button.

396 Web Enabling AS/400 Applications with IBM WebSphere Studio

8. Press the Enter key twice, and then type some text thanking the user forreturning to the Web site. Refer to Chapter 4, “Restoring the ABC CompanyWeb site sample project” on page 121, for an example.

9. Save this file, and exit Page Designer.

8.5.9 Linking the Login pageThis procedure allows the user to register and login. Follow these steps:

1. In the Studio Workbench, double-click the login.html file. This checks out thefile and opens it in Page Designer.

2. Double-click in the middle right cell in the form. You should get the FormAttribute dialog box. If you do not see this dialog box, click in the drop-downlist box next to the Tag caption, and select Form.

3. Type /servlet/login for the action parameter, and set the method to Post.Click OK.

4. Double-click in the top field next to the caption called user ID. In the Attributedialog box, type username for the Name. Click OK.

5. Double-click in the bottom field next to the caption called password. In theAttribute dialog box, type password. Click the OK button.

6. Save this file, and exit Page Designer.

8.5.10 Linking the Registered User pages togetherWe now have all the pages formatted for either the registered user area or thegeneral browsable area. We now need to link all the pages together. We use thisprocess:

1. In the Studio Workbench, double-click on the viewAllCatalogItemsInput.htmlfile. This checks out the file and opens it in Page Designer. The page shouldlook like the example in Figure 359.

Figure 359. Page Designer: viewAllCatalogItemsInput.html for initial parameters

Creating the complete ABC Company Web site 397

2. Double-click in the form area. Inside the Attribute dialog box, make sure thevalue in the drop-down list box next to the Tag caption is Form.

3. Make note of the action, which in this case is/servlet/catalog.viewAllCatalogItems.

4. There are no fields on this page. If there were, you would need to repeat steps1 through 3 to take down the field names. You now have all the informationyou need to call the catalog page.

5. Repeat this process on every input page. You will need this information later.Use Table 47 for a reference.

Table 47. Parameter actions for the input pages

We now use the above information to link the pages together. Once the pages arelinked together, we can remove the HTML pages or change the HTML pages tobecome JSPs.

Input page Parameters from page

viewByPriceCatalogItemsInput.html Action /servlet/catalog.viewByPriceCatalogItemsField minPriceField maxPrice

custinsertInput.html This information is not needed

cartselectInput.html Action /servlet/OrderPurchase.cartselectField cust

dltCartInput.html Action /servlet/OrderPurchase.dltCartField cust

lastorderInput.html Action /servlet/OrderPurchase.lastorderField cust

sbmorderInput.html Action /servlet/OrderPurchase.sbmorderField cust

sbmtorderInput.html Action /servlet/OrderPurchase.sbmtorderField cust

orderLineInput.html Action /servlet/orderStatus.orderLineField orderID

ordersInput.html Action /servlet/orderStatus.ordersField custID

deleteShoppingCartItemInput.html Action /servlet/ShoppingCart.deleteShoppingCartItemField custIDField productID

updateShoppingCartQuantitiesInput.html Action /servlet/ShoppingCart.updateShoppingCartQuantitiesField newQtyField custIDField productID

viewAllShoppingCartInput.html Action /servlet/ShoppingCart.viewAllShoppingCartField custID

viewShoppingCartItemInput.html Action /servlet/ShoppingCart.viewShoppingCartItemField custIDField productID

398 Web Enabling AS/400 Applications with IBM WebSphere Studio

On each page inside the registered user area, we have the following links:

• Shopping Cart• Catalog• Purchase• Order Status• Logout

We need to link these pages as follows:

1. In the Studio Workbench, double-click the loginIndex.jsp page. This checksthe file out and opens it in the Page Designer.

2. Provided you created these pages using dynamicTemplate.jsp, you shouldhave images down the side that have forms around them. Double-click theShopping Cart image.

3. In the Push Button Attribute dialog box, click in the drop-down list box next tothe tag caption, and select Form.

4. When someone clicks the Shopping Cart button, you need the result to be theequivalent of going through viewAllShoppingCartInput.html. Referring to Table47, select the action value, and type/servlet/ShoppingCart.viewAllShoppingCart for this forms action.

5. Set the method to Post.

6. If you look at Table 47 for the viewAllShoppingCartInput.html file, you see thatwe also need a custID field. Click on the Hidden Fields tab.

7. For the Name property, type custID.

8. For the value, select the Specify by property check box, and click theBrowse... button.

9. In the Bean Property Selection dialog box, expand custIDBean, and selectcustID. Click OK.

10.Click Add in the Attribute dialog box. Click OK.

11.You have now linked this page to the shopping cart servlet, which shows theshopping cart result page. When you have done this for all JSP pages, youcan delete your test page viewAllShoppingCartInput.html. Table 48 gives allthe parameters for the other buttons.

Table 48. Parameter actions for the remaining input pages

Link caption Form values

Catalog Replaces viewAllCatalogItemsInput.htmlAction /servlet/catalog.viewAllCatalogItems

Purchase Replaces cartselectInput.htmlAction /servlet/OrderPurchase.cartselectHidden Field cust

Order Status Replaces ordersInput.htmlAction /servlet/orderStatus.ordersHidden Field /servlet/orderStatus.orders

Logout Replaces Taken from custom servletAction /servlet/logout

Creating the complete ABC Company Web site 399

12.Repeat the previous steps across all JSP pages in the restricted area subsite.

8.5.11 Final touchesNow that we have linked together all Web site pages, we should have a smoothflow between all the pages. We now need to edit each page to give it that finallook. Go through each page and separate the tables from the header cell. Youcan indent some of the items if you want. It is worth putting a heading inside eachpage just at the top of the content cell so people know where they are.

If you come to any pages where the tables do not have meaningful headings, nowis the time to change them. If you feel that you should restructure some of thetables, then do that.

When you view each page in the Page Designer, you should also change thepage names to something more appropriate. You can do so by doing these steps:

1. In Page Designer, double-click the page. You should see the Attribute dialogbox. Select Document Properties from the drop-down list box next to the tagcaption.

2. For the document title, enter something that represents the page on which youare working. For example, if you are looking at viewAllCatalogItemsError.jsp,type the caption Error viewing all the catalog items.

8.5.12 Publishing the Web siteSet the publishing target to point to the final destination on the AS/400 system,and select Publish. The Web site should now be ready to operate on the AS/400system. Be sure to test the entire Web site and ensure that the final deliveredWeb site does exactly what is required. It may be worth having some people testthe Web site and submit their comments for review.

Refer to 4.3.1, “Publishing to the AS/400 system” on page 125, for detailedinstructions on publishing the ABC Company Web site to the AS/400 system.

8.6 Heading towards e-commerce

In this section, we cover initiatives and steps towards e-commerce. We discussthe methodology and steps to make your Web site e-commerce ready.

Unfortunately, before one can conduct commerce over the Internet, certain issuesneed to be addressed and precautionary measures taken. There are individuals,who, for whatever reason, try to jeopardize, destroy or damage company Websites, steal confidential information, and so forth. Security becomes first andforemost a concern. Security covers the aspects (not in any particular order)shown in Table 49.

400 Web Enabling AS/400 Applications with IBM WebSphere Studio

Table 49. Heading towards e-commerce: Security aspects

In-depth coverage of security topics is outside of the scope of this book. Instead,our goal is to force you to think about security aspects and direct you to theproper sources. However, we explain certain security concepts, such as, SSL,digital certificates, and certificate authorities on the conceptual level.

We also talk about the ABC Company Web site and suggest ideas and notes inregard to security. The scope of the book focuses on the WebSphere Studio setof tools and how they can be productively used to Web-enable an AS/400application. The ABC Company Web site is not a secure site as it exists.

Let us discuss different elements of the ABC Company Web site in connection tosecurity topics. We would use SSL for the New User creation and resulting pagesto protect users’ personal information along with a login ID and password theyenter. All the pages starting from the Login page (registered users area) would beunder SSL to protect user order and credit card information.

Web users are logged into the WEBUSRDB table, which contains their login IDsand passwords. We need to secure the WEBUSRDB table using OS/400 securitymechanisms to authorize only certain user profiles to have access to the table.

A user profile, which is used to connect to the AS/400 server for database accessand program calling from the WebSphere Application Server, should have

Security aspect Precautionary measures and methods

Securing data transmission from the client tothe server and vice versa; when transmittingconfidential information (credit card data,personal data, other)

Secure Socket Layers (SSL) to securetransmission data

Authentication and Digital certificates

Securing the AS/400 server responsible forthe enterprise databases and applications

Firewall

Demilitarized Zone (DMZ): Having twofirewalls:

• One firewall is responsible for filteringincoming traffic and protecting HTTPand application servers

• A second firewall protects enterpriseapplications and databases containingbusiness logic

Have only one user profile to connect to theAS/400 server from the WebSphereApplication Server

Securing the HTTP and WebSphereApplication Servers; responsible for the wellbeing of the Web site

Firewall or DMZ

Pay special attention to securing folderscontaining servlet configuration files, wherethe user ID, password, and AS/400 systemURLs are stored

Securing company private networks(intranets)

Firewall or DMZ

Securing business-to-business transactions Virtual Private Networks (VPNs), think ofthem as extensions of an Intranet

Creating the complete ABC Company Web site 401

adequate security privileges. The password for this user profile should bechanged regularly.

Information (user ID, pwd, URL) needed to access the AS/400 server services(database, program object calling) is not hardcoded in any of the code generatedby the wizards or by ourselves. It is stored in the *.servlet and *.sql files. Thefolders where these type of files are stored, should be secure.

Before conducting e-commerce transactions over the Internet, formal testingshould be performed to uncover potential security holes.

Additional informationFor additional information, check out these resources:

• Net.Commerce V3.2 for AS/400: A Case Study for Doing Business in the NewMillennium, SG24-5198

• Building AS/400 Internet-Based Applications with Java, SG24-5337

• Securing Your AS/400 from Harm on the Internet, SG24-4929

• HTTP Server for AS/400 Webmaster's Guide, GC41-5434

• The AS/400 Toolbox for Java is a library of Java classes that give easy accessto AS/400 data and resources. For more information and trial downloads, visitthe Web at: http://www.as400.ibm.com/toolbox

• Information and related links regarding Digital Certificate Management can befound at:http://publib.boulder.ibm.com/pubs/html/as400/ic2924/info/index.htm

At the site, click Internet->Digital certificate management

• For information, news, and related links about the WebSphere family ofproducts, visit the IBM WebSphere home page at:http://www.software.ibm.com/webservers/

• For news and information regarding IBM e-business security solutions, visitthe Web site at: http://www.ibm.com/security

• News and information regarding a host of IBM software products can beaccessed at: http://www.internet.ibm.com/commercepoint/registry/

• Visit the VeriSign home page at: http://www.verisign.com/products/

• Visit the RSA Security home page at: http://www.rsasecurity.com

8.7 Task summary and integration testing

Let us recall what has been accomplished in the process of Web-enabling AS/400applications. In this chapter, we performed the following tasks:

1. Identified the existing application to be Web-enabled.

2. Identified the user community:

• Existing users: Existing customers• New users: Will set themselves up as customers

3. Analyzed an existing call center application to conclude which portions of theapplication can be Web-enabled.

4. Made a strong distinction between business and presentation logic.

402 Web Enabling AS/400 Applications with IBM WebSphere Studio

5. Separated presentation and business logic, preserving all of the businesslogic on the AS/400 server: powerful, secure, stable, and reliable serverplatform.

6. Identified issues and assumptions to start designing functionality and flow forthe Web site.

7. Designed and developed user authentication and a security model.

• Web users do not need to have user profiles created on the AS/400 server.

• Web users will be authenticated based on the database table on theAS/400 server; application logic will handle security and authentication.

• Only one user profile is needed on the AS/400 server for the WebSphereApplication Server database connection manager to connect to the AS/400database.

8. Created the Web site’s map and navigational flow.

9. Designed a functional flow in conjunction with a navigational flow.

10.Designed and developed a session management function.

11.Divided the Web site into subsites to allow parallel development:

• Each subsite performs a critical and essential function.• Each subsite has only one entry point, self contained.

12.Unit tested the subsites.

13.Integrated the subsites into a complete Web site.

8.7.1 Integration testingIntegration testing is referred to as testing end to end. In Chapter 7, “ABCCompany Web site design and development” on page 157, in the process ofdevelopment, we performed unit tests on individual subsites. Integration testingusually consists of:

• Testing the navigational flow:

Testing all the links

• Testing the functionality:

– Testing all the buttons that call servlets

– Testing resulting and error pages against expected results

– Attempting to break the application by supplying erroneous data on theinput forms

Refer Chapter 4, “Restoring the ABC Company Web site sample project” on page121, to restore the complete Web site from the archive file and verify the Web sitefunctionality.

8.7.2 SummaryNoteworthy, we used WebSphere Studio Wizards, such as, SQL and DatabaseWizard to develop most of the functionality required. Studio Wizards generatedservlets, beans, JSPs, and HTML pages, which turned out to be more thanadequate. We did not have to write a single line of code to connect to thedatabase and issue SQL commands, such as, database selects, inserts, updates,deletes. In some cases, we had to modify wizard-generated SQL statement to

Creating the complete ABC Company Web site 403

issue more complex queries: finding the highest customer ID and finding the lastorder created for a particular customer. In these cases, we only had to modify theSQL statement inside the bean.

To present the information to the user, placing data elements on the page, werelied on the Database Wizard and Page Designer. These tools have the ability tovisually add a bean to your JSP and visually select any bean’s property, providedit has a getter method.

WebSphere Studio Wizards also present a great opportunity to learn servlets,beans, and JSPs. Servlets, generated by the Studio Wizards, could be modifiedto instantiate more than one database access bean and perform differentcalculations or data manipulations. We modified one of the servlets to get theshopping cart data, package it, and call the AS/400 application program passingorder data as parameters. Beans can be easily modified to add setter or gettermethods and to change an SQL statement if it is a database access bean.

We developed Java code inside VisualAge for Java and then imported the *.javafiles into WebSphere Studio. Studio integrates with VisualAge for Java 3.0. If youhave VisualAge for Java 3.0 installed, you can navigate between the twoproducts. WebSphere Studio allows you to choose different applications to editfiles of different type. If you have your favorite HTML editor, you can set theWebSphere Studio to invoke it for HTML files. However, Page Designer supportsHTML, JSP, servlet, and other tags.

We found WebSphere Studio importing capabilities to be very useful. Since wedivided the ABC Web site into subsites, subsites had to be integrated together ata later stage. We imported entire subsite folders into the main project.

The Find and Replace function within WebSphere Studio is very powerful. Whilein development, one may use different test libraries on the AS/400 server ordifferent folders on the PC. When ready to switch to production libraries, the Findand Replace function can search and modify all the files (.java, .servlet, .jsp,.html, and so forth) in the project. We recommend that you generate theWebSphere Studio archive prior to running Find and Replace because there is noUndo function.

Another useful feature of WebSphere Studio is the ability to set test or productionpublishing stages, with different targets. You can have both the test publishingstage and the production stage on the AS/400 system.

8.7.3 Known problemsThese are known problems that you may run into when developing the ABCCompany Web site sample project:

• Creating a new user with a duplicate login ID produces an abnormal Servererror page (see the custinsert.java servlet inside the performTask() method)instead of the regular error page custInsertError.jsp.

• When viewing the catalog multiple times, the message INVALID METHOD

appears, and forces you to click the OK button and then reload.

404 Web Enabling AS/400 Applications with IBM WebSphere Studio

Appendix A. Example programs

You can download the WebSphere Studio archive file (ABCCompany.war), theAS/400 programs, and the libraries that are used in this redbook from theInternet. The examples were developed using WebSphere Studio 3.0. Note thatOS/400 V4R4 or later is required. These components are available:

• AS/400 RPG code• AS/400 CL code• AS/400 databases• WebSphere Studio archive file

A.1 Downloading the files from the Internet

To use these files, download them to your personal computer from the InternetWeb site. See the file named Readme.pdf. It contains instructions for restoringthe AS/400 libraries, the WebSphere Studio archive file, and runtime notes.

The Web site address to access is: http://www.redbooks.ibm.com

In the left panel, click Additional Materials. Follow the instructions on the pagethat appears so you can access the list of available downloads. When thedownloads page appears, scroll down until you find SG245634, and select it.Then, download this file to your system.

A.2 ReadMe file

These example programs have not been subjected to any formal testing. Theyare provided “as is”. They should be used for reference only. Please refer to“Special notices” on page 407, for more information.

Disclaimer

Before attempting to restore the WebSphere Studio archive file(ABCCompany.war) and create the ABC Company Web site, you must followthe instructions on the ReadMe file. This file is packaged with theself-extracting SG245634.exe file.

ReadMe file

© Copyright IBM Corp. 2000 405

406 Web Enabling AS/400 Applications with IBM WebSphere Studio

Appendix B. Special notices

This publication is intended to help anyone who wants to use the IBM WebSphereStudio and the IBM WebSphere Application Server Standard Edition to bring thecontents of an existing AS/400 application to the Web. The information in thispublication is not intended as the specification of any programming interfacesthat are provided by the IBM WebSphere Studio or the IBM WebSphereApplication Server Standard Edition. See the PUBLICATIONS section of the IBMProgramming Announcement for more information about what publications areconsidered to be product documentation.

References in this publication to IBM products, programs or services do not implythat IBM intends to make these available in all countries in which IBM operates.Any reference to an IBM product, program, or service is not intended to state orimply that only IBM's product, program, or service may be used. Any functionallyequivalent program that does not infringe any of IBM's intellectual property rightsmay be used instead of the IBM product, program or service.

Information in this book was developed in conjunction with use of the equipmentspecified, and is limited in application to those specific hardware and softwareproducts and levels.

IBM may have patents or pending patent applications covering subject matter inthis document. The furnishing of this document does not give you any license tothese patents. You can send license inquiries, in writing, to the IBM Director ofLicensing, IBM Corporation, North Castle Drive, Armonk, NY 10504-1785.

Licensees of this program who wish to have information about it for the purposeof enabling: (i) the exchange of information between independently createdprograms and other programs (including this one) and (ii) the mutual use of theinformation which has been exchanged, should contact IBM Corporation, Dept.600A, Mail Drop 1329, Somers, NY 10589 USA.

Such information may be available, subject to appropriate terms and conditions,including in some cases, payment of a fee.

The information contained in this document has not been submitted to any formalIBM test and is distributed AS IS. The information about non-IBM ("vendor")products in this manual has been supplied by the vendor and IBM assumes noresponsibility for its accuracy or completeness. The use of this information or theimplementation of any of these techniques is a customer responsibility anddepends on the customer's ability to evaluate and integrate them into thecustomer's operational environment. While each item may have been reviewedby IBM for accuracy in a specific situation, there is no guarantee that the same orsimilar results will be obtained elsewhere. Customers attempting to adapt thesetechniques to their own environments do so at their own risk.

Any pointers in this publication to external Web sites are provided forconvenience only and do not in any manner serve as an endorsement of theseWeb sites.

Any performance data contained in this document was determined in a controlledenvironment, and therefore, the results that may be obtained in other operating

© Copyright IBM Corp. 2000 407

environments may vary significantly. Users of this document should verify theapplicable data for their specific environment.

Reference to PTF numbers that have not been released through the normaldistribution process does not imply general availability. The purpose of includingthese reference numbers is to alert IBM customers to specific information relativeto the implementation of the PTF when it becomes available to each customeraccording to the normal IBM PTF distribution process.

The following terms are trademarks of the International Business MachinesCorporation in the United States and/or other countries:

The following terms are trademarks of other companies:

Tivoli, Manage. Anything. Anywhere.,The Power To Manage., Anything.Anywhere.,TME, NetView, Cross-Site, Tivoli Ready, Tivoli Certified, Planet Tivoli,and Tivoli Enterprise are trademarks or registered trademarks of Tivoli SystemsInc., an IBM company, in the United States, other countries, or both. In Denmark,Tivoli is a trademark licensed from Kjøbenhavns Sommer - Tivoli A/S.

C-bus is a trademark of Corollary, Inc. in the United States and/or other countries.

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

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

PC Direct is a trademark of Ziff Communications Company in the United Statesand/or other countries and is used by IBM Corporation under license.

ActionMedia, LANDesk, MMX, Pentium and ProShare are trademarks of IntelCorporation in the United States and/or other countries.

AIX AS/400AT CICSCross-Site CTCurrent DB2Domino IBMLotus Manage. Anything. Anywhere.MQSeries NetfinityNetView OS/400Planet Tivoli RS/6000S/390 SPSystem/390 TivoliTivoli Certified Tivoli ReadyTME VisualAgeWebSphere WizardXT 400

408 Web Enabling AS/400 Applications with IBM WebSphere Studio

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

SET and the SET logo are trademarks owned by SET Secure ElectronicTransaction LLC.

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

Special notices 409

410 Web Enabling AS/400 Applications with IBM WebSphere Studio

Appendix C. Related publications

The publications listed in this section are considered particularly suitable for amore detailed discussion of the topics covered in this redbook.

C.1 IBM Redbooks publications

For information on ordering these ITSO publications see “How to get IBMRedbooks” on page 415.

• Building AS/400 Client/server Applications with Java, SG24-2152

• Securing Your AS/400 from Harm on the Internet, SG24-4929

• Net.Commerce V3.2 for AS/400: A Case Study for Doing Business in the NewMillennium, SG24-5198

• Building AS/400 Internet-Based Applications with Java, SG24-5337

• Developing an e-business Application for the IBM WebSphere ApplicationServer, SG24-5423

• WebSphere Application Servers: Standard and Advanced Editions,SG24-5460

• Building AS/400 Applications for IBM WebSphere Standard Edition 2.0,SG24-5635

C.2 IBM Redbooks collections

Redbooks are also available on the following CD-ROMs. Click the CD-ROMsbutton at http://www.redbooks.ibm.com/ for information about all the CD-ROMsoffered, updates and formats.

C.3 Other resources

These publications are also relevant as further information sources:

• HTTP Server for AS/400 Webmaster's Guide V4R4, GC41-5434

• ILE RPG for AS/400 Programmer's Guide, SC09-2507

• AS/400 Performance Capabilities Reference - Version 4, Release 4,SC41-0607

CD-ROM Title Collection KitNumber

System/390 Redbooks Collection SK2T-2177Networking and Systems Management Redbooks Collection SK2T-6022Transaction Processing and Data Management Redbooks Collection SK2T-8038Lotus Redbooks Collection SK2T-8039Tivoli Redbooks Collection SK2T-8044AS/400 Redbooks Collection SK2T-2849Netfinity Hardware and Software Redbooks Collection SK2T-8046RS/6000 Redbooks Collection (BkMgr Format) SK2T-8040RS/6000 Redbooks Collection (PDF Format) SK2T-8043Application Development Redbooks Collection SK2T-8037IBM Enterprise Storage and Systems Management Solutions SK3T-3694

© Copyright IBM Corp. 2000 411

This publication is available in soft copy only by visiting the Web site at:http://publib.boulder.ibm.com/pubs/html/

At the site, select AS/400 Online Library. Then, select the appropriatelanguage, and click GO!. Click V4R4, and then click Search or view all V4R4books. Finally, in the Find books with titles, names, or doc numberscontaining: field, enter the publication number, and click Find.

• OS/400 Work Management V4R4, SC41-5306

• Performance Tools V4R2, SC41-5340

• DB2 for AS/400 Database Programming, SC41-5701

• DB2 for AS/400 Distributed Database Programming, SC41-5702

• Cohn, Mike. Java Developer’s Reference. Sams.net Publishing, 1996 (ISBN:1-5752112-97).

• Cooper, Alan. About Face: The Essentials of User Interface Design. IDGBooks Worldwide, 1995 (ISBN: 1-5688432-24).

• Couthard, Phillip and Farr, George. Java for RPG Programmers. IBM Press,1998 (ISBN: 1-8896712-31).

• Englander, Robert. Developing JavaBeans. O'Reilly & Associates, 1997(ISBN: 1-5659228-91).

• Flanagan, David. Java in a Nutshell, 3rd Edition. O’Reilly & Associates, 1999(ISBN: 1-5659248-78).

• Fowler, Martin. UML Distilled: Applying the Standard Object ModelingLanguage. Addison-Wesley Publishing Co., 1997 (ISBN: 0-2013256-32).

• Gamma, Erich, et al. Design Patterns: Elements of Reusable Object-OrientedSoftware. Addison-Wesley Publishing Co., 1995 (ISBN: 0-2016336-12).

• Galitz, Wilbert O. User-Interface Screen Design. John Wiley & Sons, 1993(ISBN: 0-4715615-68).

• Hunter, Jason and Crawford, William. Java Servlet Programming. O’Reilley &Associates, 1998 (ISBN: 1-565923-91).

• Lemay, Laura. JAVA 1.1 Interactive Course. The Waite Group, 1997 (ISBN1-5716908-32).

• Mayhew, Deborah J. Principles and Guidelines in Software User InterfaceDesign, Prentice Hall, 1991 (ISBN: 0-1372192-96).

• Preece, Jenny. Human Computer Interaction. Addison-Wesley Publishing Co.,1994 (ISBN: 0-2016276-98).

• Taylor, David, Ph.D. Object Technology: A Manager’s Guide. Addison-WesleyPublishing Co., 1997 (ISBN: 0-2013099-47).

• Vanderburg, Glenn. Tricks of the Java Programming Gurus. Sams.netPublishing, 1996 (ISBN: 1-5752110-25).

The following publications are available only on the Web at:http://publib.boulder.ibm.com/pubs/html/as400/infocenter.html

• AS/400 Java Developer Kit for Java• AS/400 Toolbox for Java• Qshell Interpreter

412 Web Enabling AS/400 Applications with IBM WebSphere Studio

At the site, select V4R4 and the appropriate language, and click GO!. In thethe left window pane, click Java. Select the information topic you desire.

C.4 Referenced Web sites

These Web sites are also relevant as further information sources:

• For an online version of the JavaScript Guide, visit the Web site at:http://developer.netscape.com/docs/manuals/communicator/jsguide4/index.htm

• For an online version of the JavaScript Reference, visit the Web site at:http://developer.netscape.com/docs/manuals/communicator/jsref/index.htm

• Investigate IBM Special Needs Solutions to improve accessibility. It is locatedon the Web at: http://www.austin.ibm.com/sns/access.html

• The AS/400 Toolbox for Java is a library of Java classes that gives easyaccess to AS/400 data and resources. For more information and trialdownloads, visit the Web at: http://www.as400.ibm.com/toolbox

• Information and related links regarding Digital Certificate Management can befound at:http://publib.boulder.ibm.com/pubs/html/as400/ic2924/info/index.htm

At the site, click Internet->Digital certificate management

• For information, news, and related links about the WebSphere family ofproducts, visit the IBM WebSphere home page at:http://www.software.ibm.com/webservers/

• For news and information regarding IBM e-business security solutions, visitthe Web site at: http://www.ibm.com/security

• News and information regarding a host of IBM software products can beaccessed at: http://www.internet.ibm.com/commercepoint/registry/

• Visit the VeriSign home page at: http://www.verisign.com/products/doc.html

• Visit the RSA Security home page at: http://www.rsasecurity.com

• To find information about the WebSphere family of products, refer to the Website: http://www.software.ibm.com/websphere

• For the latest information on WebSphere on the AS/400 system, go to the Website at: http://www.as400.ibm.com/websphere

Related publications 413

414 Web Enabling AS/400 Applications with IBM WebSphere Studio

How to get IBM Redbooks

This section explains how both customers and IBM employees can find out about IBM Redbooks, redpieces, andCD-ROMs. A form for ordering books and CD-ROMs by fax or e-mail is also provided.

• Redbooks Web Site http://www.redbooks.ibm.com/

Search for, view, download, or order hardcopy/CD-ROM Redbooks from the Redbooks Web site. Also readredpieces and download additional materials (code samples or diskette/CD-ROM images) from this Redbookssite.

Redpieces are Redbooks in progress; not all Redbooks become redpieces and sometimes just a few chapters willbe published this way. The intent is to get the information out much quicker than the formal publishing processallows.

• E-mail Orders

Send orders by e-mail including information from the IBM Redbooks fax order form to:

• Telephone Orders

• Fax Orders

This information was current at the time of publication, but is continually subject to change. The latest informationmay be found at the Redbooks Web site.

In United StatesOutside North America

e-mail [email protected] information is in the “How to Order” section at this site:http://www.elink.ibmlink.ibm.com/pbl/pbl

United States (toll free)Canada (toll free)Outside North America

1-800-879-27551-800-IBM-4YOUCountry coordinator phone number is in the “How to Order” section atthis site:http://www.elink.ibmlink.ibm.com/pbl/pbl

United States (toll free)CanadaOutside North America

1-800-445-92691-403-267-4455Fax phone number is in the “How to Order” section at this site:http://www.elink.ibmlink.ibm.com/pbl/pbl

IBM employees may register for information on workshops, residencies, and Redbooks by accessing the IBMIntranet Web site at http://w3.itso.ibm.com/ and clicking the ITSO Mailing List button. Look in the Materialsrepository for workshops, presentations, papers, and Web pages developed and written by the ITSO technicalprofessionals; click the Additional Materials button. Employees may access MyNews at http://w3.ibm.com/ forredbook, residency, and workshop announcements.

IBM Intranet for Employees

© Copyright IBM Corp. 2000 415

IBM Redbooks fax order formPlease send me the following:

We accept American Express, Diners, Eurocard, Master Card, and Visa. Payment by credit card notavailable in all countries. Signature mandatory for credit card payment.

Title Order Number Quantity

First name Last name

Company

Address

City Postal code

Telephone number Telefax number VAT number

Invoice to customer number

Country

Credit card number

Credit card expiration date SignatureCard issued to

416 Web Enabling AS/400 Applications with IBM WebSphere Studio

Index

Symbols.class file 29.java file 29<BEAN> 28<INSERT> 28<REPEAT> 29

Numerics5769-AS1 85769-DG1 85769-JV1 85769-SS1 8

AABC Company 137ABC Company database 137ABC Company database tables 145ABC Company project files 123ABC Company sample project 16ABC Company Web site 361

assembling 382configuration 132design and development 157sample project 121

About Us page 388adding enhanced graphics

AnimatedGif Designer 88WebArt Designer 88

Advanced Edition 1analysis of AS/400 application 152animated images 94animated redbook file 112AnimatedGif Designer 88

registering 88applet

created from Applet Designer 112with nervous text 118

Applet Designer 112archive file 121AS/400 application to Web-enable 151AS/400 database 135AS/400 system for running ABC Company Web site 125AS/400 Toolbox for Java 20, 135AS/400 user profile 124

Bbanner buttons 91beans generated by DB Wizard 183broken references 392business logic 152

CCache Manager 3calling the AS/400 server program to submit the order 310

© Copyright IBM Corp. 2000

cascading style sheets 103catalog 154, 217, 220, 227

adding an item from 243displaying a single item 227displaying items by price range 225displaying items from 223

catalog pages 231linking 237testing 231

Catalog project 215catalog project 215Catalog subsite 215catalog subsite 215, 223changing quantities of items in the shopping cart 278changing user input to uppercase 204client side validation 203configuration 7

AS/400 Toolbox for Java 20other platforms 20WebSphere Application Server 7WebSphere Application Server for AS/400 9

CORBA 2creating an SQL INSERT statement 52creating images for all links 370creating publishing stages 45creating the Web pages for the Catalog subsite 223CSMTR table 174CSTMR input HTML form 192CSTMR insert 172CSTMR select 176

creating the servlet and DB access bean 176CSTMR table 168, 174, 185custID bean 159, 162, 381custInsert servlet 186, 189custInsertInput.html 212custInsertInput.html input form 192custInsertResult.jsp 196Customer Table Layout (CSTMR) 146customer transaction flow 139custSelectDBBean bean 185

Ddata tag 316data validation summary 214database table structure 145database terminology 148Database Wizard 30, 350

with orderLine.sql 352with orderStatus.sql 350

DB access bean 176, 299for ORDERS select 322for SHPCART delete 328for SHPCART select 295

default publishing server 45defining the default publishing server in a stage 45DELETE SQL for the SHPCART table 326deleting items 287

417

Demo Company Web site 50directives 16displaying items from the catalog 223Distributed Program Call (DPC) 311District Table Layout (Dstrct) 146document-level style sheets 103download files 121DPC (Distributed Program Call) 311DPC class 311

Ee-commerce 400editing the Shopping Cart Item Results JSP 278, 287enabling servlets 13Enterprise Edition 2Enterprise JavaBeans 1error handling on order submission 334example programs 405existing pages 365external style sheets 103

Ffield length 211file filter tool bar 26final resulting JSP 196finishing the servlet 160

Ggeneral catalog area 236getting parameters 159

Hhidden fields 276History page 389Host Order Entry application 343HTML 29HTML file 368HTML form 172HTML form, servlet, bean, and JSP 180HTML form, servlet, bean, JSP for CSTMR insert 172HTTP server 9, 16

configuration 18directives 16

IIBM HTTP Server for AS/400 7IBM WebSphere family 1IBM XML parser 317identifying issues and assumptions 151importing an existing Web site 29inline style sheets 103input data validation 203INSERT SQL 168, 178

for the CSTMR table 168for WEBUSRDB table 178

installation 7considerations 7

IBM WebSphere Application Server (V4R4) 8other platforms 20software requirements 7Websphere Application Server (V4R3) 8

installing the download files 121installing WebSphere Application Server 7instantiating the custID bean 159integration testing 156, 402, 403Internet download files 405item quantities 285Item Table Layout (ITEM) 148

JJava code 301Java code for packaging and submitting an order to theAS/400 server 301Java files 185JavaBean Wizard 82JavaBeans 28JavaBeans with Page Designer 106JavaScript Guide 204JavaScript Reference 204JavaServer Pages (JSP) 1, 28, 299JSP (JavaServer Pages) 1, 28, 299JSP cartSelectResult.jsp 297jvm.properties file 14

Kknown problems 404

Llast order record retrieval 325link filter tool bar 26link filters 27link types 27linking the Catalog pages 237links on the static pages 384login 153, 158login and session management 158Login page 395

linking 397login servlet 158, 381login servlet flow 158logo buttons 91Logon page 97Logout page 389

Mmain tool bar 26mandatory entries 207menu bar 26merging input pages 238merging the two input pages 238

Nnervous text on the applet 118Net Objects ScriptBuilder 3.0 119

418 Web Enabling AS/400 Applications with IBM WebSphere Studio

new customer ID 185, 189new customer ID in the CSTMR table 185new customer ID in WEBUSRDB table 189new user creation summary and final testing 215new user input 204new user subsite 157, 164new users 154

development on the AS/400 server 164development using WebSphere Studio tools 166

new users subsite 164normal page templates 374normal user templates 374

Oorder class 308order confirmation 320, 330order data, retrieving from the bean 304Order Entry application 137, 151

changing the host 343database layout 145processing the submitted order 343

Order files 305order line 356Order Line Table Layout (ORDLIN) 147order object 308order packaging 329order purchase 155order purchase project 292order purchase subsite 157, 291, 336

final testing 342order status 155, 356Order Status pages

testing 354order status project 346order status subsite 346

testing 358order submission 330, 333Order Table Layout (ORDERS) 147order total on the confirmation page 331OrderDetail 304OrderDetail files 305orderLine.sql with Database Wizard 352ORDERS select 322orderStatus.sql with Database Wizard 350

Ppackage order objects 306packaging the WebSphere Studio application 130Page Designer 88Page Designer with JavaBeans 106page template 102Panel Definition Markup Language (PDML) 314password 159PCML

architecture 315classes 314conclusion 319

PCML (Program Call Markup Language) 314, 315PCML classes 314

PCML file 316PDML (Panel Definition Markup Language) 314PICS filtering platform 3presentation logic 152previewing the demo company Web site 50previewing Web sites 130price range 217, 225primary users of the Web application 151Program Call Markup Language (PCML) 314, 315program tag 316project archive file 122publishing stages 44publishing target 47publishing the Web site 44, 400publishing to the AS/400 system 46, 125

QQTMHHTTP user profile 7

RReadMe file 405redirecting users 159Registered User pages

linking 397registered user templates 374, 377, 393required fields 207restructuring directories 394resulting JSP 202Rollover button on the applet 116RPG Order Entry application 137

application flow 138customer transaction 138database table structure 145

RPG order entry applicationcomponents 138customer transaction flow 139database 137starting the application 139

SsbmOrder servlet 306SELECT SQL 174, 293

for CSMTR table 174for the ORDERS table 320for the SHPCART table 293

selectcartInput.html 337selectcartResults.jsp 338server side validation 203servlet 28, 82, 160, 176, 299Servlet access bean 176servlet alias 132servlet and DB access bean for CSTMR select 176servlet folders 392servlet for ORDERS select 322servlet for SHPCART delete 328servlet for SHPCART select query 295servlet with the SQL DELETE statement 77servlet with the SQL INSERT statement 56

419

servlet with the SQL SELECT statement 39servlet with the SQL UPDATE statement 66servlets generated by DB Wizard 183session 159session management 153, 158session management servlet 162, 381setting up AS/400 system to run ABC Company Web site125setting up publishing stages 44SGML (Standard Generalized Markup Language) 314shop cart deletion 333shopping cart 155, 221, 229, 248, 250, 252

changing quantities of items 278deleting a singe item 252deleting items 287displaying a single item 256displaying all items 254displaying items 229displaying updated item 258retrieving a single item 264retrieving all items 263selecting a single item 248testing for changing item quantity 285testing for deleted items 290unit test contents retrieval 297updaing an item quantity 265verifying a deleted item 260, 266

shopping cart bean to display item totals 267Shopping Cart Item Results JSP, editing 278, 287Shopping Cart page, testing 277shopping cart pages

linking 271testing 262

shopping cart project 246Shopping Cart Results page 268shopping cart selection, modifying the resulting page 297shopping cart subsite 246, 254

SQL queries 247SHPCART select 295SHPCART table 293soft coding the parameters 132specifying field length 211SQL DELETE statement 73, 77SQL INSERT statement 52SQL queries 215, 247SQL queries for the order status subsite 346SQL queries in the Database Wizard 350SQL SELECT statement 30, 39SQL UPDATE statement 62SQL Wizard 346SQL Wizard to check cusotmer orders 346SQL Wizard to view order line details 348Standard Edition 1Standard Generalized Markup Language (SGML) 314static HTML page content 365static HTML pages 153static pages 365status bar 26Stock Table Layout (Stock) 148struct tag 316

Studio Wizards generated result page 109Studio WorkBench 24Studio Workbench 24style sheets 103submission 329submitOrder() method 317submitted order 343submitting the order 310

creating the servlet, DB access bean, and JSPs 299subsite development 155subsites 157

cleaning up 391importing 390

Ttest resulting JSP 202testing shopping cart pages 262testing the catalog pages 231troubleshooting WebSphere Application Server 20

Uunit testing 155

customer insertion 188data validation functionality 213new Web user creation 195the shopping cart contents retrieval 297Web user insertion 192

username 159

VV4R3 to V4R4 upgrade considerations 9validating username and password 159validation functionality of custInsertInput.html 212viewAllCatalogItems.jsp page 238viewAllShoppingCartResults.jsp page 271visual cues 26VisualAge for Java 185VisualAge for Java 3.0 Professional Edition 120

WWeb enabling the Order Entry application 151Web pages 223, 254Web site

design 152publishing 400

Web site developmentcontent 363content negotiation 362design issues 361design objectives 361evaluating the Web site 364form and content 363images 363information architecture 361interface design 361issues 361linking 362multimedia 364

420 Web Enabling AS/400 Applications with IBM WebSphere Studio

pitfalls 361production 363production issues 363publicizing 364testing 364view on paper 363

Web site division into subsites 153Web site functionality 153Web site template file 367Web user profile 164WebArt Designer 88

registering 90WebSphere Application Server 1, 9

Administration support 20Advanced Edition 1configuration 7Enterprise Edition 2Group PTFs 8JDK support 8Standard Edition 1

WebSphere Application Server Administration 20Websphere Application Server for AS/400 7WebSphere Performance Pack 3WebSphere Site Analyzer 4WebSphere Studio 2

inserting Order and OrderDetail files 305WebSphere Studio application, packaging 130WebSphere Studio project 121WebSphere Studio servlet template 158WebSphere Studio tools 23

minimum hardware requirements 24minimum software requirements 24

WebSphere Studio Wizards examples 52WEBUSRDB input HTML form 192WEBUSRDB physical file 165WEBUSRDB table 178, 189Welcome page 387Welcome Registered User page 396working with existing pages 365working with style sheets 103

XXML (eXtensible Markup Language) 314

421

422 Web Enabling AS/400 Applications with IBM WebSphere Studio

© Copyright IBM Corp. 2000 423

IBM Redbooks review

Your feedback is valued by the Redbook authors. In particular we are interested in situations where a Redbook"made the difference" in a task or problem you encountered. Using one of the following methods, please review theRedbook, addressing value, subject matter, structure, depth and quality as appropriate.

• Use the online Contact us review redbook form found at http://www.redbooks.ibm.com/• Fax this form to: USA International Access Code + 1 914 432 8264• Send your comments in an Internet note to [email protected]

Document NumberRedbook Title

SG24-5634-00Web Enabling AS/400 Applications with IBM WebSphere Studio

Review

What other subjects would youlike to see IBM Redbooksaddress?

Please rate your overallsatisfaction:

O Very Good O Good O Average O Poor

Please identify yourself asbelonging to one of the followinggroups:

O CustomerO Business PartnerO Solution DeveloperO IBM, Lotus or Tivoli EmployeeO None of the above

Your email address:The data you provide here may beused to provide you with informationfrom IBM or our business partnersabout our products, services oractivities.

O Please do not use the information collected here for future marketing orpromotional contacts or other communications beyond the scope of thistransaction.

Questions about IBM’s privacypolicy?

The following link explains how we protect your personal information.http://www.ibm.com/privacy/yourprivacy/

SG24-5634-00

Printed in the U.S.A.

Web

Enabling

AS/400

Applications

with

IBM

WebSphere

StudioSG

24-5634-00

®