Sams Teach Yourself JavaServer Pages in 24 Hours 0672320231, 9780672320231, 9780768657401

Sams Teach Yourself JavaServer Pages in 24 Hours guarantees to teach 24 one-hour lessons on JSP and its ties to other J2

510 100 4MB

English Pages 456 [452] Year 2000

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Sams Teach Yourself JavaServer Pages in 24 Hours 
 0672320231, 9780672320231, 9780768657401

Citation preview

Jose Annunziato Stephanie Fesler Kaminaris

Teach Yourself ™

JavaServer Pages

in

24 Hours

800East 96th St., Indianapolis, Indiana, 46240

Sams Teach Yourself JavaServer Pages™ in 24 Hours

ASSOCIATE PUBLISHER

Copyright © 2001 by Sams Publishing

Steve Anglin Heather Goodell

All rights reserved. No part of this book shall be reproduced, stored in a retrieval system, or transmitted by any means, electronic, mechanical, photocopying, recording, or otherwise, without written permission from the publisher. No patent liability is assumed with respect to the use of the information contained herein. Although every precaution has been taken in the preparation of this book, the publisher and authors assume no responsibility for errors or omissions. Nor is any liability assumed for damages resulting from the use of the information contained herein. International Standard Book Number: 0-672-32023-1 Library of Congress Catalog Card Number: 00-104401 Printed in the United States of America First Printing: November 2000 03

02

01

00

4

3

2

Michael Stephens

ACQUISITIONS EDITORS

DEVELOPMENT EDITOR Heather Goodell

MANAGING EDITOR Matt Purcell

PROJECT EDITOR George E. Nedeff

COPY EDITOR Maryann Steinhart

INDEXER Sandy Henselmeier

PROOFREADER 1

Trademarks All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. Sams Publishing cannot attest to the accuracy of this information. Use of a term in this book should not be regarded as affecting the validity of any trademark or service mark.

Candice Hightower

TECHNICAL EDITORS Alexandre Pereira Calsavara Venkat S.R. Krishna Chaganti Al Saganich

TEAM COORDINATOR Pamalee Nelson

JavaServer Pages and JSP are registered trademarks of Sun Microsystems.

Warning and Disclaimer Every effort has been made to make this book as complete and as accurate as possible, but no warranty or fitness is implied. The information provided is on an “as is” basis. The authors and the publisher shall have neither liability nor responsibility to any person or entity with respect to any loss or damages arising from the information contained in this book or from the use of the CD-ROM or programs accompanying it.

MEDIA DEVELOPER Matt Bates

INTERIOR DESIGNER Gary Adair

COVER DESIGNER Aren Howell

PRODUCTION Lizbeth Patterson

Contents at a Glance Introduction

PART I Overview Hour 1

Introduction to Web Applications

1

3 5

2

Building Your First JSP

23

3

Introduction to Servlets

35

4

Configuring Application Servers

47

PART II Building Simple JSPs Hour 5

57

Understanding the JSP Application Models

59

6

Understanding the Layout of a JSP

71

7

Declaring Variables and Methods in a JSP

8

Inserting Java Expressions in a JSP

9

85 101

Controlling JSPs with Java Scriptlets

111

10

Processing Requests from the User

129

11

Generating a Dynamic Response for the User

145

PART III Adding Functionality to Your JSPs Hour 12

159

Keeping Track of the User Session

161

13

Configuring and Initializing JSPs

177

14

Creating Error Pages

187

15

Inserting Applets into Your JSPs

205

16

Using JavaBeans in a JSP

221

17

Accessing a Database from a JSP

239

18

Substituting Text in a JSP

255

19

Extending JSP Functionality with Tag Libraries

267

20

Using Multiple JSPs to Handle the Request

283

PART IV Creating an Enterprise Application Hour 21

305

Designing an Enterprise Application

307

22

Creating a Presentation Layer

317

23

Programming the Business Logic

339

24

Packaging and Deploying an Enterprise Application

359

Answers

383

Index

397

Appendix A

Contents Introduction

PART I Overview HOUR 1 Introduction to Web Applications

1

3 5

What Are JavaServer Pages (JSPs)? ......................................................................6 Evolution of the Web ..............................................................................................8 The Static Web ..................................................................................................8 The Plug-In Web ................................................................................................9 The Dynamic Web ..........................................................................................12 The N-Tier Web ..............................................................................................15 What Is the Java 2 Enterprise Edition (J2EE) Platform? ....................................16 Who Developed This Specification? ..............................................................16 What Does the Specification Define? ............................................................17 Who Benefits from This Specification? ..........................................................17 What Technologies Make Up This Platform? ................................................17 What Are Application Servers? ............................................................................19 The Need for an Application Server ..............................................................19 What Does It Mean to Be Compliant with the J2EE? ....................................19 A Listing of Application Server Vendors ........................................................19 Summary ..............................................................................................................20 Q&A ......................................................................................................................21 Workshop ..............................................................................................................21 Quiz ................................................................................................................21 Activities ..........................................................................................................22 HOUR 2 Building Your First JSP

23

A Review of HTML ..............................................................................................23 Comparing JSPs and CGI Programs ....................................................................24 Comparing JSPs and ASPs ..................................................................................25 Creating Your First JSP ........................................................................................27 Setting Up Apache’s Tomcat ..........................................................................27 Type the JSP into a Text Editor ......................................................................31 Save with a .jsp Extension ............................................................................32 View the Page in a Browser ............................................................................32 Summary ..............................................................................................................33 Q&A ......................................................................................................................33 Workshop ..............................................................................................................34 Quiz ................................................................................................................34 Activity ............................................................................................................34

vi

Sams Teach Yourself JavaServer Pages in 24 Hours

HOUR 3 Introduction to Servlets

35

What Is a Servlet? ................................................................................................35 How JSPs Become Servlets ..................................................................................36 The JSP/Servlet Lifecycle ..............................................................................36 The JSP Translation Process ..........................................................................37 The Basic Structure of an HttpServlet ..............................................................38 The init(...) Method ..................................................................................38 The service(...) Method ..............................................................................39 The doPost(...) and doGet(...) Methods ..................................................39 Translating a Simple JSP into a Servlet ..............................................................41 Writing a Simple JSP ......................................................................................41 Summary ..............................................................................................................44 Q&A ......................................................................................................................45 Workshop ..............................................................................................................45 Quiz ................................................................................................................45 Activity ............................................................................................................45 HOUR 4 Configuring Application Servers

47

How to Configure BEA WebLogic Server ..........................................................47 Installing BEA WebLogic Server ....................................................................48 The WebLogic Server Directory Structure ......................................................49 The weblogic.properties File ......................................................................50 Registering the JSPServlet ............................................................................52 Setting the Initial Arguments for the JSPServlet ..........................................52 Deploying a JSP on WLS ....................................................................................53 Summary ..............................................................................................................55 Q&A ......................................................................................................................55 Workshop ..............................................................................................................55 Quiz ................................................................................................................55 Activity ............................................................................................................56

PART II Building Simple JSPs HOUR 5 Understanding the JSP Application Models

57 59

What Are Application Models? ............................................................................59 The Simple Model ................................................................................................60 The N-Tier Model ................................................................................................62 The Loosely Coupled Model ................................................................................63 The Including Requests Model ............................................................................64 The Forwarding Requests Model ........................................................................66 Summary ..............................................................................................................70 Q&A ......................................................................................................................70 Workshop ..............................................................................................................70 Quiz ................................................................................................................70 Activity ............................................................................................................70

Contents

HOUR 6 Understanding the Layout of a JSP

vii

71

Using Tags and Attribute Values ..........................................................................71 Understanding Single and Paired Tags ............................................................72 Configuring Tags with Attributes ....................................................................72 Adding Comments to the Code ............................................................................73 Adding HTML Comments ..............................................................................73 Adding JSP Comments ....................................................................................73 Adding Java Comments ..................................................................................73 Dissecting a JSP ....................................................................................................74 Writing HTML Code ......................................................................................75 Understanding JSP Tag Elements ....................................................................75 Using the JSP Built-in Objects ............................................................................79 Understanding the request Object ..................................................................79 Understanding the response Object ................................................................79 Understanding the session Object ..................................................................80 Understanding the config Object ..................................................................80 An Overview of the Other JSP Built-in Objects ............................................80 Understanding JSPs and JavaBeans ......................................................................80 The Motivation Behind JavaBeans ..................................................................81 The JavaBean Specification ............................................................................81 Instantiating a JavaBean ..................................................................................81 Using the set and get Property Tags ..............................................................82 A Quick Example of Using JavaBeans ..........................................................82 Summary ..............................................................................................................82 Q&A ......................................................................................................................83 Workshop ..............................................................................................................83 Quiz ................................................................................................................83 Activity ............................................................................................................83 HOUR 7 Declaring Variables and Methods in a JSP

85

Using the Declaration Tags ..................................................................................86 Declaring Variables in a JSP ................................................................................86 Understanding Data Types ..............................................................................87 Initializing Variables ........................................................................................89 Declaring Arrays and Collections ..................................................................90 Declaring Methods in a JSP ................................................................................93 Invoking Methods ............................................................................................94 Understanding Method Overloading ..............................................................97 Summary ..............................................................................................................98 Q&A ......................................................................................................................99 Workshop ............................................................................................................100 Quiz ..............................................................................................................100 Activities ........................................................................................................100

viii

Sams Teach Yourself JavaServer Pages in 24 Hours

HOUR 8 Inserting Java Expressions in a JSP

101

The JSP Expression Tags ....................................................................................102 Referencing a Variable from an Expression ......................................................102 Overriding the toString( ) Method ................................................................104 Calling Methods from an Expression ................................................................106 Calling a Local Method ................................................................................106 Calling a Method of an Object ......................................................................107 Summary ............................................................................................................109 Q&A ....................................................................................................................109 Workshop ............................................................................................................110 Quiz ..............................................................................................................110 Activity ..........................................................................................................110 HOUR 9 Controlling JSPs with Java Scriptlets

111

Scriptlets ............................................................................................................112 Selection Control Structures ..............................................................................112 Using if Selection Statements ......................................................................112 Using switch Statements ..............................................................................115 Using the break Statement ............................................................................117 Iteration Control Structures ................................................................................118 Using for Loops ............................................................................................118 Using while Loops ........................................................................................121 Using the continue Statement ......................................................................123 Using do/while Loops ........................................................................................124 Summary ............................................................................................................127 Workshop ............................................................................................................127 Quiz ..............................................................................................................127 Activity ..........................................................................................................127 HOUR 10 Processing Requests from the User

129

Understanding User Requests ............................................................................130 Creating User Requests ......................................................................................131 The Anatomy of a URL ................................................................................131 Generating Requests with a Hyperlink ........................................................132 Extracting Path and URL Information ..............................................................133 Extracting Host and Port Information ................................................................134 Parsing Parameters in the Query String ............................................................136 Using HTML Forms ..........................................................................................137 An HTML Form and JSP That Process Credit Card Information ......................140 Summary ............................................................................................................143 Q&A ....................................................................................................................143 Workshop ............................................................................................................143 Quiz ..............................................................................................................144 Activity ..........................................................................................................144

Contents

HOUR 11 Generating a Dynamic Response for the User

ix

145

Generating Dynamic Content ............................................................................145 Dynamic Titles ..............................................................................................146 Dynamic Tables ............................................................................................147 Dynamic Forms ............................................................................................149 A Configurable Home Page ................................................................................152 Summary ............................................................................................................156 Q&A ....................................................................................................................156 Workshop ............................................................................................................156 Quiz ..............................................................................................................156 Activity ..........................................................................................................157

PART III Adding Functionality to Your JSPs HOUR 12 Keeping Track of the User Session

159 161

HTTP Is a Stateless Protocol ..............................................................................162 Storing and Retrieving Cookies ..........................................................................163 User Sessions ......................................................................................................166 Encoding URLs ..................................................................................................172 Summary ............................................................................................................174 Q&A ....................................................................................................................174 Workshop ............................................................................................................175 Quiz ..............................................................................................................175 Activities ........................................................................................................175 HOUR 13 Configuring and Initializing JSPs

177

Understanding the Registration and Initialization of JSPs ................................177 A Simple JSP that Prints All Initialization Parameters ......................................178 Compiling JSPs Into Servlets ............................................................................179 Registering and Initializing JSPs with the Application Server ..........................181 Using the config Object ....................................................................................182 A Simple Example: A Configured Login Page ..................................................183 The ServletContext Object ..............................................................................184 Summary ............................................................................................................185 Q&A ....................................................................................................................185 Workshop ............................................................................................................186 Quiz ..............................................................................................................186 Activity ..........................................................................................................186 HOUR 14 Creating Error Pages

187

Understanding Errors ..........................................................................................187 The Exception and Throwable Classes ........................................................188 Understanding the Stack Trace ......................................................................190 Catching Exceptions ......................................................................................190

x

Sams Teach Yourself JavaServer Pages in 24 Hours

Processing Exceptions ........................................................................................191 Creating Custom Exceptions ........................................................................191 Raising Exceptions in a JSP ..........................................................................192 Catching Exceptions in a JSP ........................................................................194 Raising Exceptions in a Java Class and Catching Them in a JSP ................196 Implementing Error Pages ..................................................................................198 Determining the Error Page ..........................................................................198 The exception Implicit Object ....................................................................200 Summary ............................................................................................................202 Q&A ....................................................................................................................203 Workshop ............................................................................................................203 Quiz ..............................................................................................................203 Activity ..........................................................................................................203 HOUR 15 Inserting Applets into Your JSPs

205

The General Syntax of a JSP Action Tag ..........................................................206 Using the plugin Action to Insert an Applet ......................................................206 Defining Initial Parameters for the Applet with the param Tags ........................211 Utilizing All Parts of the plugin Action ............................................................214 Summary ............................................................................................................220 Q&A ....................................................................................................................220 Workshop ............................................................................................................220 Quiz ..............................................................................................................220 Activity ..........................................................................................................220 HOUR 16 Using JavaBeans in a JSP

221

Understanding JavaBeans ..................................................................................222 Employee JavaBean: A Simple Example ............................................................223 Understanding JavaBean Scope ..........................................................................226 Implementing a Shopping Cart with JavaBeans ..........................................227 Setting and Getting JavaBean Properties ............................................................232 Using Forms with JavaBeans ..............................................................................234 Summary ............................................................................................................236 Q&A ....................................................................................................................236 Workshop ............................................................................................................237 Quiz ..............................................................................................................237 Activity ..........................................................................................................237 HOUR 17 Accessing a Database from a JSP

239

Creating a Database ............................................................................................240 Using Cloudscape’s Cloudview ....................................................................240 Creating Tables ..............................................................................................241 Creating Records ..........................................................................................243 Java Database Connectivity (JDBC) ..................................................................244 JDBC Drivers ................................................................................................245

Contents

xi

Getting a Connection to the Database ..........................................................247 Interacting with the Database with the Statement Object ............................248 Navigating Query Results with the ResultSet Object ..................................248 A JSP that Interacts with a Database ..................................................................249 Printing the Contents of a Database with a JSP ............................................249 Updating a Database with a JSP ..................................................................251 Summary ............................................................................................................252 Q&A ....................................................................................................................253 Workshop ............................................................................................................254 Quiz ..............................................................................................................254 Activity ..........................................................................................................254 HOUR 18 Substituting Text in a JSP

255

Understanding the include Directive ................................................................256 Using the include Directive ........................................................................256 Examples of the include Directive ....................................................................257 Including a Text Document ..........................................................................257 Including Another JSP ..................................................................................260 File to Include Is Missing ..............................................................................262 Summary ............................................................................................................264 Q&A ....................................................................................................................265 Workshop ............................................................................................................265 Quiz ..............................................................................................................265 Activity ..........................................................................................................265 HOUR 19 Extending JSP Functionality with Tag Libraries

267

Understanding a Tag Library ..............................................................................268 The taglib Directive ....................................................................................269 Examples of Using Tag Libraries ......................................................................270 Using a Custom Action to Track Page Hits ..................................................270 Listing Elements of a session Object ..........................................................273 Using a Custom Action Tag with Attributes ................................................276 Summary ............................................................................................................280 Q&A ....................................................................................................................280 Workshop ............................................................................................................280 Quiz ..............................................................................................................281 Activity ..........................................................................................................281 HOUR 20 Using Multiple JSPs to Handle the Request

283

Reviewing the Including Requests Application Model ......................................284 A Review of JSP Actions ....................................................................................284 Using the include Action ..............................................................................285 Understanding the Difference Between the include Action and the include Directive ......................................................................................................285

xii

Sams Teach Yourself JavaServer Pages in 24 Hours

Implementing the include Action ......................................................................285 Reviewing the Forwarding Requests Application Model ..................................293 Using the forward Action ..............................................................................293 Implementing the forward Action ......................................................................293 Summary ............................................................................................................302 Q&A ....................................................................................................................303 Workshop ............................................................................................................303 Quiz ..............................................................................................................303 Activity ..........................................................................................................303

PART IV Creating an Enterprise Application

305

HOUR 21 Designing an Enterprise Application

307

Gathering Design Requirements ........................................................................308 Designing the Application ..................................................................................312 Summary ............................................................................................................315 Q&A ....................................................................................................................315 Workshop ............................................................................................................315 Quiz ..............................................................................................................315 Activity ..........................................................................................................315 HOUR 22 Creating a Presentation Layer

317

Building the Application ....................................................................................317 Writing CompanyBanner.html ........................................................................318 Writing SiteNavigator.html ........................................................................319 Writing the Home Page ................................................................................321 Writing PresentCompanyHealthCareInfo.jsp ..............................................323 Writing the JSP to Present the Company’s Policies ....................................326 Allowing Employees to View Personal Benefits ..........................................329 Summary ............................................................................................................337 Q&A ....................................................................................................................337 Workshop ............................................................................................................337 Quiz ..............................................................................................................337 Activity ..........................................................................................................338 HOUR 23 Programming the Business Logic

339

Overview ............................................................................................................340 Adding New Employees Through the Husky World Human Resources Web Site ..........................................................................................................340 Writing Capabilities to Change Employee’s Information ..................................350 Summary ............................................................................................................357 Q&A ....................................................................................................................357 Workshop ............................................................................................................358 Quiz ..............................................................................................................358 Activity ..........................................................................................................358

Contents

HOUR 24 Packaging and Deploying an Enterprise Application

xiii

359

What Is a Web Archive File? ..............................................................................360 Setting Up the Directory Structure for the Web Archive ..................................361 Making Appropriate Changes to Your HTML and JSP Files ........................362 Creating the Deployment Descriptor ..................................................................376 Generating the .war File ....................................................................................379 Deploying the .war File ................................................................................380 Making Requests to Your Application ................................................................380 Summary ............................................................................................................381 Q&A ....................................................................................................................381 Workshop ............................................................................................................381 Quiz ..............................................................................................................381 Activity ..........................................................................................................381 APPENDIX A Answers Index

383 397

About the Authors JOSE ANNUNZIATO received his Master’s and Doctor of Science degrees in computer science from the University of Massachusetts Lowell. He taught at the university for several years while completing his doctorate. Although content in academia, he was lured into private industry, working on a range of Internet-related projects for several years. Dr. Annunziato has consulted for several companies working on many distributed systems projects for the Department of Defense. He then found a nice blend of academic rigorousness and private-industry challenges at BEA Systems, developing courseware for the industry’s leading application server products such as WebLogic Server, WebLogic Commerce Server, and WebLogic Enterprise. His other interests include 3D graphics animation, robotics, virtual reality, artificial intelligence, and classical piano. In his spare time he enjoys wrestling with his three children, and the company of his wife. STEPHANIE FESLER KAMINARIS has several years of experience in software development training. She has split her time between the classroom and writing course materials. In that time she has written hundreds of pages of course materials on Web development, such as HTML, JavaScript, Active Server Pages, VBScript, and CGI programming. She has also written course materials for BEA’s WebLogic Server courses, such as WebLogic as a Web Server, JavaServer Pages, Servlets, and Web Applications. In the classroom she has taught courses in software programming languages, including Java and C++, and Java Enterprise technologies such as EJBs, JSPs, Servlets, JNDI, JDBC, and much more. She also teaches courses on running BEA’s WebLogic Server and Administrating BEA’s WebLogic Server.

Dedications I would like to dedicate this book to my wife, Alexandra, who has been so caring, loving, and patient with me, and has brought us the joy of our three beautiful children, Katerina, Rafael, and Victoria. Thank you, this is for you. This book is also dedicated to the loving memory of my parents Pasquale and Emilia Annunziato. Thank you and I wish you were here. —Jose Annunziato There are many people who have helped me get to where I am today. I would like to thank my family and especially my mother and father for always supporting me and believing that I can do anything that I put my mind to. Thanks to my Grandma Fesler and Grandma Corneau for being proud of me and making me feel like I have wings to fly. I am also dedicating this book to my grandfather, John F. Fesler, who was truly a great man; it is an absolute honor when people compare me to him. Also thanks to my sister, Kristy: you have always been a great big sister and have always been there when I needed you. I would also like to mention my puppies, Mickey and Minnie, who have added so much joy and laughter to my life. Last, but definitely not least, I am dedicating this book to my husband, Chris. I love you more and more each day, thanks for loving me, believing in me, supporting me, and most importantly just being you. You are the sweetest man. —Stephanie Fesler Kaminaris

Acknowledgments Although not directly involved in the production of this book, I would like to thank Margarita Turcotte for helping our family through several ordeals. Also Dr. Charles Kosta for sponsoring and mentoring me while in school. Thank you to the staff at UMass Lowell for their support, especially Professor Charlie Steele, Professor William Moloney, Dr. Mariam Williams, and Dr. James Canning. Also thanks to Dr. Haim and Dr. Ethel Levkowitz for their insights, subjectivity, and guidance. It was a pleasure to work with my co-author Stephanie Fesler Kaminaris. I love the way she jumps at the occasion to help and volunteer in some of the most adverse scenarios. Good for you. I would like to thank the people at Sams Publishing, especially Heather Goodell, for doing a wonderful job at keeping everything on track. —Jose Annunziato It has been such a pleasure writing this book and having the opportunity to work with absolutely wonderful individuals. The book author is just one piece of the puzzle, but there are so many people working behind the scenes to make a book a success. So thanks to Heather Goodell, who kept the book on track and oversaw the development of the material. Thanks also Al Saganich, who tech edited the book and made sure that all code listings were in tip-top shape. Thanks also to all the other people at Sams Publishing who worked on this book to make it the way it is. —Stephanie Fesler Kaminaris

Tell Us What You Think! As the reader of this book, you are our most important critic and commentator. We value your opinion and want to know what we’re doing right, what we could do better, what areas you’d like to see us publish in, and any other words of wisdom you’re willing to pass our way. As an Associate Publisher for Sams Publishing, I welcome your comments. You can fax, email, or write me directly to let me know what you did or didn’t like about this book— as well as what we can do to make our books stronger. Please note that I cannot help you with technical problems related to the topic of this book, and that due to the high volume of mail I receive, I might not be able to reply to every message. When you write, please be sure to include this book’s title and authors as well as your name and phone or fax number. I will carefully review your comments and share them with the authors and editors who worked on the book. Fax: Email: Mail:

317-581-4770 [email protected]

Michael Stephens Associate Publisher Sams Publishing 201 West 103rd Street Indianapolis, IN 46290 USA

Introduction Welcome to Sams Teach Yourself JavaServer Pages in 24 Hours! You have decided that you want to learn how to write JavaServer Pages. Well, you have come to the right place. This book introduces you to the basics of JSPs, such as their structure, their application models, and how they can be used to create dynamic content on the Web. You also will learn about some advanced topics such as connecting to a database from within a JSP and using JavaBeans to access a database. Finally, you are going to write a Web application that models a human resources Web site for a company’s intranet. Sound like a lot? It is, and you will accomplish it all in 24 one-hour lessons. Good luck, work hard, and have fun.

Who Is This Book’s Intended Audience? This book is aimed at individuals who are familiar with HTML and Java. You do not need to be an expert in HTML, but you should be familiar with the common tags and be able to create a simple HTML document. Also, you do not need to be an expert Java programmer, although experience with programming in any language will help you work through the activities.

What You’ll Learn in the Next 24 Hours You will learn what JSPs are and how they fit into Sun Microsystems Java 2 Enterprise Edition Platform. You’ll also see how JSPs compare to other similar technologies such as CGI programs and Active Server Pages (ASPs). First, we’ll show you the basics of JSPs, such as the tags that allow you to embed Java in HTML pages and how to divide the work among several JSPs. This book also goes into advanced features such as connecting to a database from your JSP, using a JavaBean or server-side class, and extending the functionality of your JSPs using a custom tag library. You will complete the book with a project, writing a human resources Web site for a company’s intranet. There is a lot to do, so buckle up and enjoy the ride.

What You Need There are a few things you need before starting your journey. You need a text editor, such as Notepad in the Windows operating environment. You also need a Java Development Kit, JDK, from Sun Microsystems. The JDK can be downloaded from Sun’s Web site,

2

Sams Teach Yourself JavaServer Pages in 24 Hours

http://java.sun.com/products/jdk/1.2/index.html.

Under the Production Releases heading you can choose what platform to download for. The best JDK to select is version 1.2.2. It is very easy to download and install and should only take a few minutes. You will download a zip file, typically named jdk1_2_2-win.zip, that contains the necessary files. All you need to do to deploy is unzip it to your root directory, such as c:\.

Conventions Used in This Book This book uses different typefaces to differentiate between code and regular English, and also to help you identify important concepts. Therefore, code lines, commands, statements, variables, and any text you type or see onscreen appear in a computer typeface. Do not type any line numbers that appear at the beginning of lines in code listings! The line numbers are used to reference the lines of code during explanation of the listing. Placeholders for variables and expressions appear in a monospace italic font. You should replace the placeholder with the specific value it represents.

A Note presents interesting pieces of information related to the surrounding discussion.

A Tip offers advice or teaches an easier way to do something.

A Caution advises you about potential problems and helps you steer clear of disaster.

New Term: A New Term provides a clear definition of a new, or essential term.

PART I Overview Hour 1 Introduction to Web Applications 2 Building Your First JSP 3 Introduction to Servlets 4 Configuring Application Servers

HOUR

1

Introduction to Web Applications Our story begins with a young lady, Marian, who is interested in going to Florida for her upcoming vacation. Marian is Internet savvy, so she visited an airline’s Web site and entered in her destination, Florida. A list of flights to Florida was returned and displayed in an easy-to-read fashion in her browser. Her business partner, John, was also planning his upcoming vacation, but he wanted to go to Hawaii. Because he was Internet savvy as well, he went to the same airline’s Web site, entered in his destination, and received a listing of flights to Hawaii. How was it possible that they received such different information from the same Web site? The airline’s Web site has an application, called a Web application, that accepted their requests and generated a response pertaining to each particular query. Because the Web application created these documents on-the-fly, it is considered to return dynamic content. That means the response from these sites, such as flights to various parts of the country, are dynamically created when the particular query is entered.

6

Hour 1

New Term: Web Application A Web application is a program that runs on a Web server.

Marian and John found their flights and off on vacation they went. Our story about Marian and John has come to an end, but our adventure is just beginning. You are going to delve into Web structures and understand how Web applications can generate different responses to various queries. This book focuses on Sun Microsystems technology JavaServer Pages (JSP) to deliver dynamic content to Web clients. So, let the adventure begin. In this hour, you are going to understand • What JavaServer Pages are • The evolution of the Web • The reason the Java 2 Enterprise Edition (J2EE) platform was created • What application servers are

What Are JavaServer Pages (JSPs)? JavaServer Pages (JSPs) are a technology defined by Sun Microsystems to create dynamic content on the Web. They are HTML documents that are interleaved with Java, which provides the dynamic content. JSPs are a server-side application; they accept a request and generate a response. Generally the requests are made from a Web client, and the response is a generated HTML document that gets sent back to the Web client. Because JSPs are a server-side application, they have access to the resources on the server, such as Servlets, JavaBeans, EJBs, and databases. In Hour 5, “Understanding the JSP Application Models,” you will take a look at various design patterns that JSPs can implement, as defined in the Sun specification.

New Term: Web Client A Web client is a client that interacts with a Web server using the HTTP protocol. The client runs a Web browser, such as Internet Explorer or Netscape Navigator, and requests documents by specifying a URL in the browser.

There are many benefits to using JavaServer Pages. Because JSPs utilize the Java programming language, they follow the write-once, run-anywhere policy. This means that a JSP can be run on any application server that supports JSPs without any modifications to

Introduction to Web Applications

the code. (Application servers will be discussed in the section “What Are Application Servers?”) Another benefit of JSPs is that the specification is written in a way that promotes integration with integrated development environments (IDEs).

JSPs can be written in any text editor; just be sure to save the document with a .jsp extension. This means you can write JSPs in Notepad on a Windows operating system, or emacs on a UNIX operating system. An IDE that supports writing JSPs is Dreamweaver, which is part of the WebGain Studio.

Another benefit of JSPs is the use of tag libraries. JSPs use tags, which are similar to HTML and XML, to insert dynamic content. It is possible to add additional functionality to a JSP by importing a tag library. The tag library defines additional tags that can be used to replace sections of code. Another major benefit of JSPs is the separation of roles. The specification for JSPs allows for the workload to be separated into two categories: the graphical content of the page and the dynamic content of the page. The creative team that has no knowledge of the Java programming language can create the graphical content of the page. A Java programmer then inserts Java into the HTML document to achieve the dynamic content.

When writing a JSP, it is easier to write the HTML code and then insert the Java code to create your dynamic content. So, if you don’t plan to write the HTML, have your graphical artists work their magic to create a beautiful page and then insert your Java code to make the JSP dynamic.

Listing 1.1 is a simple JSP that shows how Java code is inserted into a JSP. All this JSP does is insert the current time and date into an HTML page (see Figure 1.1). Don’t worry if you don’t understand what the parts are right now—this book goes into great detail about generating JSPs. In Hour 2, “Building Your First JSP,” you are going to create and deploy your first JSP. LISTING 1.1 Document 1: 2: 3: 4: 5: 6:

A Simple JSP That Inserts the Current Time and Date into an HTML

A Simple JSP

The Current Date and Time is:

7

1

8

Hour 1

LISTING 1.1 7: 8: 9: 10:

continued



FIGURE 1.1 The simple JSP is viewed in a browser.

Evolution of the Web The technology of the Web has evolved enormously in the last few years. It was not so long ago that the Web consisted of only static documents. Now, programs are embedded in HTML and dynamic content can be added to the HTML documents at runtime. Take a look at the evolution of the Web.

The Static Web The Static Web is the simplest Web structure. Figure 1.2 shows a diagram of the Static Web. The Web client connects to the Web server using TCP/IP and makes requests using HTTP. The server sends an already-made HTML document to the Web client. This HTML document contains text, possibly hyperlinks, and the formatting tags. It does not contain any dynamic content, nor does it contain a way for the user to interact with it. Basically, in this structure HTML documents are stale and provide no interaction to the client.

Introduction to Web Applications

FIGURE 1.2 Dynamic content and user interaction are not part of the Static Web structure. Web Client This is an HTML document

Simple HTML

This is an HTML document

HTTP TCP/IP

9

1 Web Server

HTML files

Technologies: HTML

The Plug-In Web As technology evolved, people wanted more capabilities in their Web pages. The Plug-In Web, diagrammed in Figure 1.3, allowed users to add small programs to HTML documents. FIGURE 1.3 The Plug-In Web structure provides for small programs to be included. Web Client

Simple HTML