The javax.servlet Package

The javax.servlet Package

Table of

Content

Java for the Web with Servlets, JSP, and EJB: A Developer's Guide to

J2EE Solutions

By

Budi Kurniawan

Publisher : New Riders Publishing

Pub Date : April 12, 2002

ISBN : 0-7357-1195X

Pages : 976

Java for the Web with Servlets, JSP and EJB is the one book you need to master Java

web programming. It covers all the technologies needed to program web applications in Java using Servlets 2.3, JSP 1.2, EJB 2.0 and client-side programming with

JavaScript. These technologies are explained in the context of real-world projects, such as an e-commerce application, a document management program, file upload and programmable file download, and an XML-based online book project.

In addition to excellent content, this book includes licenses to two Java web components from BrainySoftware.com. You receive a full license of the

Programmable File Download component for commercial and non-commercial company Commerce One and purchased by major corporations such as Saudi

TE

AM

FL

Y

Team-Fly ®

Table of Content

Table of Content ........................................................................................................... ii

Copyright ...................................................................................................................... ix

Copyright © 2002 by New Riders Publishing...................................................... ix

Trademarks .............................................................................................................. ix

Warning and Disclaimer ......................................................................................... ix

About the Author ......................................................................................................... xi

About the Technical Reviewers ................................................................................ xi

Acknowledgments ....................................................................................................... xi

Tell Us What You Think............................................................................................. xii

Introduction.................................................................................................................. xii

The Hypertext Transfer Protocol (HTTP) .......................................................... xiv

System Architecture............................................................................................. xvii

Java 2, Enterprise Edition (J2EE)..................................................................... xviii

Developing Web Applications in Java.............................................................. xviii

Overview of Parts and Chapters......................................................................... xix

Part I: Building Java Web Applications......................................................................... 1

Chapter 1. The Servlet Technology .......................................................................... 2

The Benefits of Servlets .......................................................................................... 2

Servlet Application Architecture ............................................................................. 4

How a Servlet Works ............................................................................................... 5

The Tomcat Servlet Container ............................................................................... 5

Six Steps to Running Your First Servlet ............................................................... 6

Summary ................................................................................................................. 11

Chapter 2. Inside Servlets......................................................................................... 12

The javax.servlet Package.................................................................................... 12

A Servlet's Life Cycle............................................................................................. 13

Obtaining Configuration Information ................................................................... 16

Preserving the ServletConfig................................................................................ 18

The Servlet Context ............................................................................................... 19

Sharing Information Among Servlets .................................................................. 21

Requests and Responses..................................................................................... 23

The GenericServlet Wrapper Class .................................................................... 28

Creating Thread-Safe Servlets............................................................................. 29

Summary ................................................................................................................. 34

Chapter 3. Writing Servlet Applications .................................................................. 35

The HttpServlet Class............................................................................................ 35

The HttpServletRequest Interface ....................................................................... 39

HttpServletResponse............................................................................................. 48

Sending an Error Code.......................................................................................... 51

Sending Special Characters ................................................................................. 51

Buffering the Response......................................................................................... 55

Populating HTML Elements.................................................................................. 56

Request Dispatching.............................................................................................. 57

Summary ................................................................................................................. 65

Chapter 4. Accessing Databases with JDBC ........................................................ 67

The java.sql Package ............................................................................................ 67

ii

Four Steps to Getting to the Database ............................................................... 71

A Database-Based Login Servlet......................................................................... 79

The Single Quote Factor ....................................................................................... 84

Inserting Data into a Table with RegistrationServlet ........................................ 86

Displaying All Records........................................................................................... 96

Search Page ........................................................................................................... 98

An Online SQL Tool ............................................................................................. 102

Should I Keep the Connection Open? .............................................................. 108

Transactions.......................................................................................................... 109

Connection Pooling.............................................................................................. 110

Summary ............................................................................................................... 110

Chapter 5. Session Management .......................................................................... 111

What Is Session Management? ......................................................................... 111

URL Rewriting....................................................................................................... 113

Hidden Fields ........................................................................................................ 125

Cookies .................................................................................................................. 138

Session Objects.................................................................................................... 152

Knowing Which Technique to Use .................................................................... 160

Summary ............................................................................................................... 161

Chapter 6. Application and Session Events......................................................... 162

Listening to Application Events .......................................................................... 162

Listening to HttpSession Events ........................................................................ 171

Summary ............................................................................................................... 177

Chapter 7. Servlet Filtering ..................................................................................... 178

An Overview of the API ....................................................................................... 178

A Basic Filter ......................................................................................................... 180

Mapping a Filter with a URL ............................................................................... 182

A Logging Filter..................................................................................................... 183

Filter Configuration............................................................................................... 185

A Filter that Checks User Input .......................................................................... 186

Filtering the Response ........................................................................................ 192

Filter Chain ............................................................................................................ 195

Summary ............................................................................................................... 199

Chapter 8. JSP Basics ............................................................................................ 200

What's Wrong with Servlets?.............................................................................. 200

Running Your First JSP....................................................................................... 202

How JSP Works.................................................................................................... 206

The JSP Servlet Generated Code ..................................................................... 206

The JSP API.......................................................................................................... 208

The Generated Servlet Revisited ...................................................................... 210

Implicit Objects ..................................................................................................... 214

Summary ............................................................................................................... 217

Chapter 9. JSP Syntax ............................................................................................ 218

Directives ............................................................................................................... 218

Scripting Elements ............................................................................................... 229

Standard Action Elements .................................................................................. 239

Comments ............................................................................................................. 240

Converting into XML Syntax ............................................................................... 241

Summary ............................................................................................................... 242

Chapter 10. Developing JSP Beans...................................................................... 243

iii

Calling Your Bean from a JSP Page................................................................. 243

A Brief Theory of JavaBeans.............................................................................. 245

Making a Bean Available .................................................................................... 246

Accessing Properties Using jsp:getProperty and jsp:setProperty ................ 250

Setting a Property Value from a Request......................................................... 252

JavaBeans Code Initialization ............................................................................ 254

The SQLToolBean Example............................................................................... 255

Summary ............................................................................................................... 262

Chapter 11. Using JSP Custom Tags ................................................................... 264

Writing Your First Custom Tag........................................................................... 265

The Role of the Deployment Descriptor ........................................................... 269

The Tag Library Descriptor ................................................................................. 270

The Custom Tag Syntax ..................................................................................... 272

The JSP Custom Tag API................................................................................... 273

The Life Cycle of a Tag Handler ........................................................................ 274

Summary ............................................................................................................... 285

Chapter 12. Programmable File Download.......................................................... 286

Keys to Programmable File Download ............................................................. 287

Using the Brainysoftware.com File Download Bean ...................................... 288

Summary ............................................................................................................... 288

Chapter 13. File Upload .......................................................................................... 290

The HTTP Request .............................................................................................. 290

Client-Side HTML ................................................................................................. 294

HTTP Request of an Uploaded File .................................................................. 295

Uploading a File.................................................................................................... 298

FileUpload Bean ................................................................................................... 302

Multiple File Upload ............................................................................................. 303

Summary ............................................................................................................... 304

Chapter 14. Security Configuration ....................................................................... 305

Imposing Security Constraints ........................................................................... 305

Allowing Multiple Roles ....................................................................................... 312

Form-Based Authentication ................................................................................ 313

Digest Authentication........................................................................................... 316

Methods Related to Security .............................................................................. 317

Restricting Certain Methods ............................................................................... 319

Summary ............................................................................................................... 319

Chapter 15. Caching................................................................................................ 320

Caching Data into a Text File ............................................................................. 320

Caching in Memory .............................................................................................. 325

Summary ............................................................................................................... 330

Chapter 16. Application Deployment .................................................................... 331

Application Directory Structure .......................................................................... 331

Deployment Descriptor........................................................................................ 333

Servlet Alias and Mapping .................................................................................. 351

JSP Alias and Mapping ....................................................................................... 353

Packaging and Deploying a Web Application.................................................. 355

Summary ............................................................................................................... 355

Chapter 17. Architecting Java Web Applications ................................................ 356

Model 1 Architecture............................................................................................ 356

Model 2 Architecture............................................................................................ 361

iv

Summary ............................................................................................................... 364

Chapter 18. Developing E-Commerce Applications ........................................... 365

Project Specification ............................................................................................ 365

The Database Structure ...................................................................................... 366

Page Design.......................................................................................................... 367

Preparation............................................................................................................ 367

Application Design ............................................................................................... 368

Building the Project .............................................................................................. 371

Summary ............................................................................................................... 388

Chapter 19. XML-Based E-Books ......................................................................... 389

The Table of Contents......................................................................................... 390

Translating XML into the Object Tree ............................................................... 390

The Project ............................................................................................................ 392

Pre-Render the Table of Contents..................................................................... 403

Summary ............................................................................................................... 403

Chapter 20. Web-Based Document Management.............................................. 404

The Docman Project ............................................................................................ 405

Summary ............................................................................................................... 437

Part II: Client-Side Programming with JavaScript ................................................... 439

Chapter 21. JavaScript Basics ............................................................................... 440

Introduction to JavaScript ................................................................................... 440

Adding JavaScript Code to HTML ..................................................................... 450

JavaScript Object Model ..................................................................................... 452

Event Handler ....................................................................................................... 453

Window and String Objects ................................................................................ 454

Summary ............................................................................................................... 457

Chapter 22. Client-Side Programming Basics..................................................... 458

Checking Whether JavaScript Is Enabled........................................................ 458

Handling JavaScript-Unaware Browsers.......................................................... 461

Handling Different Versions of JavaScript........................................................ 461

Including a JavaScript File.................................................................................. 462

Checking the Operating System ........................................................................ 463

Checking the Browser Generation .................................................................... 464

Checking the Browser Type ............................................................................... 465

Checking the Browser Language ...................................................................... 465

Handling Dynamic Variable-Names .................................................................. 466

Summary ............................................................................................................... 467

Chapter 23. Redirection .......................................................................................... 468

Anticipating Failed Redirection .......................................................................... 468

Using the Refresh Meta Tag .............................................................................. 468

Using the location Object .................................................................................... 469

Going Back to the Previous Page...................................................................... 470

Moving Forward .................................................................................................... 471

Navigation with a SELECT Element.................................................................. 472

Summary ............................................................................................................... 473

Chapter 24. Client-Side Input Validation .............................................................. 474

The isEmpty Function.......................................................................................... 474

The trim Function ................................................................................................. 475

The trimAll Function ............................................................................................. 477

The isPositiveInteger Function........................................................................... 477

v

The isValidPhoneNumber Function .................................................................. 478

The isMoney Function ......................................................................................... 479

The isUSDate and isOZDate Functions ........................................................... 480

Converting Date Formats.................................................................................... 483

Data Type Conversion: String to Numeric........................................................ 483

Data Type Conversion: Numeric to String........................................................ 485

Using the Validation Functions........................................................................... 485

Summary ............................................................................................................... 487

Chapter 25. Working with Client-Side Cookies ................................................... 488

Creating Cookies with a <META> Tag ............................................................. 488

Creating Cookies with document.cookie .......................................................... 489

Creating Cookies with the setCookie Function................................................ 490

Reading Cookies on the Browser ...................................................................... 492

Deleting a Cookie on the Browser ..................................................................... 493

Checking If the Browser Can Accept Cookies Using JavaScript.................. 494

Checking If the Browser Accepts Cookies Without JavaScript..................... 495

Summary ............................................................................................................... 495

Chapter 26. Working with Object Trees................................................................ 496

The Array Object .................................................................................................. 496

Truly Deleting an Array Element........................................................................ 499

Creating an Object ............................................................................................... 501

A Hierarchy of Objects......................................................................................... 501

Summary ............................................................................................................... 513

Chapter 27. Controlling Applets............................................................................. 514

Is Java Enabled?.................................................................................................. 514

Is the Applet Ready? ........................................................................................... 515

Resizing an Applet ............................................................................................... 516

Calling an Applet's Method ................................................................................. 516

Getting an Applet's Property............................................................................... 517

Setting an Applet Property.................................................................................. 518

Using Java Classes Directly ............................................................................... 519

Applet-to-JavaScript Communication................................................................ 520

Accessing the Document Object Model from an Applet ................................ 522

Invoking JavaScript Functions from an Applet ................................................ 523

Evaluating a JavaScript Statement from an Applet ........................................ 524

Setting the Applet Parameter ............................................................................. 525

Applet-to-Applet Communication Through JavaScript ................................... 526

Direct Applet-to-Applet Communication ........................................................... 528

Summary ............................................................................................................... 530

Part III: Developing Scalable Applications with EJB............................................... 531

Chapter 28. Enterprise JavaBeans ....................................................................... 532

What Is an Enterprise JavaBean? ..................................................................... 532

Benefits of EJB ..................................................................................................... 533

EJB Application Architecture .............................................................................. 533

The Six EJB Roles ............................................................................................... 534

Types of Enterprise Beans ................................................................................. 535

Writing Your First Enterprise Bean.................................................................... 535

EJB Explained....................................................................................................... 538

Writing Client Applications .................................................................................. 541

Creating a Bean's Instance................................................................................. 544

vi

Summary ............................................................................................................... 547

Chapter 29. The Session Bean.............................................................................. 548

What Is a Session Bean?.................................................................................... 548

Stateful and Stateless Session Beans.............................................................. 548

Writing a Session Bean ....................................................................................... 549

The Tassie Online Bookstore Example ............................................................ 554

Summary ............................................................................................................... 572

Chapter 30. Entity Beans ........................................................................................ 573

What Is an Entity Bean?...................................................................................... 573

The Remote Interface.......................................................................................... 574

The Home Interface ............................................................................................. 574

The Primary Key Class........................................................................................ 576

The Entity Bean .................................................................................................... 576

Two Types of Entity Beans................................................................................. 580

Writing a BMP Entity Bean ................................................................................. 580

Writing a CMP Entity Bean ................................................................................. 596

Summary ............................................................................................................... 602

Chapter 31. EJB Query Language ........................................................................ 603

EJB QL Syntax ..................................................................................................... 604

EJB QL BNF.......................................................................................................... 609

Summary ............................................................................................................... 611

Chapter 32. Java Message Service ...................................................................... 612

Introduction to Messaging................................................................................... 612

The JMS API ......................................................................................................... 612

The JMS API Messaging Domains.................................................................... 613

The JMS Object Model........................................................................................ 614

Writing JMS Clients.............................................................................................. 619

Summary ............................................................................................................... 622

Chapter 33. Message-Driven Beans ..................................................................... 624

What Is a Message-Driven Bean?..................................................................... 624

The Application Programming Interface ........................................................... 624

Writing a Message-Driven Bean ........................................................................ 625

Summary ............................................................................................................... 630

Part IV: Appendixes ..................................................................................................... 631

Appendix A. Tomcat Installation and Configuration............................................ 632

Tomcat Installation ............................................................................................... 632

Tomcat Directories ............................................................................................... 636

Changing the Port ................................................................................................ 637

Constructing a JSP Application.......................................................................... 637

Appendix B. The javax.servlet Package Reference ........................................... 639

Interfaces ............................................................................................................... 640

Classes .................................................................................................................. 650

Exceptions ............................................................................................................. 657

Appendix C. The javax.servlet.http Package Reference ................................... 659

Interfaces ............................................................................................................... 660

Classes .................................................................................................................. 671

Appendix D. The javax.servlet.jsp Package Reference ..................................... 679

Interfaces ............................................................................................................... 679

Classes .................................................................................................................. 680

Appendix E. The javax.servlet.jsp.tagext Package Reference ......................... 689

vii

Interfaces ............................................................................................................... 689

Classes .................................................................................................................. 692

Appendix F. JBoss Installation and Configuration .............................................. 702

System Requirements ......................................................................................... 702

Installing JBoss..................................................................................................... 702

Directory Structure ............................................................................................... 704

Configuration......................................................................................................... 704

Running JBoss...................................................................................................... 705

Deployment ........................................................................................................... 705

JBoss and Tomcat ............................................................................................... 705

Summary ............................................................................................................... 705

Appendix G. Related Resources ........................................................................... 706

J2EE ....................................................................................................................... 706

Servlet .................................................................................................................... 706

JSP ......................................................................................................................... 706

Tag Library ............................................................................................................ 706

Servlet/JSP Containers ....................................................................................... 707

JDBC ...................................................................................................................... 707

JNDI........................................................................................................................ 707

JMS......................................................................................................................... 707

EJB ......................................................................................................................... 707

J2EE Server .......................................................................................................... 708

Appendix H. What's On the CD-ROM?................................................................. 709

Read This Before Opening the Software.......................................................... 709

GNU LESSER GENERAL PUBLIC LICENSE................................................. 710

GNU LESSER GENERAL PUBLIC LICENSE................................................. 711

NO WARRANTY................................................................................................... 716

viii

Copyright

Copyright © 2002 by New Riders Publishing

FIRST EDITION: April, 2002

All rights reserved. No part of this book may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage and retrieval system, without written permission from the publisher, except for the inclusion of brief quotations in a review.

Library of Congress Catalog Card Number: 2001093802

06 05 04 03 02 7 6 5 4 3 2 1

Interpretation of the printing code: The rightmost double-digit number is the year of the book's printing; the rightmost single-digit number is the number of the book's printing. For example, the printing code 02-1 shows that the first printing of the book occurred in 2002.

Trademarks

All terms mentioned in this book that are known to be trademarks or service marks have been appropriately capitalized. New Riders 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.

Warning and Disclaimer

This book is designed to provide information about Java for the web working with servlets, jsp, and ejb. Every effort has been made to make this book as complete and as accurate as possible, but no warranty of fitness is implied.

The information is provided on an as-is basis. The authors and New Riders Publishing 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 discs or programs that may accompany it.

Publisher

David Dwyer

Associate Publisher

Stephanie Wall

Production Manager

Gina Kanouse

Managing Editor

ix

Kristy Knoop

Acquisitions Editor

Deborah Hittel-Shoaf

Development Editor

Grant Munroe

Product Marketing Manager

Kathy Malmloff

Publicity Manager

Susan Nixon

Copy Editor

Kathy Murray

Indexer

Chris Morris

Manufacturing Coordinator

Jim Conway

Book Designer

Louisa Klucznik

Cover Designer

Brainstorm Design, Inc.

Cover Production

Aren Howell

Proofreader

Sossity Smith

Composition

Jeff Bredensteiner

Media Developer

Jay Payne x

About the Author

Budi Kurniawan is an IT consultant specializing in Internet and object-oriented programming and has taught both Java and Microsoft technologies. He is the author of the most popular Java

Upload bean from BrainySoftware.com, which is licensed by Commerce One (NASDAQ: CMRC) and purchased by major corporations, such as Saudi Business Machine Ltd ( www.sbm.com.sa

),

Baxter Healthcare Corporation ( www.baxter.com

), and others.

Budi has a Masters of Research degree in Electrical Engineering from Sydney University,

Australia. His research topic was on digital image processing. Budi has written a number of computer books, as well as published articles for more than 10 publications—including prestigious Java magazines, such as Java-Pro, JavaWorld, JavaReport, and O'Reilly's www.onjava.com

. Budi is now the weekly contributor for the Servlets/JSP section of Java Insight and can be contacted at [email protected]

.

About the Technical Reviewers

Y process for Java for the Web with Servlets, JSP, and EJB. As the book was being written, these

FL reader's need for the highest-quality technical information. programming courses covering a wide range of programming concepts and languages, such as

TE

AM throughout Canada and the U.S. He is also certified as an MCP, MCSD, MCT, CCNA, CCAI and

SCP/Java2.

Lan Wu joined Persistence Software in Silicon Valley after receiving her Master's Degree in

Computer Science. Lan's efforts at Persistence were focused on Java with EJBs. Later, she moved on to myCFO Corporation, where she is involved with the designing and developing of the automation system. She is now with Blue Martini Software and responsible for automation with

Java and web programming.

Acknowledgments

So many people are involved in the process of delivering this book, without whom this book would never be a reality.

First and foremost I'd like to thank Deborah Hittel-Shoaf, my Acquisitions Editor, for her professionalism and flexibility. Really, she takes care of her authors.

Team-Fly ®

Thanks also go to Grant Munroe, my Development Editor, for his patience and for getting all the chapters together.

Two excellent editors helped me with technical review and provided invaluable feedback and made the content much, much better: Lan Wu and Chris Crane. I would also like to thank them.

Finally, all the folks at New Riders who helped me with the diagrams, proofreading, index, layout, and so on. Thank you.

Special thanks go to my best friend Ken for providing me with excellent accommodation (and

Internet access) during my Christmas visit to Vancouver, BC—after being knocked out exhausted in the middle of the writing of this book. His party and the tours refreshed me.

Tell Us What You Think

As the reader of this book, you are the 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 the Associate Publisher for New Riders 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 author as well as your name and phone or fax number. I will carefully review your comments and share them with the author and editors who worked on the book.

Fax: 317-581-4663

Email: [email protected]

Mail: Stephanie Wall

Associate Publisher

New Riders Publishing

201 West 103 rd

Street

Indianapolis, IN 46290 USA

Introduction

The Internet is still young and vulnerable. Therefore, its history is not a lengthy one. The web started when everything was just static pages. Unless you are a six-year-old whiz kid reading this book because you are more interested in Java web programming than PlayStation2, it is most likely that you experienced the time when a web site was no more than HTML pages. In the earlier days, a web site had at most one page and it more often than not was called a home page.

The terms "Internet application" or "web application" were coined when dynamic content was introduced. Loosely interpreted, a web application is a web site whose contents are generated

xii

dynamically before being sent to the browser. You should first understand how the Internet works before learning how a web application works.

When you surf the Internet, you basically request for a certain file located in a particular computer in the location you specify in the Uniform Resource Locator (URL). The computer where the file is stored is called the web server. This computer's main function is to serve anybody on the

Internet who requests files it hosts. Because you never know when a user will visit and use your web application, your web server must be up and running all the time.

When you click or type in a URL in the Location or Address box of your browser, the following things happen:

The client browser establishes a TCP/IP connection with the server.

The browser sends a request to the server.

The server sends a response to the client.

The server closes the connection.

Note that after sending the requested page to the browser, the server always closes the connection, whether or not the user requests other pages from the server.

What Is Happening in the Industry

Since the emergence of the Internet, web technologies have become more and more important, and web applications are more and more common. The use of a web browser is no longer restricted to surfing static pages on the Internet. It is now very commonplace to see a web browser used as an application's client.

What this means is, some people believe, whoever controls the Internet controls the future of computing—or even the future itself. At the very least, the evidence has been demonstrated by the struggles of a few companies to grab the web browsers' domination in the late 1990s. As the best example, Microsoft Corporation—still the number one player in the software business up until now—felt it was important to have everyone on the planet using its Internet Explorer browser. That's why it exerted its overwhelming power in software technology to create the fastest and smartest browser ever and distribute it for free. With the surrender of Netscape, Microsoft has won the battle of browsers. In the next five years, it is still hard to imagine how any browser could surpass the popularity of Microsoft Internet Explorer.

On the server side, it's a different story, though. The war is far from over. Microsoft can't push its server technology as easily as it forced Netscape to give up. In fact, the most popular server technology is Java. To be precise, it's Sun Microsystems' Java 2,

Enterprise Edition (J2EE). Microsoft is still trying to catch up with its new .NET initiative that is a replacement of its previous Distributed interNet Applications (DNA) platform for developing enterprise applications. Released in early 2002, .NET will collide head-on with J2EE. The next few years will still see J2EE and .NET as the two competing server technologies. Right now, it's still too premature to predict who will come out the winner.

Strategy-wise, Microsoft takes a far different approach from Sun in trying to win.

Microsoft provides a single-vendor solution, selling from the operating system to the database server. J2EE, on the other hand, is supported by the entire industry. (For a list of vendors who provide J2EE compliant servers, see

Appendix G , "Related Resources.")

Analysts have tried to compare J2EE and .NET in many white papers published on the

Internet. Unfortunately, the conclusions vary a great deal. To find out more about how

J2EE and .NET compare, you can consult the following articles, which are available

xiii

online:

Microsoft .NET vs. J2EE: How Do They Stack Up?, http://java.oreilly.com/news/farley_0800.html

Java 2 Enterprise Edition (J2EE) versus The .NET Platform: Two Visions for eBusiness, http://www.objectwatch.com/FinalJ2EEand DotNet.doc

J2EE vs. Microsoft.NET: A Comparison of Building XML-Based Web

Services, http://www.theserverside.com/resources/article.jsp?l=J2EE-vs-DOTNET

Compare Microsoft .NET to J2EE Technology, http://msdn.microsoft.com/net/compare/default.asp

The Great Debate: .NET vs. J2EE http://www.javaworld.com/javaworld/jw- 03-2002/jw-0308-j2eenet.html

At this point, you should have gotten the big picture of what is happening in the industry. You can find out more about .NET at http://msdn.microsoft.com

. J2EE is presented in the section, "

Java 2 ."

Also note that the term web server can also be used to refer to the software package used in the web server computer to handle requests and respond to them. In fact, throughout this book, the term web server is used to refer to this software.

The first popular web server—NCSA HTTPd—was created by Rob McCool at the

National Center for Supercomputing Applications. And, McCool's invention was really cool because it helped the Internet revolutionize our lives and went on to become the foundation for the Apache web server—the most used web server on the Internet today.

The Hypertext Transfer Protocol (HTTP)

HTTP is the protocol that allows web servers and browsers to exchange data over the web. It is a request and response protocol. The client requests a file and the server responds to the request.

HTTP uses reliable TCP connections—by default on TCP port 80. HTTP (currently at version 1.1 at the time of this writing) was first defined in RFC 2068. It was then refined in RFC 2616, which can be found at http://www.w3c.org/Protocols/ .

In HTTP, it's always the client who initiates a transaction by establishing a connection and sending an HTTP request. The server is in no position to contact a client or make a callback connection to the client. Either the client or the server can prematurely terminate a connection. For example, when using a web browser you can click the Stop button on your browser to stop the download process of a file, effectively closing the HTTP connection with the web server.

xiv

HTTP Requests

An HTTP transaction begins with a request from the client browser and ends with a response from the server. An HTTP request consists of three components:

Method——URI—Protocol/Version

Request headers

Entity body

An example of an HTTP request is the following:

GET /servlet/default.jsp HTTP/1.1

Accept: text/plain; text/html

Accept-Language: en-gb

Connection: Keep-Alive

Host: localhost

Referer: http://localhost/ch8/SendDetails.htm

User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)

Content-Length: 33

Content-Type: application/x-www-form-urlencoded

Accept-Encoding: gzip, deflate

LastName=Franks&FirstName=Michael

The method—URI—protocol version appears as the first line of the request.

GET /servlet/default.jsp HTTP/1.1 where

GET

is the request method,

/servlet/default.jsp

represents the URI and

HTTP/1.1

the Protocol/Version section.

The request method will be explained in more details in the next section, "

HTTP request

Methods ."

The URI specifies an Internet resource completely. A URI is usually interpreted as being relative to the server's root directory. Thus, it should always begin with a forward slash /. A URL is actually a type of URI (see http://www.ietf.org/rfc/rfc2396.txt

). The Protocol version represents the version of the HTTP protocol being used.

The request header contains useful information about the client environment and the entity body of the request. For example, it could contain the language the browser is set for, the length of the entity body, and so on. Each header is separated by a carriage return/linefeed (CRLF) sequence.

Between the headers and the entity body, there is a blank line (CRLF) that is important to the

HTTP request format. The CRLF tells the HTTP server where the entity body begins. In some

Internet programming books, this CRLF is considered the fourth component of an HTTP request.

In the previous HTTP request, the entity body is simply the following line:

LastName=Franks&FirstName=Michael

The entity body could easily become much longer in a typical HTTP request.

HTTP request Methods

xv

Each HTTP request can use one of the many request methods as specified in the HTTP standards.

The HTTP 1.1 request methods and the descriptions of each method are given in

Table I.1

.

Table I.1. HTTP 1.1 request Methods

Method Description

GET GET is the simplest, and probably, most used HTTP method. GET simply retrieves the data identified by the URL. If the URL refers to a script (CGI, servlet, and so on), it returns the data produced by the script.

HEAD The HEAD method provides the same functionality as GET, but HEAD only returns

HTTP headers without the document body.

POST Like GET, POST is also widely used. Typically, POST is used in HTML forms. POST is used to transfer a block of data to the server in the entity body of the request.

OPTIONS The OPTIONS method is used to query a server about the capabilities it provides.

Queries can be general or specific to a particular resource.

PUT The PUT method is a complement of a GET request, and PUT stores the entity body at the location specified by the URI. It is similar to the PUT function in FTP.

DELETE The DELETE method is used to delete a document from the server. The document to be deleted is indicated in the URI section of the request.

TRACE The TRACE method is used to tract the path of a request through firewall and multiple proxy servers. TRACE is useful for debugging complex network problems and is similar to the traceroute tool.

Warning

HTTP 1.0 only has three request methods: GET, HEAD, and POST.

Of the seven methods, only GET and POST are commonly used in an Internet application.

HTTP Responses

Similar to requests, an HTTP response also consists of three parts:

Protocol—Status code——Description

Response headers

Entity body

The following is an example of an HTTP response:

HTTP/1.1 200 OK

Server: Microsoft-IIS/4.0

Date: Mon, 3 Jan 1998 13:13:33 GMT

Content-Type: text/html

Last-Modified: Mon, 11 Jan 1998 13:23:42 GMT

Content-Length: 112

<HTML>

<HEAD>

<TITLE>HTTP Response Example</TITLE></HEAD><BODY>

Welcome to Brainy Software

</BODY>

</HTML>

xvi

The first line of the response header is similar to the first line of the request header. The first line tells you that the protocol used is HTTP version 1.1, the request succeeded (200 = success), and that everything went okay.

The response headers contain useful information similar to the headers in the request. The entity body of the response is the HTML content of the response itself. The headers and the entity body are separated by a sequence of CRLFs.

System Architecture

This section is meant to give you the big picture of a software application system utilizing Java or other technologies. This section takes the common approach of introducing software system architecture by observing how it has evolved.

A well-designed software application is partitioned into separate logical parts called layers. Each layer has a different responsibility in the overall architecture. These layers are purely abstractions, and do not correspond to physical distribution.

Typical layers in a software system are as follows:

Presentation layer. In this layer are parts that handle the user interface and user interaction.

Business logic layer. This layer contains components that handle the programming logic of the application.

Data layer. This layer is used by the business logic layer to persist state permanently.

This layer normally consists of one or more databases where data is stored. However, other types of datastore could also be used. For example, it is now very common to use

XML documents as storage to keep data.

The Two-Tier Architecture

A two-tiered application is a simple client-server application in which the processing workload falls onto the client computer's shoulders and the server simply acts as a traffic controller between the client and the data. The term "fat client" for this type of architecture is due to the bulk of processing requirements at the client side. In this architecture, the presentation layer and the business logic layer are hosted in one tier and the data layer is on another tier.

Figure I.1

shows a

two-tier architecture.

Figure I.1. A two-tiered application.

The drawback of this type of architecture is that it starts to pose problems as the number of clients increases. The first problem is due to the fact that all processing happens at the client side. There is increased network traffic because each client has to make multiple requests for data from the serve—even before presenting anything to the user.

Another problem is cost because each client needs a machine with sufficient processing power. As the number of clients increase, the cost for providing client machines alone could be astronomical.

xvii

However, the most severe problem that this type of architecture can cause is probably a maintenance problem. Even a tiny change to the processing logic might require a complete rollout to the entire organization. Even though the process can be automated, there are always problems with larger organizations because some users may not be ready for an upgrade, whereas others insist it be performed immediately.

The Three-Tier Architecture

To overcome the problems in many client two-tiered applications, an application is broken up into three separate tiers, instead of two. The first tier contains the presentation layer, the second tier, or the middle tier, consists of the business logic layer, and the third tier contains the data layer.

Figure I.2

shows a three-tier architecture.

Figure I.2. A three-tiered application.

The n-Tier Architecture

To achieve more flexibility, the three tiers in the three-tiered application can be segregated even further. An application with this type of architecture is called an n-tiered application. In this architecture, the business logic layer is divided by function instead of being physically divided. It breaks down like the following:

A user interface. This handles the user interaction with the application. In an Internet application, this is usually a web browser used to render HTML tags.

Presentation logic. This defines what the user interface displays and how user requests are handled.

Business logic. This models the application business logic.

Infrastructure services. These provide additional functionality required by the application components.

The data layer. Hosts the application data.

Java 2, Enterprise Edition (J2EE)

First of all, J2EE is not a product. Rather, it is a specification that defines the contract between applications and the container. The container here refers to a standardized runtime environment, which provides specific services for components deployed in it. J2EE is described in more detail in

Part III , "Developing Scalable Applications with EJB," of this book.

Developing Web Applications in Java

You normally adopt two main architectures when developing web applications in Java. The first architecture utilizes servlets and JSP in the middle tier to serve clients and process the business

xviii

logic. This architecture is depicted in

Figure I.3

. The middle tier is discussed during the servlets

and JSP coverage in this book.

Figure I.3. A servlets/JSP application architecture.

Small to medium-size applications use this design model.

The second architecture includes the use of J2EE server and Enterprise JavaBeans (EJB) and this is especially useful for large enterprise applications that need scalability. The architecture is shown in

Figure I.4

, and EJB is discussed in

Part III of this book.

Figure I.4. A J2EE application architecture.

Overview of Parts and Chapters

This book consists of four parts, including the appendixes.

Part I : Building Java Web Applications

This part is comprised of 20 chapters on servlets and JavaServer Pages (JSP).

Chapter 1 , "The Servlet Technology," introduces you to the servlet technology and compares it

with other existing web technologies. More importantly, this chapter prepares you to write servlets, including the step-by-step instructions on quickly configuring the servlet container, compiling your servlet, and deploying it in the container. If you follow the instructions correctly, you will be able to view your servlet in action with your web browser.

Chapter 2 , "Inside Servlets," discusses the nuts and bolts of the latest release of the Java Servlet

specification Application Programming Interface (API), version 2.3. This chapter explains the first of the two packages available for servlet programmers: javax.servlet. This package contains basic classes and interfaces that you can use to write servlets from the scratch. Important concepts, such as a servlet's life cycle, a servlet's context, requests, responses, and how to write thread-safe servlets are discussed in this chapter.

xix

Chapter 3 , "Writing Servlet Applications," explains the classes and interfaces in the

javax.servlet.http package. Compared to the javax.servlet package, javax.servlet.http offers more advanced classes and interfaces that extend classes and interfaces in javax.servlet. This chapter also demonstrates the use of several techniques, such as obtaining values sent by the user, using different HTTP methods, response buffering, request dispatching, and including other resources in a servlet.

Chapter 4 , "Accessing Databases with JDBC," shows how you can access and manipulate data in a

database using Java Database Connectivity ( JDBC). This chapter starts with a look at the object model in the java.sql package and explains how to connect to a database in detail. After a few examples, this chapter concludes with a multipurpose tool that enables you to type your SQL statement in the browser, get it executed on the server, and have the result displayed in the browser.

Chapter 5 , "Session Management," explains the importance of being able to manage user session

and retain state from previous requests. Several techniques are introduced, such as URL rewriting, hidden fields, and cookies. However, the servlet container offers its own automatic session management, a great feature that makes managing user session easy and straightforward.

Chapter 6 , "Application and Session Events," discusses the new feature in the Servlet 2.3

specification, as well as several events that have been available since the previous versions of the specification. This chapter provides examples on how to listen and capture the application and session events and configure the deployment descriptor.

Chapter 7 , "Servlet Filtering," explains another new feature in the Servlet 2.3 specification. This

chapter shows you how you can make full use of servlet filtering to achieve some important tasks, such as preprocessing an HTTP request.

Chapter 8 , "JSP Basics," introduces the second Java web technology that should be used in

conjunction with servlets. This chapter explains situations where you want to use JSP, and discusses the relation between servlets and JSP.

Chapter 9 , "JSP Syntax," presents the complete syntax for JavaServer Pages. In particular, it

discusses directives, scripting elements, and action elements. Wherever possible, examples are given to illustrate how to use each item.

Chapter 10 , "Developing JSP Beans," introduces the component-centric approach for writing JSP

applications using JavaBeans. Using this approach, division of labor is possible. The Java programmer writes and compiles JavaBeans that incorporate all the functionality needed in an application and the page designer works with the page design at the same time. When the

JavaBeans are ready, the page designer uses tags to call methods and properties of the beans from the JSP page.

Chapter 11 , "Using JSP Custom Tags," explains what custom tags are and how to use them to

perform custom actions from a JSP page. This chapter explores the great features of custom tags and begins with writing a JSP page that uses custom tags. It then explains the classes and interfaces in the javax.servlet.jsp.tagext package.

Chapter 12 , "Programmable File Download," discusses a technique that allows you to

programmatically send a file to a browser. Using this technique, you, the programmer, have full control over the downloaded file. This chapter offers an example of how to do programmable file download from a JSP page.

Chapter 13 , "File Upload," explains all you need to know about file upload, including the

underlying theory of HTTP requests. Knowledge of the HTTP request is critical because when you process an uploaded file, you work with raw data not obtainable from simply querying the

xx

HTTP Request object. The last section of the chapter talks about the File Upload Bean from

Brainysoftware.com, included on the accompanying CD.

Chapter 14 , "Security Configuration," presents the technique for securing your web application by

configuring the deployment descriptor to instruct the web container to restrict access to some, or all, of the resources. The configuration means that you only need to modify your deployment descriptor file—no coding is needed.

Chapter 15 , "Caching," offers two caching techniques to enhance the application performance:

caching data in a text file and caching data in memory. The first solution writes frequently accessed but hardly changed data into text files. When your application needs the data from the database, instead of hitting the database server, the application can just include a text file. The second technique can boost performance more dramatically by caching data in memory. This chapter will show you how you can use these two techniques to improve your application performance.

Chapter 16 , "Application Deployment," discusses the process of deploying a servlet and JSP

application. To understand how to properly display your web application, you need to first understand the directory structure of an application. Therefore, this chapters starts with a review of the directory structure. The next topic is the deployment descriptor where you can configure each application.

Chapter 17 , "Architecting Java Web Applications," presents the two models in servlets/JSP

Chapter 18

that uses Model 2 architecture, which is discussed in

FL

Y

. This is a complete application

Chapter 19

AM

Chapter 20

TE explore the database structure that manages all objects representing your documents and extend the functionality to suit your needs.

Part II : Client-Side Programming with JavaScript

This part contains seven chapters on how to use JavaScript as the client-side programming language in your web application.

Chapter 21 , "JavaScript Basics," presents an introduction to JavaScript and prepares you to

program the client-side of your web application.

Chapter 22 , "Client-Side Programming Basics," offers the discussion on the benefits of client-side

programming. These benefits not only contribute to the level of scalability of your web application, but also to user satisfaction. In this chapter you will learn the sort of problems that you will encounter when programming for the client side, problems that you should be aware of even before you write your first line of code.

Chapter 23 , "Redirection," discusses various techniques to redirect users to another resource.

Redirection is a commonly used in many web applications, and it is important to be able to select the right technique for the redirection.

Team-Fly ®

Chapter 24 , "Client-Side Input Validation," provides you with techniques to do input validation on

the client-side. When you apply client-side validation, you ensure that the values of form elements are valid before the form is submitted. From the server's perspective, this means reduced workload because it does not have to return the user to the form to correct a value. For users, this means they receive a much faster response because they get an instant warning when a form entry is not correct. This chapter discusses the two types of input validation: at the form level and at the form element level.

Chapter 25 , "Working with Client-Side Cookies," looks at cookies in detail, especially how to

manipulate cookies at the client-side (for example, on the browser). This chapter presents tips for working with cookies, including how to create, delete, and edit a cookie both on the server side and the client side.

Chapter 26 , "Working with Object Trees," offers the technique to work with objects in a hierarchy.

The technique described in this chapter is used for the XML-based online help and document management projects in

Chapter 19 and

Chapter 20 .

Chapter 27 , "Controlling Applets," does not discuss how to write applets. Instead, it discusses a

different aspect of working with applets: how you can control applets from an HTML page using

JavaScript. Controlling an applet includes running an applet's methods, reading its properties, and passing a value to it for further processing.

Part III : Developing Scalable Applications with EJB

This part offers six chapters on Enterprise JavaBeans to help you develop scalable applications.

Chapter 28 , "Enterprise JavaBeans," serves as the introduction to Enterprise JavaBeans (EJB). It

starts with defining what EJB is and presenting some of the benefits of using EJB—most of which are not available in servlet/JSP. Then, it discusses the architecture and the distinct roles in the EJB application and deployment life cycle. It then provides a sample application and some technical insights by presenting a review of the javax.ejb package. Lastly, two client applications are presented to test the sample application.

Chapter 29 , "The Session Bean," presents the first type of enterprise bean: session bean. It starts

with an overview of what a session bean is and explains two types of session beans: stateful and stateless. After a discussion of the API, it offers an example that demonstrates the use of session beans and how to write a client application that uses the bean.

Chapter 30 , "Entity Beans," explains the two types of entity beans: entity beans with bean-

managed persistence (BMP) and entity beans with container-managed persistence (CMP).

Chapter 31 , "EJB Query Language," presents the language added to the EJB 2.0 specification: the

Enterprise JavaBeans Query Language (EJB QL). EJB QL is similar to Structured Query

Language (SQL) and is used by bean developers to select data for finder methods of CMP entity beans.

Chapter 32 , "Java Message Service," offers an introduction to messaging and the JMS API. This

chapter also provides several examples that use JMS to send and receive messages. This chapter should provide the basic knowledge for working with the third type of Enterprise JavaBeans (EJB): message-driven beans (MDB).

Chapter 33 , "Message-Driven Beans," begins with an overview of what a message-driven bean is

and a close look at the object model. It then continues with an example of a message-driven bean and instruction on how to deploy it in JBoss.

xxii

Appendixes

The last part of this book comprises of seven appendixes, all of which are self-explanatory. The seven appendixes are as follows:

Appendix A , "Tomcat Installation and Configuration"

Appendix B , "The javax.servlet Package Reference"

Appendix C , "The javax.servlet.http Package Reference"

Appendix D , "The javax.servlet.jsp Package Reference"

Appendix E , "The javax.servlet.jsp.tagext Package Reference"

Appendix F , "JBoss Installation and Configuration"

Appendix G , "Related Resources"

Appendix H , "What's On the CD-ROM?"

xxiii

Part I: Building Java Web Applications

Part I Building Java Web Applications

1 The Servlet Technology

2 Inside Servlets

3 Writing Servlet Applications

4 Accessing Databases with JDBC

5 Session Management

6 Application and Session Events

7 Servlet Filtering

8 JSP Basics

9 JSP Syntax

10 Developing JSP Beans

11 Using JSP Custom Tags

12 Programmable File Download

13 File Upload

14 Security Configuration

15 Caching

16 Application Deployment

17 Architecting Java Web Applications

18 Developing E-Commerce Applications

19 XML Based E-Books

20 Web-Based Document Management

1

Chapter 1. The Servlet Technology

The servlet technology is the foundation of web application development using the Java programming language. It is one of the most important Java technologies, and it is the underlying technology for another popular Java technology for web application development: JavaServer

Pages (JSP). Therefore, understanding the servlet technology and its architecture is important if you want to be a servlet developer. Even if you plan to develop your Java web application using

JSP pages alone, understanding the servlet technology helps you build a more efficient and effective JSP application.

The aim of this chapter is to introduce the servlet technology and make you comfortable with it by presenting step-by-step instructions that enable you to build and run a servlet application.

In particular, this chapter discusses the following topics:

The benefits of servlets

Servlet application architecture

How a servlet works

How to write and run your first servlet application

Throughout this book, Tomcat 4.0 is used as both the servlet container and JSP container. In this chapter, you learn how to configure Tomcat quickly so that you can run your first servlet application.

Note

For a complete reference on how to configure your application, see

Chapter 16 ,

"Application Deployment." You can find more detail on Tomcat installation in

Appendix

A

, "Tomcat Installation and Configuration."

The Benefits of Servlets

When it first emerged, this great thing we call the Internet consisted of only static contents written using Hypertext Markup Language (HTML). At that time, anyone who could author HTML pages was considered an Internet expert.

This did not last long, however.

Soon dynamic web contents were made possible through the Common Gateway Interface (CGI) technology. CGI enables the web server to call an external program and pass HTTP request information to that external program to process the request. The response from the external program is then passed back to the web server, which forwards it to the client browser. CGI programs can be written in any language that can be called by the web server. Over the course of time, Perl became the most popular language to write CGI programs.

As the Internet became more and more popular, however, the number of users visiting a popular web site increased exponentially, and it became apparent that CGI had failed to deliver scalable

Internet applications. The flaw in CGI is that each client request makes the web server spawn a new process of the requested CGI program. As we all know, process creation is an expensive operation that consumes a lot of CPU cycles and computer memory.

2

Gradually, new and better technologies will replace CGI as the main technology for web application development. The world has witnessed the following technologies trying to dominate web development:

ColdFusion. Allaire's ColdFusion provides HTML-like custom tags that can be used to perform a number of operations, especially querying a database. This technology had its glamorous time in the history of the World Wide Web as the main technology for web application programming. Its glorious time has since gone with the invention of other technologies.

Server-side JavaScript (SSJS). SSJS is an extension of the JavaScript language, the scripting language that still rules client-side web programming. SSJS can access Java classes deployed at the server side using the LiveWire technology from Netscape.

PHP. PHP is an exciting open-source technology that has matured in recent years. The technology provides easy web application development with its session management and includes some built-in functionality, such as file upload. The number of programmers embracing PHP as their technology of choice has risen sharply in recent years.

Servlet. The servlet technology was introduced by Sun Microsystems in 1996. This technology is the main focus of this book and will be explained in more detail in this and coming chapters.

JavaServer Pages (JSP). JSP is an extension of the servlet technology. This, too, is the center of attention in this book.

Active Server Pages (ASP). Microsoft's ASP employs scripting technologies that work in Windows platforms, even though there have been efforts to port this technology to other operating systems. Windows ASP works with the Internet Information Server web server. This technology will soon be replaced by Active Server Pages.NET.

Active Server Pages.NET (ASP.NET). This technology is part of Microsoft's .NET initiative. Interestingly, the .NET Framework employs a runtime called the Common

Language Runtime that is very similar to Java Virtual Machine and provides a vast class library available to all .NET languages and from ASP.NET pages. ASP.NET is an exciting technology. It introduced several new technologies including state management that does not depend on cookies or URL rewriting.

In the past, ASP and servlet/JSP have been the main technologies used in web application development. With the release of ASP.NET, it is not hard to predict that this technology will become the servlet/JSP's main competitor. ASP (and ASP.NET) and servlet/JSP each have their own fans, and it is not easy to predict which one will come out the winner. The most likely outcome is that neither will be an absolute winner that corners the market; instead the technologies will probably run head-to-head in the coming years.

Servlet (and JSP) offers the following benefits that are not necessarily available in other technologies:

Performance. The performance of servlets is superior to CGI because there is no process creation for each client request. Instead, each request is handled by the servlet container process. After a servlet is finished processing a request, it stays resident in memory, waiting for another request.

Portability. Similar to other Java technologies, servlet applications are portable. You can move them to other operating systems without serious hassles.

Rapid development cycle. As a Java technology, servlets have access to the rich Java library, which helps speed up the development process.

Robustness. Servlets are managed by the Java Virtual Machine. As such, you don't need to worry about memory leak or garbage collection, which helps you write robust applications.

Widespread acceptance. Java is a widely accepted technology. This means that numerous vendors work on Java-based technologies. One of the advantages of this

3

widespread acceptance is that you can easily find and purchase components that suit your needs, which saves precious development time.

Servlet Application Architecture

A servlet is a Java class that can be loaded dynamically into and run by a special web server. This servlet-aware web server is called a servlet container, which also was called a servlet engine in the early days of the servlet technology.

Servlets interact with clients via a request-response model based on HTTP. Because servlet technology works on top of HTTP, a servlet container must support HTTP as the protocol for client requests and server responses. However, a servlet container also can support similar protocols, such as HTTPS (HTTP over SSL) for secure transactions.

Figure 1.1

provides the architecture of a servlet application.

Figure 1.1. The servlet application architecture.

In a JSP application, the servlet container is replaced by a JSP container. Both the servlet container and the JSP container often are referred to as the web container or servlet/JSP container, especially if a web application consists of both servlets and JSP pages.

Note

You will learn more about servlet and JSP containers in

Chapter 8 , "JSP Basics."

As you can see in the

Figure 1.1

, a servlet application also can include static content, such as

HTML pages and image files. Allowing the servlet container to serve static content is not preferable because the content is faster if served by a more robust HTTP server, such as the

Apache web server or Microsoft Internet Information Server. As such, it is common practice to put a web server at the front to handle all client requests. The web server serves static content and passes to the servlet containers all client requests for servlets.

Figure 1.2

shows a more common

architecture for a servlet application.

Figure 1.2. The servlet application architecture employing an HTTP server.

Caution

A Java web application architecture employing a J2EE server is different from the

diagrams in Figures 1.1

and 1.2

. This is discussed in

Chapter 28 , "Enterprise JavaBeans."

4

How a Servlet Works

A servlet is loaded by the servlet container the first time the servlet is requested. The servlet then is forwarded the user request, processes it, and returns the response to the servlet container, which in turn sends the response back to the user. After that, the servlet stays in memory waiting for other requests—it will not be unloaded from the memory unless the servlet container sees a shortage of memory. Each time the servlet is requested, however, the servlet container compares the timestamp of the loaded servlet with the servlet class file. If the class file timestamp is more recent, the servlet is reloaded into memory. This way, you don't need to restart the servlet container every time you update your servlet.

The way in which a servlet works inside the servlet container is depicted in the diagram in

Figure

1.3

.

Figure 1.3. How a servlet works.

The Tomcat Servlet Container

A number of servlet containers are available today. The most popular one—and the one recognized as the official servlet/JSP container—is Tomcat. Originally designed by Sun

Microsystems, Tomcat source code was handed over to the Apache Software Foundation in

October 1999. In this new home, Tomcat was included as part of the Jakarta Project, one of the

5

projects of the Apache Software Foundation. Working through the Apache process, Apache, Sun, and other companies—with the help of volunteer programmers worldwide—turned Tomcat into a world-class servlet reference implementation. Two months after the handover, Tomcat version 3.0 was released. Tomcat went through several 3.x releases until version 3.3 was introduced.

The successor of version 3.3 is the current version, version 4.0. The 4.0 servlet container (Catalina) is based on a completely new architecture and has been developed from the ground up for flexibility and performance. Version 4.0 implements the Servlet 2.3 and JSP 1.2 specifications, and it is this version you will be using in this book.

Another popular servlet container is JRun from Allaire Corporation. JRun is available in three editions: Developer, Professional, and Enterprise. The Developer edition is free but not licensed for deployment. The Professional and Enterprise editions grant you the license for deployment with a fee. You can download JRun from http://commerce.allaire.com/download .

Tomcat by itself is a web server. This means that you can use Tomcat to service HTTP requests for servlets, as well as static files (HTML, image files, and so on). In practice, however, since it is faster for non-servlet, non-JSP requests, Tomcat normally is used as a module with another more robust web server, such as Apache web server or Microsoft Internet Information Server. Only requests for servlets or JSP pages are passed to Tomcat.

To write a servlet, you need at least version 1.2 of the Java Development Kit. If you have not already downloaded one, you can download JDK 1.2 from http://java.sun.com/j2se . The reference implementation for both servlets and JSP are not included in J2SE, but they are included in

Tomcat. Tomcat is written purely in Java.

If you haven't yet installed and configured Tomcat, now's the time to do it. If you need help with these tasks, refer to

Appendix A for specific steps.

Six Steps to Running Your First Servlet

After you have installed and configured Tomcat, you can put it into service. Basically, you need to follow six steps to go from writing your servlet to running it. These steps are summarized as follows:

1. Create a directory structure under Tomcat for your application.

2. Write the servlet source code. You need to import the javax.servlet package and the javax.servlet.http package in your source file.

3. Compile your source code.

4. Create a deployment descriptor.

6. Call your servlet from a web browser.

The sections that follow walk you through each of these steps.

Step 1: Create a Directory Structure Under Tomcat

Note

The directory where Tomcat is installed is often referred to as %CATALINA_HOME%.

In previous versions of Tomcat, this directory was called %TOMCAT_HOME%.

6

When you install Tomcat, several subdirectories are automatically created under the Tomcat home directory (%CATALINA_HOME%). One of the subdirectories is webapps. The webapps directory is where you store your web applications. A web application is a collection of servlets and other content installed under a specific subset of the server's URL namespace. A separate directory is dedicated for each servlet application. Therefore, the first thing to do when you build a servlet application is create an application directory. To create a directory structure for an application called myApp, follow these steps:

1. Create a directory called myApp under the webapps directory. The directory name is important because this also appears in the URL to your servlet.

2. Create the and WEB-INF directories under myApp, and create a directory named classes under WEB-INF. The directory structure is shown in

Figure 1.4

. The directory classes

under WEB-INF is for your Java classes. If you have HTML files, put them directly under the myApp directory. You may also want to create a directory called images under myApp for all your image files.

Figure 1.4. Tomcat application directory structure.

Note that the examples, manager, ROOT, tomcat-doc, and webdav directories are for applications that are created automatically when you install Tomcat.

Step 2: Write the Servlet Source Code

In this step, you prepare your source code. You can write the source code yourself using your favorite text editor or copy it from the accompanying CD.

Tip

The source code for all examples in this book are also available on the book's web site.

Check out www.newriders.com

to download the files you need.

The code in

Listing 1.1

shows a simple servlet called TestingServlet. The file is named

TestingServlet.java. The servlet sends a few HTML tags and some text to the browser. For now, don't worry if you haven't got a clue about how it works.

Listing 1.1 TestingServlet.java

import javax.servlet.*; import javax.servlet.http.*;

7

import java.io.*; import java.util.*; public class TestingServlet extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Servlet Testing</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("Welcome to the Servlet Testing Center");

out.println("</BODY>");

out.println("</HTML>");

}

}

Now, save your TestingServlet.java file to the WEB-INF/classes directory under myApp. Placing your source code here will make it inaccessible from a web browser. Static files, such as HTML files and image files, should be placed directly under the myApp directory or a directory under it.

Warning

from a browser.

FL

Y

Placing your source code files outside the WEB-INF directory will make them viewable

For your servlet source code to compile, you need to include the path to the servlet.jar file in your under %CATALINA_HOME%.

TE

For example, if you installed Tomcat under the C:\drive on Windows and you named the install directory tomcat, type the following command from the directory where TestingServlet.java resides. javac -classpath C:\tomcat\common\lib\servlet.jar TestingServlet.java

Alternatively, to save you typing the class path every time you compile your source code, you can add the complete path to the servlet.jar file to your CLASSPATH environment variable. Again, if you have installed Tomcat under C:\and named the install directory tomcat, you must add

C:\tomcat\ common\lib\servlet.jar to the CLASSPATH environment variable. Afterward, you can compile your source by simply typing the following. javac TestingServlet.java

Note

If you have forgotten how to edit the CLASSPATH environment variable, refer to

Appendix A .

Team-Fly ®

If you are using Windows, remember that the new environment variable takes effect only for new console windows. In other words, after changing a new environment variable, open a new console window for typing in your command lines.

Step 4: Create the Deployment Descriptor

A deployment descriptor is an optional component in a servlet application. The descriptor takes the form of an XML document called web.xml and must be located in the WEB-INF directory of the servlet application. When present, the deployment descriptor contains configuration settings specific to that application. Deployment descriptors are discussed in detail in

Chapter 16 .

To create the deployment descriptor, you now need to create a web.xml file and place it under the

WEB-INF directory under myApp.

The web.xml for this example application must have the following content.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>Testing</servlet-name>

<servlet-class>TestingServlet</servlet-class>

</servlet>

</web-app>

The web.xml file has one element—web-app. You should write all your servlets under <web-app>.

For each servlet, you have a <servlet> element and you need the <servlet-name> and <servletclass> elements. The <servlet-name> is the name for your servlet, by which it is known Tomcat.

The <servlet-class> is the compiled file of your servlet without the .class extension.

Having more than one servlet in an application is very common. For every servlet, you need a

<servlet> element in the web.xml file. For example, the following shows you how web.xml looks if you add another servlet called Login:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>Testing</servlet-name>

<servlet-class>TestingServlet</servlet-class>

</servlet>

<servlet>

<servlet-name>Login</servlet-name>

<servlet-class>LoginServlet</servlet-class>

</servlet>

</web-app>

Step 5: Run Tomcat

9

If Tomcat is not already running, you need to start it. See

Appendix A for information on how to

start or run Tomcat.

Step 6: Call Your Servlet from a Web Browser

Now, you can call your servlet from a web browser. By default, Tomcat runs on port 8080 in the myApp virtual directory under the servlet subdirectory. The servlet that you wrote in the preceding steps is named Testing. The URL for that servlet has the following format: http://domain-name/virtual-directory/servlet/servlet-name

Any static file can be accessed using the following URL: http://domain-name/virtual-directory/staticFile.html

For example, a Logo.gif file under the myApp/images/ directory can be accessed using the following URL. http://domain-name/virtual-directory/images/Logo.gif

If you run the web browser from the same computer as Tomcat, you can replace the domain-name part with "localhost". In that case, the URL for your servlet is http://localhost:8080/myApp/servlet/Testing

In the deployment descriptor you wrote in Step 4, you actually mapped the servlet class file called

TestingServlet with the name "Testing," so that your servlet can be called by specifying its class file (TestingServlet) or its name (Testing). Without a deployment descriptor, you must call the servlet by specifying its class name; that is, TestingServlet. This means that if you did not write a deployment descriptor in Step 4, you need to use the following URL to call your servlet: http://localhost:8080/myApp/servlet/TestingServlet

Typing the URL in the Address or Location box of your web browser will give you the string

"Welcome to the Servlet Testing Center," as shown in

Figure 1.5

.

Figure 1.5. The Testing servlet.

10

Congratulations. You have just written your first servlet.

If you don't want to type the port number each time, you can change the default port of Tomcat so that it runs on port 80, the default port for a web server. (Details on how to change the port number can be found in

Appendix A .) However, the rest of the book will use Tomcat's default port

8080.

Note

You will find code for various servlets in this chapter and the next. To run each individual servlet, you need to repeat these six steps. To avoid repetition, I do not mention these steps for every servlet presented in this book. You don't need to worry about these steps if you are using a Java development tool, such as Borland's JBuilder or IBM's VisualAge, because those steps are taken care of by the RAD program.

Summary

This chapter has given you the big picture of how to build a servlet application. Specifically, you learned about the benefits of servlets, explored servlet application architecture, and discovered how a servlet works inside the servlet container. You also have been shown how to configure

Tomcat and followed the six steps you need to build your own servlets. The next chapter digs deeper into the servlet technology by presenting the Java Servlet specification Application

Programming Interface (API) version 2.3

11

Chapter 2. Inside Servlets

Watching your servlet in action, as you did in Chapter 1 , "The Servlet Technology," should bring

you confidence. And, as some people say, having confidence is half the battle in learning anything.

To be an expert, however, you need to understand the nuts and bolts of the Java Servlet specification Application Programming Interface (API). This book has been written using the latest release of the servlet specification API—version 2.3. Two packages are available for servlet programmers: javax.servlet and javax.servlet.http. The first one contains basic classes and interfaces that you can use to write servlets from the scratch. The second package, javax.servlet.http, offers more advanced classes and interfaces that extend classes and interfaces from the first package. It is much more convenient to program using the second package.

When you learn something, it is best to start with the basics and build a strong foundation. For example, understanding the javax.servlet.Servlet interface is very important because it encapsulates the life cycle methods of a servlet and it is the interface that all servlets must implement. You also need to know the servlet's context, which represents a servlet's environment, and the servlet's configuration. Because of the importance of these items, this chapter introduces you to members of the javax.servlet package. In this chapter, you also will see that oftentimes several ways exist to do the same thing.

After a few examples, I will introduce you to the GenericServlet class, a member of the javax.servlet package that acts as a wrapper for the javax.servlet.Servlet interface. Extending this class makes your code simpler because you need to provide implementations only for methods that you need to use.

To run each example in this chapter, you need to compile the source code and copy the resulting class file into the classes directory under the WEB-INF directory of your application. Refer to

Chapter 1 if you have forgotten the six steps you need to run your servlet.

The rest of this chapter explains and uses the interfaces and classes of the javax.servlet package.

The chapters that follow focus more on the second package.

The javax.servlet Package

The javax.servlet package contains seven interfaces, three classes, and two exceptions. Instead of using the conventional approach by explaining each interface and class in alphabetical order—thus making the book feel like a dictionary—I present the discussions based on functions and offer examples that demonstrate each function.

Nevertheless, mastering all the members of this package is important. To help you, a complete reference is given in

Appendix B , "The javax.servlet Package Reference."

The seven interfaces are as follows:

RequestDispatcher

Servlet

ServletConfig

ServletContext

ServletRequest

ServletResponse

SingleThreadModel

12

The three classes are as follows:

GenericServlet

ServletInputStream

ServletOutputStream

And, finally, the exception classes are these:

ServletException

UnavailableException

The object model of the javax.servlet package is shown in

Figure 2.1

.

Figure 2.1. The javax.servlet package object model.

A Servlet's Life Cycle

Let there be servlet. This interface in the javax.servlet package is the source of all activities in servlet programming. Servlet is the central abstraction of the Java servlet technology. Every servlet you write must implement this javax.servlet.Servlet interface, either directly or indirectly.

The life cycle of a servlet is determined by three of its methods: init, service, and destroy.

The init() Method

The init method is called by the servlet container after the servlet class has been instantiated. The servlet container calls this method exactly once to indicate to the servlet that the servlet is being placed into service. The init method must complete successfully before the servlet can receive any requests.

You can override this method to write initialization code that needs to run only once, such as loading a database driver, initializing values, and so on. In other cases, you normally leave this method blank.

The signature of this method is as follows:

13

public void init(ServletConfig config) throws ServletException

The init method is important also because the servlet container passes a ServletConfig object, which contains the configuration values stated in the web.xml file for this application. More on

ServletConfig can be found later in this chapter, in the section, " Obtaining Configuration

Information ."

This method also can throw a ServletException. The servlet container cannot place the servlet into service if the init method throws a ServletException or the method does not return within a time period defined by the web server.

Note

ServletException is the most important exception in servlet programming. In fact, a lot of methods in the javax.servlet and javax.servlet.http packages can throw this exception when a problem exists in a servlet.

The service() Method

The service method is called by the servlet container after the servlet's init method to allow the servlet to respond to a request.

Servlets typically run inside multithreaded servlet containers that can handle multiple requests concurrently. Therefore, you must be aware to synchronize access to any shared resources, such as files, network connections, and the servlet's class and instance variables. For example, if you open a file and write to that file from a servlet, you need to remember that a different thread of the same

servlet also can open the same file. See the section, " Creating Thread-Safe Servlets ," for more on

the topic of multithreading and synchronization.

This method has the following signature: public void service(ServletRequest request, ServletResponse response)

throws ServletException, java.io.IOException

The servlet container passes a ServletRequest object and the ServletResponse object. The

ServletRequest object contains the client's request and the ServletResponse contains the servlet's response. These two objects are important because they enable you to write custom code that determines how the servlet services the client request.

The service method throws a ServletException if an exception occurs that interferes with the servlet's normal operation. The service method also can throw a java.io.IOException if an input or output exception occurs during the execution of this method.

As the name implies, the service method exists so that you can write code that makes the servlet function the way it is supposed to.

The destroy() Method

The servlet container calls the destroy method before removing a servlet instance from service.

This normally happens when the servlet container is shut down or the servlet container needs some free memory.

This method is called only after all threads within the servlet's service method have exited or after a timeout period has passed. After the servlet container calls this method, it will not call the service method again on this servlet.

14

The destroy method gives the servlet an opportunity to clean up any resources that are being held

(for example, memory, file handles, and threads) and make sure that any persistent state is synchronized with the servlet's current state in memory.

The signature of this method is as follows: public void destroy()

Demonstrating the Life Cycle of a Servlet

Listing 2.1

contains the code for a servlet named PrimitiveServlet, a very simple servlet that exists

to demonstrate the life cycle of a servlet. The PrimitiveServlet class implements javax.servlet.Servlet (as all servlets must) and provides implementations for all the five methods of servlet. What it does is very simple. Each time any of the init, service, or destroy methods is called, the servlet writes the method's name to the console.

Listing 2.1 PrimitiveServlet.java

import javax.servlet.*; import java.io.IOException; public class PrimitiveServlet implements Servlet {

public void init(ServletConfig config) throws ServletException {

System.out.println("init");

}

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

System.out.println("service");

}

public void destroy() {

System.out.println("destroy");

}

public String getServletInfo() {

return null;

}

public ServletConfig getServletConfig() {

return null;

}

}

After you compile the source code into the myApp\WEB-INF\classes directory, add the servlet to the web.xml under the name Primitive, as shown in

Listing 2.2

.

Listing 2.2 The web.xml File for PrimitiveServlet

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

15

<servlet-name>Primitive</servlet-name>

<servlet-class>PrimitiveServlet</servlet-class>

</servlet>

</web-app>

You should then be able to call this servlet from your browser by typing the following URL: http://localhost:8080/myApp/servlet/Primitive

The first time the servlet is called, the console displays these two lines: init service

This tells you that the init method is called, followed by the service method. However, on subsequent requests, only the service method is called. The servlet adds the following line to the console: service

This proves that the init method is called only once.

What are the getServletInfo and getServletConfig doing in Listing 2.1

? Nothing. They can be

useful, but in the PrimitiveServlet class, they are just there to meet the specification that a class must provide implementations for all methods in the interface it implements.

You can return any string in the getServletInfo method, such as your company name or the author name or other information deemed necessary. Other people might extend your servlet class and might want to know what useful information the designer of the servlet has provided.

The getServletConfig is more important. We will see how it can be of use next.

Obtaining Configuration Information

The servlet specification allows you to configure your application. You'll find more information on this topic in the discussion of the deployment descriptor in

Chapter 16 , "Application

Deployment." In this chapter, I present an example that demonstrates how you can retrieve configuration information from the application web.xml file.

Note

You need to restart Tomcat for the changes in the deployment descriptor (the web.xml file) to take effect.

For each servlet registered in the web.xml file, you have the option of specifying a set of initial parameter name/value pairs that you can retrieve from inside the servlet. The following web.xml file contains a servlet called ConfigDemo whose class is named ConfigDemoServlet.class. The servlet has two initial parameter name/value pairs. The first parameter is named adminEmail and its value is [email protected]

. The second parameter is named adminContactNumber and the value for this parameter is 04298371237.

<?xml version="1.0" encoding="ISO-8859-1"?>

16

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">

<web-app>

<servlet>

<servlet-name>ConfigDemo</servlet-name>

<servlet-class>ConfigDemoServlet</servlet-class>

<init-param>

<param-name>adminEmail</param-name>

<param-value>[email protected]</param-value>

</init-param>

<init-param>

<param-name>adminContactNumber</param-name>

<param-value>04298371237</param-value>

</init-param>

</servlet>

</web-app>

Why would you want to use an initial parameter? For practicality. Hardcoding information in the servlet code means that you have to recompile the servlet if the information changes. A web.xml file is plain text. You can edit its content easily using a text editor.

The code that retrieves the initial parameter name and values is given in

Listing 2.3

.

To retrieve initial parameters, you need the ServletConfig object passed by the servlet container to the servlet. After you get the ServletConfig object, you then can use its getInitParameterNames and getInitParameter methods. The getInitParameterNames does not take an argument and returns an Enumeration containing all the parameter names in the ServletConfig object. The getInitParameter takes a String containing the parameter name and returns a String containing the value of the parameter.

Because the servlet container passes a ServletConfig object to the init method, it is easiest to write the code in the init method. The code in

Listing 2.3

loops through the Enumeration object called

parameters that is returned from the getInitParameterNames method. For each parameter, it outputs the parameter name and value. The parameter value is retrieved using the getInitParameter method.

Listing 2.3 Retrieving Initial Parameters

import javax.servlet.*; import java.util.Enumeration; import java.io.IOException; public class ConfigDemoServlet implements Servlet {

public void init(ServletConfig config) throws ServletException {

Enumeration parameters = config.getInitParameterNames();

while (parameters.hasMoreElements()) {

String parameter = (String) parameters.nextElement();

System.out.println("Parameter name : " + parameter);

System.out.println("Parameter value : " +

config.getInitParameter(parameter));

}

}

public void destroy() {

}

17

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

}

public String getServletInfo() {

return null;

}

public ServletConfig getServletConfig() {

return null;

}

}

The output of the code in the console is as follows:

Parameter name : adminContactNumber

Parameter value : 04298371237

Parameter name : adminEmail

Parameter value : [email protected]

Preserving the ServletConfig

The code in

Listing 2.3

FL

Y you need to preserve the ServletConfig object to a class level variable. This task is not difficult. by the servlet container in the init method.

AM

Listing 2.4

variable for the ServletConfig object.

TE

ServletConfig servletConfig;

Then, in the init method, you write the following code: servletConfig = config;

Now the servletConfig variable references the ServletConfig object returned by the servlet container. The getServletConfig method is provided to do just that: return the ServletConfig object. public ServletConfig getServletConfig() {

return servletConfig;

}

If you extend the ReserveConfigServlet class, you can still retrieve the ServlerConfig object by calling the getServletConfig method.

Listing 2.4 Preserving the ServletConfig Object

import javax.servlet.*; import java.io.IOException;

Team-Fly ®

public class ReserveConfigServlet implements Servlet {

ServletConfig servletConfig;

public void init(ServletConfig config) throws ServletException {

servletConfig = config;

}

public void destroy() {

}

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

}

public String getServletInfo() {

return null;

}

public ServletConfig getServletConfig() {

return servletConfig;

}

}

The Servlet Context

In servlet programming, the servlet context is the environment where the servlet runs. The servlet container creates a ServletContext object that you can use to access information about the servlet's environment.

A servlet also can bind an object attribute into the context by name. Any object bound into a context is available to any other servlet that is part of the same web application.

How do you obtain the ServletContext object? Indirectly, from the ServletConfig object passed by the servlet container to the servlet's init method. The ServletConfig interface has a method called getServletContext that returns the ServletContext object. You then can use the ServletContext interface's various methods to get the information you need. These methods include the following:

getMajorVersion. This method returns an integer representing the major version for the servlet API that the servlet container supports. If the servlet container supports the servlet

API version 2.3, this method will return 2.

getMinorVersion. This method returns an integer representing the minor version of the servlet API that the servlet container supports. For the servlet API version 2.3, this method will return 3.

getAttributeNames. This method returns an enumeration of strings representing the names of the attributes currently stored in the ServletContext.

getAttribute. This method accepts a String containing the attribute name and returns the object bound to that name.

setAttribute. This method stores an object in the ServletContext and binds the object to the given name. If the name already exists in the ServletContext, the old bound object will be replaced by the object passed to this method.

19

removeAttribute. This method removes from the ServletContext the object bound to a name. The removeAttribute method accepts one argument: the name of the attribute to be removed.

The code in

Listing 2.5

shows a servlet named ContextDemoServlet that retrieves some of the

servlet context information, including attribute names and values, minor and major versions of the servlet container, and the server info.

Listing 2.5 Retrieving Servlet Context Information

import javax.servlet.*; import java.util.Enumeration; import java.io.IOException; public class ContextDemoServlet implements Servlet {

ServletConfig servletConfig;

public void init(ServletConfig config) throws ServletException {

servletConfig = config;

}

public void destroy() {

}

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

ServletContext servletContext = servletConfig.getServletContext();

Enumeration attributes = servletContext.getAttributeNames();

while (attributes.hasMoreElements()) {

String attribute = (String) attributes.nextElement();

System.out.println("Attribute name : " + attribute);

System.out.println("Attribute value : " +

servletContext.getAttribute(attribute));

}

System.out.println("Major version : " + servletContext.getMajorVersion());

System.out.println("Minor version : " + servletContext.getMinorVersion());

System.out.println("Server info : " + servletContext.getServerInfo());

}

public String getServletInfo() {

return null;

}

public ServletConfig getServletConfig() {

return null;

}

}

The output of the code is as follows. This output may be different on your computer, depending on the version of Tomcat you are using, the operating system, and so on.

Attribute name : javax.servlet.context.tempdirAttribute value :

..\work\localhost\myApp

Attribute name : org.apache.catalina.resources

20

Attribute value : [email protected]

Attribute name : org.apache.catalina.WELCOME_FILES

Attribute value : [Ljava.lang.String;@2bb7e0

Attribute name : org.apache.catalina.jsp_classpath

Attribute value : C:\tomcat4\webapps\myApp\WEB-INF\classes;

.

.

.

Major version : 2

Minor version : 3

Server info : Apache Tomcat/4.0-b5

Sharing Information Among Servlets

For some applications, you want to make certain types of information available to all the servlets.

You can share this information—such as a database connection string or a page count—among the servlets by using attributes in the ServletContext object.

The following example uses two servlets: AttributeSetterServlet and DisplayAttributesServlet.

The AttributeSetterServlet servlet, shown in

Listing 2.6

, binds the name password to a String

object containing the word "ding-dong". The servlet does this by first obtaining the ServletContext object from the ServletConfig object passed by the servlet container to the init method. Then the servlet uses the setAttribute method to bind "password" with "ding-dong".

Listing 2.6 The AttributeSetterServlet

import javax.servlet.*; import java.io.IOException; public class AttributeSetterServlet implements Servlet {

public void init(ServletConfig config) throws ServletException {

// bind an object that is to be shared among other servlets

ServletContext servletContext = config.getServletContext();

servletContext.setAttribute("password", "dingdong");

}

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

}

public void destroy() {

}

public String getServletInfo() {

return null;

}

public ServletConfig getServletConfig() {

return null;

}

}

21

The code in Listing 2.7

is the servlet that retrieves all attribute name/value pairs in the

ServletContext object. The init method of this servlet preserves the ServletConfig object into servletConfig. The service method then uses the ServletConfig interface's getServletContext method to obtain the ServletContext object. After you get the ServletContext object, you can then use its getAttributeNames method to get an Enumeration of all attribute names and loop through it to obtain each attribute's value, which it outputs to the console along with the attribute name.

Listing 2.7 DisplayAttributesServlet

import javax.servlet.*; import java.io.IOException; import java.util.Enumeration; public class DisplayAttributesServlet implements Servlet {

ServletConfig servletConfig;

public void init(ServletConfig config) throws ServletException {

servletConfig = config;

}

public void destroy() {

}

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

ServletContext servletContext = servletConfig.getServletContext();

Enumeration attributes = servletContext.getAttributeNames();

while (attributes.hasMoreElements()) {

String attribute = (String) attributes.nextElement();

System.out.println("Attribute name : " + attribute);

System.out.println("Attribute value : " +

servletContext.getAttribute(attribute));

}

}

public String getServletInfo() {

return null;

}

public ServletConfig getServletConfig() {

return null;

}

}

Enumeration attributes = servletContext.getAttributeNames();

while (attributes.hasMoreElements()) {

String attribute = (String) attributes.nextElement();

System.out.println("Attribute name : " + attribute);

System.out.println("Attribute value : " +

servletContext.getAttribute(attribute));

}

To see the servlets work, first you need to call the AttributeSetterServlet servlet to set the attribute

"password". You then call the DisplayAttributesServlet to get an Enumeration of the names of all attributes and display the values.

The output is given here:

22

Attribute name : javax.servlet.context.tempdir

Attribute value :

C:\123data\JavaProjects\JavaWebBook\work\localhost_8080

Attribute name : password

Attribute value : dingdong

Attribute name : sun.servlet.workdir

Attribute value :

C:\123data\JavaProjects\JavaWebBook\work\localhost_8080

Requests and Responses

Requests and responses are what a web application is all about. In a servlet application, a user using a web browser sends a request to the servlet container, and the servlet container passes the request to the servlet.

In a servlet paradigm, the user request is represented by the ServletRequest object passed by the servlet container as the first argument to the service method. The service method's second argument is a ServletResponse object, which represents the response to the user.

The ServletRequest Interface

The ServletRequest interface defines an object used to encapsulate information about the user's request, including parameter name/value pairs, attributes, and an input stream.

The ServletRequest interface provides important methods that enable you to access information about the user. For example, the getParameterNames method returns an Enumeration containing the parameter names for the current request. To get the value of each parameter, the

ServletRequest interface provides the getParameter method.

The getRemoteAddress and getRemoteHost methods are two methods that you can use to retrieve the user's computer identity. The first returns a string representing the IP address of the computer the client is using, and the second method returns a string representing the qualified host name of the computer.

The following example, shown in Listings

2.8

and

2.9

, shows a ServletRequest object in action.

The example consists of an HTML form in a file named index.html that you need to put in the application directory—that is, under myApp—and a servlet called RequestDemoServlet.

Listing 2.8 index.html

<HTML>

<HEAD>

<TITLE>Sending a request</TITLE>

</HEAD>

<BODY>

<FORM ACTION=servlet/RequestDemoServlet METHOD="POST">

<BR><BR>

Author: <INPUT TYPE="TEXT" NAME="Author">

<INPUT TYPE="SUBMIT" NAME="Submit">

<INPUT TYPE="RESET" VALUE="Reset">

</FORM>

</BODY>

</HTML>

23

Listing 2.9 RequestDemoServlet

import javax.servlet.*; import java.util.Enumeration; import java.io.IOException; public class RequestDemoServlet implements Servlet {

public void init(ServletConfig config) throws ServletException {

}

public void destroy() {

}

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

System.out.println("Server Port: " + request.getServerPort());

System.out.println("Server Name: " + request.getServerName());

System.out.println("Protocol: " + request.getProtocol());

System.out.println("Character Encoding: " +

request.getCharacterEncoding());

System.out.println("Content Type: " + request.getContentType());

System.out.println("Content Length: " + request.getContentLength());

System.out.println("Remote Address: " + request.getRemoteAddr());

System.out.println("Remote Host: " + request.getRemoteHost());

System.out.println("Scheme: " + request.getScheme());

Enumeration parameters = request.getParameterNames();

while (parameters.hasMoreElements()) {

String parameterName = (String) parameters.nextElement();

System.out.println("Parameter Name: " + parameterName);

System.out.println("Parameter Value: " +

request.getParameter(parameterName));

}

Enumeration attributes = request.getAttributeNames();

while (attributes.hasMoreElements()) {

String attribute = (String) attributes.nextElement();

System.out.println("Attribute name: " + attribute);

System.out.println("Attribute value: " +

request.getAttribute(attribute));

}

}

public String getServletInfo() {

return null;

}

public ServletConfig getServletConfig() {

return null;

}

}

To run the example, first request the index.html file by using the following URL: http://localhost:8080/myApp/index.html

Figure 2.2

shows the index.html file in which "haywood" has been typed in as the value for author.

24

Figure 2.2. The index.html file.

When you submit the form, you should see the list of attribute names and values in your console.

The ServletResponse Interface

The ServletResponse interface represents the response to the user. The most important method of this interface is getWriter, from which you can obtain a java.io.PrintWriter object that you can use to write HTML tags and other text to the user.

The code in Listings

2.10

and

2.11

offer an HTML file named index2.html and a servlet whose

service method is overridden with code that outputs some HTML tags to the user. This servlet

modifies the example in Listings 2.8

and

2.9

that retrieves various information about the user.

Instead of sending the information to the console, the service method sends it back to the user.

Note that the code in

Listing 2.10

is similar to the code in

Listing 2.8

, except that in

Listing 2.10

the value for the form's ACTION attribute is servlet/ResponseDemoServlet.

Listing 2.10 index2.html

<HTML>

<HEAD>

<TITLE>Sending a request</TITLE>

</HEAD>

<BODY>

<FORM ACTION=servlet/ResponseDemoServlet METHOD="POST">

<BR><BR>

Author: <INPUT TYPE="TEXT" NAME="Author">

<INPUT TYPE="SUBMIT" NAME="Submit">

<INPUT TYPE="RESET" VALUE="Reset">

</FORM>

</BODY>

25

</HTML>

Listing 2.11 The ResponseDemoServlet

import javax.servlet.*; import java.io.PrintWriter; import java.io.IOException; import java.util.Enumeration; public class ResponseDemoServlet implements Servlet {

public void init(ServletConfig config) throws ServletException {

}

public void destroy() {

}

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>");

out.println("ServletResponse");

out.println("</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<B>Demonstrating the ServletResponse object</B>");

out.println("<BR>");

out.println("<BR>Server Port: " + request.getServerPort());

out.println("<BR>Server Name: " + request.getServerName());

out.println("<BR>Protocol: " + request.getProtocol());

out.println("<BR>Character Encoding: " + request.getCharacterEncoding());

out.println("<BR>Content Type: " + request.getContentType());

out.println("<BR>Content Length: " + request.getContentLength());

out.println("<BR>Remote Address: " + request.getRemoteAddr());

out.println("<BR>Remote Host: " + request.getRemoteHost());

out.println("<BR>Scheme: " + request.getScheme());

Enumeration parameters = request.getParameterNames();

while (parameters.hasMoreElements()) {

String parameterName = (String) parameters.nextElement();

out.println("<br>Parameter Name: " + parameterName);

out.println("<br>Parameter Value: " +

request.getParameter(parameterName));

}

Enumeration attributes = request.getAttributeNames();

while (attributes.hasMoreElements()) {

String attribute = (String) attributes.nextElement();

out.println("<BR>Attribute name: " + attribute);

out.println("<BR>Attribute value: " + request.getAttribute(attribute));

}

out.println("</BODY>");

out.println("</HTML>");

}

public String getServletInfo() {

return null;

26

}

public ServletConfig getServletConfig() {

return null;

}

}

To run the example, first request the index2.html file by using the following URL: http://localhost:8080/myApp/index2.html

Figure 2.3

shows the index2.html file in which "haywood" has been typed in as the value for author.

Figure 2.3. The index2.html file.

When you submit the form, the ResponseDemoServlet is invoked and your browser should display an image similar to

Figure 2.4

.

Figure 2.4. Utilizing the ServletResponse object.

27

The GenericServlet Wrapper Class

FL

Y javax.servlet.Servlet interface. Everything works fine, but there are two annoying things that you've probably noticed: though most of the time you only need one. This makes your code look unnecessarily complicated.

2. The ServletConfig object is passed to the init method. You need to preserve this object to use it from other methods. This is not difficult, but it means extra work.

The javax.servlet package provides a wrapper class called GenericServlet that implements two important interfaces from the javax.servlet package: Servlet and ServletConfig, as well as the java.io.Serializable interface. The GenericServlet class provides implementations for all methods, most of which are blank. You can extend GenericServlet and override only methods that you need to use. Clearly, this looks like a better solution.

The code in

Listing 2.12

is a servlet called SimpleServlet that extends GenericServlet. The code

provides the implementation of the service method that sends some output to the browser. Because the service method is the only method you need, only this method needs to appear in the class.

Compared to all servlet classes that implement the javax.servlet.Servlet interface directly,

SimpleServlet looks much cleaner and clearer.

Listing 2.12 Extending GenericServlet

import javax.servlet.*; import java.io.IOException; import java.io.PrintWriter;

Team-Fly ®

public class SimpleServlet extends GenericServlet {

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>");

out.println("Extending GenericServlet");

out.println("</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("Extending GenericServlet makes your code simpler.");

out.println("</BODY>");

out.println("</HTML>");

}

}

The output from the SimpleServlet servlet is shown in Figure 2.5

.

Figure 2.5. Extending GenericServlet.

Creating Thread-Safe Servlets

A servlet container allows multiple requests for the same servlet by creating a different thread to service each request. In many cases, each thread deals with its own ServletRequest and

ServletResponse objects that are isolated from other threads. Problems start to arise, however,

29

when your servlet needs to access an external resource. To understand the problem introduced by multithreaded servlets, consider the following "playing dog" illustration.

Imagine a servlet accessing an external resource as a dog who enjoys moving tennis balls from one box to another. Each box can hold ten balls, no matter how the balls are arranged. The boxes and the balls are an external resource to the dog. To play, the dog needs two boxes and ten balls.

Initially, those ten balls are placed in the first box. The dog moves all balls from the first box to the second, one ball at a time. The dog is smart enough to count to ten. Therefore, it knows when it's finished.

Now imagine a second thread of the same servlet as a second dog that plays the same game.

Because there are only two boxes and ten balls for both dogs, the two dogs share the same

"external resource." The game goes like this:

1. The first dog starts first (the servlet receives a call from a user).

2. After the first dog moves three balls, the second dog starts to play (the servlet is invoked by the second user). What will happen?

The two dogs sharing the same balls are illustrated in

Figure 2.6

.

Figure 2.6. Understanding multi-threaded code.

The first dog and the second dog will not find enough balls to finish the game, and both will be confused.

If somehow the second dog can be queued to wait to start until the first dog finishes, however, the two dogs are happy.

That's what happens when two threads of the same servlet need to access an external resource, such as opening a file and writing to it. Consider the following example, which reflects a realworld situation.

The code in

Listing 2.13

presents a page counter servlet. What it does is simple. The servlet

overrides the service method to do the following:

1. Open the counter.txt file using a BufferedReader, read the number into a counter, and close the file.

2. Increment the counter.

3. Write the counter back to the counter.txt file.

4. Display the counter in the web browser.

30

Imagine what happens if there are two users, Boni and Bulbul, who request the servlet. First Boni requests it, and then a couple of nanoseconds after Boni, Bulbul requests the same servlet. The scenario probably looks like this:

1. The service method executes Steps 1 and 2, and then gets distracted by the other request.

2. The method then does Step 1 from Bulbul before continuing to do Step 3 and 4 for Boni.

What happens next? Boni and Bulbul get the same number, which is not how it is supposed to be.

The servlet has produced an incorrect result. As you can see in

Listing 2.13

, the servlet is an

unsafe multithreaded servlet.

Listing 2.13 Unsafe Multi-Threaded Servlet

import javax.servlet.*; import java.io.*; public class SingleThreadedServlet extends GenericServlet

{

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

int counter = 0;

// get saved value

try {

BufferedReader reader = new BufferedReader(

new FileReader("counter.txt"));

counter = Integer.parseInt( reader.readLine() );

reader.close();

}

catch (Exception e) {

}

// increment counter

counter++;

// save new value

try {

BufferedWriter writer = new BufferedWriter(

new FileWriter("counter.txt"));

writer.write(Integer.toString(counter));

writer.close();

}

catch (Exception e) {

}

try {

PrintWriter out = response.getWriter();

out.println("You are visitor number " + counter);

}

catch (Exception e) {

}

}

}

To solve the problem, remember the solution to the "playing dog" illustration: When the second dog waited until the first dog finished playing, both dogs could complete the game successfully.

31

This is exactly how you solve the problem in a servlet needing to service two users at the same time: by making the second user wait until the first servlet finishes serving the first user. This solution makes the servlet single-threaded.

This solution is very easy to do because of the marker SingleThreadedServlet interface. You don't need to change your code; you need only to implement the interface.

The code in

Listing 2.14

is the modification of the code in

Listing 2.13

. Nothing changes, except

that the SingleThreadedServlet class now implements SingleThreadModel, making it thread safe.

Listing 2.14 Safe Multi-Threaded Servlet

import javax.servlet.*; import java.io.*; public class SingleThreadedServlet extends GenericServlet

implements SingleThreadModel {

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

int counter = 0;

// get saved value

try {

BufferedReader reader = new BufferedReader(

new FileReader("counter.txt"));

counter = Integer.parseInt( reader.readLine() );

reader.close();

}

catch (Exception e) {

}

// increment counter

counter++;

// save new value

try {

BufferedWriter writer = new BufferedWriter(

new FileWriter("counter.txt"));

writer.write(Integer.toString(counter));

writer.close();

}

catch (Exception e) {

}

try {

PrintWriter out = response.getWriter();

out.println("You are visitor number " + counter);

}

catch (Exception e) {

}

}

}

Now, if a user requests the service of the servlet while the servlet is servicing another user, the user who comes later will have to wait.

32

If you want to experience erroneous multi-threading yourself, the code in

Listing 2.15

provides the

SingleThreadedServlet with a delay of 6 seconds. Open two browsers and request the same servlet quickly. Notice that you get the same number for both browsers.

Listing 2.15 Demonstrating an Unsafe Multi-Threaded Servlet

import javax.servlet.*; import java.io.*; public class SingleThreadedServlet extends GenericServlet {

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException {

int counter = 0;

// get saved value

try {

BufferedReader reader = new BufferedReader(

new FileReader("counter.txt"));

counter = Integer.parseInt( reader.readLine() );

reader.close();

}

catch (Exception e) {

}

// increment counter

counter++;

// delay for 6 seconds to make observation possible

try {

Thread thread = new Thread();

thread.sleep(6000);

}

catch (InterruptedException e) {

}

// saved new value

try {

BufferedWriter writer = new BufferedWriter(

new FileWriter("counter.txt"));

writer.write(Integer.toString(counter));

writer.close();

}

catch (Exception e) {

}

try {

PrintWriter out = response.getWriter();

out.println("You are visitor number " + counter);

}

catch (Exception e) {

}

}

}

Warning

33

The code in Listing 2.15

might give you an unexpected result because implementing the

SingleThreadModel interface only guarantees that no two threads will concurrently execute the service () method within the same servlet instance. Since the servlet container may instantiate multiple instances of a servlet class to handle a heavy request load, the SingleThreadModel interface is left useless.

What the code does is simple: It opens the counter.txt file, reads the value, increments the value, and writes the incremented value back to the file.

However, between the line of code that increments the value and the line of code that writes the incremented value back to the user, we inserted the following code: try {

Thread thread = new Thread();

thread.sleep(6000);

} catch (InterruptedException e) {

}

Now you have time to request the same servlet from the second browser. The value shown in both browsers will be the same if the second request comes before the first thread of the servlet has the time to update the value in the counter.txt file.

An inexperienced programmer would wonder whether a good solution might be to make every servlet implement the SingleThreadModel interface. The answer is no. If a servlet never accesses an external resource, queuing the second request will create unnecessary delay to the subsequent user after the first. Also, if the external resource is accessed but there is no need to update its value, you don't need to implement the SingleThreadModel interface. For example, if the service method of a servlet needs only to read a static value from a file, you can let multiple threads of the servlet open and read the file at the same time.

Summary

This chapter introduced you to most of the interfaces and classes of the javax.servlet package, one of the two packages provided for servlet programming. This package contains basic classes and interfaces that are extended by members of the second package: javax.servlet.http. Understanding the basic classes and interfaces in javax.servlet is important, even though you use them less often than the javax.servlet.http package members in real-world applications. This chapter also showed you how to implement the SingleThreadModel interface to solve the problem multi-threaded servlets can have when accessing the same external resource.

The next chapter shows you how to write servlets that use the members of the second Servlet API package, javax.servlet.http.

34

Chapter 3. Writing Servlet Applications

In the previous chapters, you have learned how to write servlets, run them in the servlet container, and invoke them from a web browser. You also have studied various classes and interfaces in the javax.servlet package and learned how to solve the problem introduced by a multi-threaded servlet.

When you are programming servlets, however, you will work with another package called javax.servlet.http. The classes and interfaces in this package derive from those in javax.servlet; however, the members of the javax.servlet.http package are much richer and more convenient to use. In this package, the HttpServlet class represents a servlet, extending javax.servlet.GenericServlet and bringing a great number of methods of its own. The javax.servlet.http package also has interfaces that are equivalent to javax.servlet.ServletRequest and javax.servlet.ServletResponse interfaces—the HttpServletRequest and the

HttpServletResponse, respectively. It is not a coincidence that HttpServletRequest extends the javax.servlet.ServletRequest interface, and HttpServletResponse is derived from the javax.servlet.ServletResponse interface.

Additional classes exist that are not available in the javax.servlet package. For example, you can use a class called Cookie to work with cookies. In addition, you will find session-related methods in the HttpServlet class that enable you to deal with user sessions. Both cookies and sessions are explained in detail in

Chapter 5 , "Session Management."

Let's now begin with an overview of the HttpServlet class, a class that you almost always extend when developing servlets.

The HttpServlet Class

As mentioned previously, the HttpServlet class extends the javax.servlet.GenericServlet class. The

HttpServlet class also adds a number of interesting methods for you to use. The most important are the six doxxx methods that get called when a related HTTP request method is used. The six methods are doPost, doPut, doGet, doDelete, doOptions and doTrace. Each doxxx method is invoked when a corresponding HTTP method is used. For instance, the doGet method is invoked when the servlet receives an HTTP request that was sent using the GET method.

Note

If you are familiar with the HTTP 1.1 protocol, you will notice that the HEAD method does not have a corresponding do method in the servlet. You are right. Actually, there is a doHead method in the HttpServlet class, but it is a private method.

Of the six doxxx methods, the doPost and the doGet methods are the most frequently used.

The doPost method is called when the browser sends an HTTP request using the POST method.

The POST method is one of the two methods that can be used by an HTML form. Consider the following HTML form at the client side:

<FORM ACTION="Register" METHOD="POST">

<INPUT TYPE=TEXT Name="firstName">

<INPUT TYPE=TEXT Name="lastName">

<INPUT TYPE=SUBMIT>

</FORM>

35

When the user clicks the Submit button to submit the form, the browser sends an HTTP request to the server using the POST method. The web server then passes this request to the Register servlet and the doPost method of the servlet is invoked. Using the POST method in a form, the parameter name/value pairs of the form are sent in the request body. For example, if you use the preceding form as an example and enter Ann as the value for firstName and Go as the value for lastName, you will get the following result in the request body: firstName=Ann lastName=Go

An HTML form can also use the GET method; however, POST is much more often used with

HTML forms.

The doGet method is invoked when an HTTP request is sent using the GET method. GET is the default method in HTTP. When you type a URL, such as www.yahoo.com

, your request is sent to

Yahoo! using the GET method. If you use the GET method in a form, the parameter name/value pairs are appended to the URL. Therefore, if you have two parameters named firstName and lastName in your form, and the user enters Ann and Go, respectively, the URL to your servlet will become something like the following: http://yourdomain/myApp/Register?firstName=Ann&lastName=Go

Upon receiving a GET method, the servlet will call its doGet method.

Note

You may wonder how a servlet knows what doxxx method to invoke. You can find the answer by reading the source code of the HttpServlet class. This class inherits the service method from the javax.servlet.Servlet interface that gets called by the servlet container.

Remember that its signature is as follows: public void service(ServletRequest request,

ServletResponse response)

throws ServletException, IOException

The method tries to downcast request to HttpRequest and response to HttpResponse, and pass both as arguments to the second service method that has the following signature: protected void service(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

The HttpServletRequest interface has a method named getMethod that returns a String containing the HTTP method used by the client request. Knowing the HTTP method, the service method simply calls the corresponding doxxx method.

The servlet in

Listing 3.1

demonstrates the doGet and the doPost methods.

Note

If an HTML form does not have the ACTION attribute, the default value for this attribute is the current page.

Listing 3.1 The doGet and doPost Methods

36

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class RegisterServlet extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>The GET method</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("The servlet has received a GET. " +

"Now, click the button below.");

out.println("<BR>");

out.println("<FORM METHOD=POST>");

out.println("<INPUT TYPE=SUBMIT VALUE=Submit>");

out.println("</FORM>");

out.println("</BODY>");

out.println("</HTML>");

}

public void doPost(

HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>The POST method</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("The servlet has received a POST. Thank you.");

out.println("</BODY>");

out.println("</HTML>");

}

}

When the servlet is first called from a web browser by typing the URL to the servlet in the

Address or Location box, GET is used as the request method. At the server side, the doGet method is invoked. The servlet sends a string saying "The servlet has received a GET. Now, click the button below." plus an HTML form. The output is shown in

Figure 3.1

.

Figure 3.1. The output of the doGet method.

37

the form, a POST request is sent to the server. The servlet then invokes the doPost method, output of doPost is shown in

Figure 3.2

.

FL

TE

Team-Fly ®

The HttpServletRequest Interface

In addition to providing several more protocol-specific methods in the HttpServlet class, the javax.servlet.http package also provides more sophisticated request and response interfaces. The request interface, HttpServletRequest, is described in this section. The response interface,

HttpServletResponse, is explained in the next section.

Obtaining HTTP Request Headers from HttpServletRequest

The HTTP request that a client browser sends to the server includes an HTTP request header with important information, such as cookies and the referer. You can access these headers from the

HttpServletRequest object passed to a doxxx method.

Note

The list of all HTTP request headers is given in

Chapter 13 , "File Upload."

The following example demonstrates how you can use the HttpServletRequest interface to obtain all the header names and sends the header name/value pairs to the browser. The code is given in

Listing 3.2

.

Listing 3.2 Obtaining HTTP request Headers

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class RegisterServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

Enumeration enumeration = request.getHeaderNames();

while (enumeration.hasMoreElements()) {

String header = (String) enumeration.nextElement();

out.println(header + ": " + request.getHeader(header) + "<BR>");

}

}

}

The RegisterServlet in Listing 3.2

uses the getHeaderNames and the getHeader methods. The getHeaderNames is first called to obtain an Enumeration containing all the header names found in the client request. The value of each header then is retrieved by using the getHeader method, passing a header name.

The output of the code in

Listing 3.2

depends on the client environment, such as the browser used

and the operating system of the client's machine. For example, some browsers might send cookies to the server. Also, whether the servlet is requested by the user typing the URL in the

Address/Location box or by clicking a hyperlink also accounts for the presence of an HTTP request header called referer.

39

The output of the code in

Listing 3.2

is shown in

Figure 3.3

.

Figure 3.3. Obtaining HTTP request headers.

Some other methods of the HttpServletRequest interface provide information about paths. The getPathInfo method returns—following the servlet path but preceding the query string—a String containing any additional path information, or returns null if there is no additional path information. The getPathTranslated method returns the same information as the getPathInfo method, but translates the path to its physical path name before returning it, or returns null if there is no additional path information. Additional information comes after the servlet name and before the query string. The servlet name and the additional information is separated by the forward slash character (/).

For example, consider a request to a servlet called PathInfoDemoServlet, made with the following

URL: http://localhost:8080/myApp/servlet/PathInfoDemoServlet/AddInfo?id=2

This URL contains additional info "/AddInfo" after the servlet name. The getPathInfo method will return the String "/AddInfo", the getQueryString method will return "id=2", and the getPathTranslated method returns "C:\App\Java\AddInfo". The return value of getPathTranslated depends on the location of the servlet class file.

Next, the getRequestURI method returns the first line of the request's Uniform Resource Identifier

(URI). This is the part of the URI that is found to the left of the query string. The getServletPath method returns the part of the URI that refers to the servlet being invoked.

Figure 3.4

shows the

path information of a servlet called HttpRequestDemoServlet.

Figure 3.4. The path information of HttpRequestDemoServlet.

40

Obtaining the Query String from HttpServletRequest

The next important method is the getQueryString method, which is used to retrieve the query string of the HTTP request. A query string is the string on the URL to the right of the path to the servlet. The following example helps you see what a query string looks like.

As mentioned previously, if you use the GET method in an HTML form, the parameter name/value pairs will be appended to the URL. The code in

Listing 3.3

is a servlet named

HttpRequestDemoServlet that displays the value of the request's query string and a form.

Listing 3.3 Obtaining the Query String

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class HttpRequestDemoServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Obtaining the Query String</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("Query String: " + request.getQueryString() + "<BR>");

out.println("<FORM METHOD=GET>");

out.println("<BR>First Name: <INPUT TYPE=TEXT NAME=FirstName>");

out.println("<BR>Last Name: <INPUT TYPE=TEXT NAME=LastName>");

out.println("<BR><INPUT TYPE=SUBMIT VALUE=Submit>");

41

out.println("</FORM>");

out.println("</BODY>");

out.println("</HTML>");

}

}

When the user enters the URL to the servlet in the web browser and the servlet is first called, the query string is null, as shown in

Figure 3.5

.

Figure 3.5. The query string is null.

After you enter some values into the HTML form and submit the form, the page is redisplayed.

Note that now there is a string added to the URL. The query string has a value of the parameter name/value pairs separated by an ampersand (&). The page is shown in

Figure 3.6

.

Figure 3.6. The query string with a non-null value.

42

Obtaining the Parameters from HttpServletRequest

You have seen that you can get the query string containing a value. This means that you can get the form parameter name/value pairs or other values from the previous page. You should not use the getQueryString method to obtain a form's parameter name/value pairs, however, because this means you have to parse the string yourself. You can use some other methods in

HttpServletRequest to get the parameter names and values: the getParameterNames and the getParameter methods.

The getParameterNames method returns an Enumeration containing the parameter names. In many cases, however, you already know the parameter names, so you don't need to use this method. To get a parameter value, you use the getParameter method, passing the parameter name as the argument.

The following example demonstrates how you can use the getParameterNames and the getParameter methods to display all the parameter names and values from the HTML form from the previous page. The code is given in

Listing 3.4

.

Listing 3.4 Obtaining the Parameter Name/Value Pairs

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class HttpRequestDemoServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

43

out.println("<TITLE>Obtaining the Parameter</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("The request's parameters are:<BR>");

Enumeration enumeration = request.getParameterNames();

while (enumeration.hasMoreElements()){

String parameterName = (String) enumeration.nextElement();

out.println(parameterName + ": " +

request.getParameter(parameterName) + "<BR>" );

}

out.println("<FORM METHOD=GET>");

out.println("<BR>First Name: <INPUT TYPE=TEXT NAME=FirstName>");

out.println("<BR>Last Name: <INPUT TYPE=TEXT NAME=LastName>");

out.println("<BR><INPUT TYPE=SUBMIT VALUE=Submit>");

out.println("</FORM>");

out.println("</BODY>");

out.println("</HTML>");

}

}

When the servlet is first called, it does not have any parameter from the previous request.

Therefore, the no parameter name/value pair is displayed, as shown in

Figure 3.7

.

Figure 3.7. The first request does not have a parameter.

On subsequent requests, the user should enter values for both the firstName and lastName parameters. This is reflected on the next page, which is shown in

Figure 3.8

.

Figure 3.8. The parameter name/value pairs.

44

The code in

Listing 3.4

also can be used without any modification if the form uses the POST

method, which is what you normally use for a form. There are numerous cases, however, where you need to pass non-form values in the URL. This technique is reviewed in

Chapter 5 .

Manipulating Multi-Value Parameters

You may have a need to use parameters with the same name in your form. This case might arise, for example, when you are using check box controls that can accept multiple values or when you have a multiple-selection HTML select control. In situations like these, you can't use the getParameter method because it will give you only the first value. Instead, you use the getParameterValues method.

The getParameterValues method accepts one argument: the parameter name. It returns an array of string containing all the values for that parameter. If the parameter of that name is not found, the getParameterValues method will return a null.

The following example illustrates the use of the getParameterValues method to get all favorite

music selected by the user. The code for this servlet is given in Listing 3.5

.

Listing 3.5 Obtaining Multiple Values from a Parameter

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class HttpRequestDemoServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

45

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Obtaining Multi-Value Parameters</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<BR>");

out.println("<BR>Select your favorite music:");

out.println("<BR><FORM METHOD=POST>");

out.println("<BR><INPUT TYPE=CHECKBOX " +

"NAME=favoriteMusic VALUE=Rock>Rock");

out.println("<BR><INPUT TYPE=CHECKBOX " +

"NAME=favoriteMusic VALUE=Jazz>Jazz");

out.println("<BR><INPUT TYPE=CHECKBOX " +

"NAME=favoriteMusic VALUE=Classical>Classical");

out.println("<BR><INPUT TYPE=CHECKBOX " +

"NAME=favoriteMusic VALUE=Country>Country");

out.println("<BR><INPUT TYPE=SUBMIT VALUE=Submit>");

out.println("</FORM>");

out.println("</BODY>");

out.println("</HTML>");

}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String[] values = request.getParameterValues("favoriteMusic");

response.setContentType("text/html");

PrintWriter out = response.getWriter();

if (values != null ) {

int length = values.length;

out.println("You have selected: ");

for (int i=0; i<length; i++) {

out.println("<BR>" + values[i]);

}

}

}

}

When the servlet is first called, the doGet method is invoked and the method sends a form to the web browser. The form has four check box controls with the same name: favoriteMusic. Their values are different, however. This is shown in

Figure 3.9

.

Figure 3.9. A form with multiple value check boxes.

46

When the user selects the value(s) of the check boxes, the browser sends all selected values. In the server side, you use the getParameterValues to retrieve all values sent in the request. This is shown in

Figure 3.10

Figure 3.10. Displaying the selected values.

Note that you use the POST method for the form; therefore, the parameter name/value pairs are retrieved in the doPost method.

47

HttpServletResponse

The HttpServletResponse interface provides several protocol-specific methods not available in the javax.servlet.ServletResponse interface.

The HttpServletResponse interface extends the javax.servlet.ServletResponse interface. In the examples in this chapter so far, you have seen that you always use two of the methods in

HttpServletResponse when sending output to the browser: setContentType and getWriter. response.setContentType("text/html");

PrintWriter out = response.getWriter();

There is more to it, however. The addCookie method sends cookies to the browser. You also use methods to manipulate the URLs sent to the browser. These methods are explored further in the section on user session management in

Chapter 5 .

Another interesting method in the HttpServletResponse interface is the setHeader method. This method allows you to add a name/value field to the response header. method, the web server sends a special message to the browser to request another page. Therefore, there is always a round trip to the client side before the other page is fetched. This method is used

FL

Listing 3.6

shows a Login page that

prompts the user to enter a user name and a password. If both are correct, the user will be redirected to a Welcome page. If not, the user will see the same Login page. outputs the form. The user can then enter the user name and password, and submit the form. Note

TE

AM that the form uses the POST method, which means that at the server side, the doPost method is outputs the Login form again along with an error message.

Listing 3.6 A Login Page

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class LoginServlet extends HttpServlet {

private void sendLoginForm(HttpServletResponse response,

boolean withErrorMessage)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Login</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

if (withErrorMessage)

Team-Fly ®

out.println("Login failed. Please try again.<BR>");

out.println("<BR>");

out.println("<BR>Please enter your user name and password.");

out.println("<BR><FORM METHOD=POST>");

out.println("<BR>User Name: <INPUT TYPE=TEXT NAME=userName>");

out.println("<BR>Password: <INPUT TYPE=PASSWORD NAME=password>");

out.println("<BR><INPUT TYPE=SUBMIT VALUE=Submit>");

out.println("</FORM>");

out.println("</BODY>");

out.println("</HTML>");

}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

sendLoginForm(response, false);

}

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

String userName = request.getParameter("userName");

String password = request.getParameter("password");

if (userName != null && password != null &&

userName.equals("jamesb") && password.equals("007")) {

response.sendRedirect("http://domain/app/WelcomePage");

}

else {

sendLoginForm(response, true);

}

}

}

Note

Note that if you are redirecting to a resource in the same application, you don't need to specify the complete URL; that is, you can just write, in the previous example, response.sendRedirect ("/app/WelcomePage"). For efficiency, however, you don't normally use the sendRedirect method to redirect a user to another resource in the same application. Instead, you forward the user, as you will see in the section, "

Request

Dispatching ," later in this chapter.

In the code in

Listing 3.6

, I wrote a private method called sendLoginForm that accepts an

HttpServletResponse object and a boolean that signals whether an error message be sent along with the form. This sendLoginForm method is called both from the doGet and the doPost methods.

When called from the doGet method, no error message is given, because this is the first time the user requests the page. The withErrorMessage flag is therefore false. When called from the doPost method, this flag is set to true because the sendLoginForm method is only invoked from doPost if the user name and password did not match.

The Login page, when it is first requested, is shown in

Figure 3.11

. The Login page, after a failed

attempt to log in, is shown in

Figure 3.12

.

Figure 3.11. The Login page when first requested.

49

Figure 3.12. The Login page after a failed login.

After seeing the example, an experienced reader may ask, "If we can go to the Welcome page by just typing its URL in the web browser, why do we have to log in?"

This is true. The user can bypass the Login page, and this issue has to do with session management and will be addressed in

Chapter 5 .

50

Sending an Error Code

The HttpServletResponse also allows you to send pre-defined error messages. The interface defines a number of public static final integers that all start with SC_. For example,

SC_FORBIDDEN will be translated into an HTTP error 403.

Along with the error code, you also can send a custom error message. Instead of redisplaying the

Login page when a failed login occurs, you can send an HTTP error 403 plus your error message.

To do this, replace the call to the sendLoginForm in the doPost method with the following: response.sendError(response.SC_FORBIDDEN, "Login failed.");

The user will see the screen in Figure 3.13

when a login fails.

Figure 3.13. Sending an HTTP Error 403.

Note

The complete list of status codes can be found in

Appendix C , "The javax.servlet.http

Package Reference."

Sending Special Characters

51

Several characters have a special meaning in HTML. For instance, the less-than character (<) is used as the opening character of an HTML tag, and the greater-than character (>) is the closing character of an HTML tag.

When sending these characters to be displayed in the browser, you need to encode them so that they will be rendered correctly. For example, consider the code in

Listing 3.7

.

The doGet method of the SpecialCharacterServlet is very simple. It is intended to send a string that will be rendered as the following text in the browser:

In HTML, you use <BR> to change line.

Listing 3.7 Incorrect Rendering of Special Characters

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class SpecialCharacterServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>HTML Tutorial — Changing Line</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("In HTML, you use <BR> to change line.");

out.println("</BODY>");

out.println("</HTML>");

}

}

This code produces a problem, however. To see what went wrong, take a look at the output of the doGet method in a browser, as shown in

Figure 3.14

.

Figure 3.14. Special characters are not displayed correctly.

52

Because <BR> means change line in HTML, the intended string is not displayed correctly. Instead, it was interpreted as a command to cut the original string into two and the output was displayed in two lines.

To get around this, every time you want to display a special character, you need to encode it. The less-than character (<) is encoded as "<" and the greater-than character (>) as ">". Other special characters are the ampersand (&) and double quotation mark (") characters. You replace the ampersand (&) with "&amp;" and the double quotation marks (") with "&quot;". Additionally, two or more white spaces are always displayed as a single space, unless you convert each individual space to "&nbsp;".

Converting every occurrence of a special character is a tedious task, however. That's why you need a function that will do it automatically. Such a function is called encodeHtmlTag and is given in

Listing 3.8

. Now, if you suspect that the String you want to send to the browser contains a

special character, just pass it to the encodeHtmlTag function.

Listing 3.8 The encodeHtmlTag Function

public static String encodeHtmlTag(String tag) {

if (tag == null)

return null;

int length = tag.length();

StringBuffer encodedTag = new StringBuffer(2 * length);

for (int i=0; i<length; i++) {

char c = tag.charAt(i);

if (c == '<')

encodedTag.append("<");

else if (c == '>')

encodedTag.append(">");

else if (c == '&')

encodedTag.append("&amp;");

else if (c == '"')

encodedTag.append("&quot;");

53

else if (c == ' ')

encodedTag.append("&nbsp;");

else

encodedTag.append(c);

}

return encodedTag.toString();

}

Listing 3.9

demonstrates a servlet that includes the encodeHtmlTag method and uses it to encode any String with special characters.

Listing 3.9 Using the encodeHtmlTag Method in a Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class SpecialCharacterServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>HTML Tutorial — Changing Line</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println(encodeHtmlTag("In HTML, you use <BR> to change line."));

out.println("</BODY>");

out.println("</HTML>");

}

/**

* Encode an HTML tag so it will be displayed

* as it is on the browser.

* Particularly, this method searches the

* passed in String and replace every occurrence

* of the following character:

* '<' with "&lt;"

* '>' with "&gt;"

* '&' with "&amp;"

* //'"' with "&quot;"

* ' ' with "&nbsp;"

*/

public static String encodeHtmlTag(String tag) {

if (tag == null)

return null;

int length = tag.length();

StringBuffer encodedTag = new StringBuffer(2 * length);

for (int i=0; i<length; i++) {

char c = tag.charAt(i);

if (c == '<')

encodedTag.append("&lt;");

else if (c == '>')

encodedTag.append("&gt;");

54

else if (c == '&')

encodedTag.append("&amp;");

else if (c == '"')

encodedTag.append("&quot;"); //when trying to output text as

// tag's value as in values="???".

else if (c == ' ')

encodedTag.append("&nbsp;");

else

encodedTag.append(c);

}

return encodedTag.toString();

}

}

Figure 3.15

shows the output of sending the string, "In HTML, you use <BR> to change line". If you look at the HTML source code, you will notice that the < character has been converted to < and the > character to >.

Figure 3.15. Encoding special characters.

Buffering the Response

If response buffering is enabled, the output to the browser is not sent until the servlet processing is finished or the buffer is full. Buffering enhances the performance of your servlet because the servlet needs to send the string output only once, instead of sending it every time the print or println method of the PrintWriter object is called. By default, buffering is enabled and the buffer size is 8,192 characters. You can change this value by using the HttpServletResponse interface's setBufferSize method. This method can be called only before any output is sent.

55

Populating HTML Elements

One of the tasks that you will perform often is populating the values of HTML elements. This is a straightforward task that can be tricky if you are not cautious. To do it correctly, pay attention to the following two rules:

1. Always enclose a value with double quotation marks ("). This way, white spaces will be rendered correctly.

2. If the value contains a double quotation mark character, you need to encode the double quotation marks (").

The servlet in

Listing 3.10

contains an HTML form with two elements: a Textbox and a Password

box. The Textbox element is given the value, Duncan "The Great" Young, and the password is lo&&lita.

Listing 3.10 Populating HTML Elements

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class PopulateValueServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String userName = "Duncan \"The Great\" Young";

String password = "lo&&lita";

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Populate HTML elements</TITLE>");

out.println("</HEAD>");

out.println("<H3>Your user name and password.</H3>");

out.println("<FORM METHOD=POST>");

out.println("<BR>User name: <INPUT TYPE=TEXT NAME=userName

VALUE=\"" + userName + "\">");

out.println("<BR>Password: <INPUT TYPE=PASSWORD NAME=password

VALUE=\"" + password + "\">");

out.println("<BODY>");

out.println("</BODY>");

out.println("</HTML>");

}

}

As you can see in Figure 3.16

, however, the value in the Textbox element is truncated because the first double quotation mark character—in "The Great"—fools the browser into thinking that it is the end of the value. To overcome this problem, use the encodeHtmlTag method.

Figure 3.16. Truncated value.

56

Request Dispatching

In some circumstances, you may want to include the content from an HTML page or the output from another servlet. Additionally, there are cases that require that you pass the processing of an

HTTP request from your servlet to another servlet. The current servlet specification responds to these needs with an interface called RequestDispatcher, which is found in the javax.servlet package. This interface has two methods, which allow you to delegate the request-response processing to another resource: include and forward. Both methods accept a javax.servlet.ServletRequest object and a javax.servlet.ServletResponse object as arguments.

As the name implies, the include method is used to include content from another resource, such as another servlet, a JSP page, or an HTML page. The method has the following signature: public void include(javax.servlet.ServletRequest request,

javax.servlet.ServletResponse response)

throws javax.servlet.ServletException, java.io.IOException

The forward method is used to forward a request from one servlet to another. The original servlet can perform some initial tasks on the ServletRequest object before forwarding it. The signature of the forward method is as follows: public void forward(javax.servlet.ServletRequest request,

javax.servlet.ServletResponse response)

throws javax.servlet.ServletException, java.io.IOException

The Difference Between sendRedirect and forward

Both the sendRedirect and forward methods bring the user to a new resource. There is a

57

fundamental difference between the two, however, and understanding this can help you write a more efficient servlet.

The sendRedirect method works by sending a status code that tells the browser to request another URL. This means that there is always a round trip to the client side.

Additionally, the previous HttpServletRequest object is lost. To pass information between the original servlet and the next request, you normally pass the information as a query string appended to the destination URL.

The forward method, on the other hand, redirects the request without the help from the client's browser. Both the HttpServletRequest object and the HttpServletResponse object also are passed to the new resource.

To perform a servlet include or forward, you first need to obtain a RequestDispatcher object. You can obtain a RequestDispatcher object three different ways, as follows:

Use the getRequestDispatcher method of the javax.servlet.ServletContext interface, passing a String containing the path to the other resource. The path is relative to the root of the ServletContext.

Use the getRequestDispatcher method of the javax.servlet.ServletRequest interface, passing a String containing the path to the other resource. The path is relative to the

• current HTTP request.

Use the getNamedDispatcher method of the javax.servlet.ServletContext interface, passing a String containing the name of the other resource.

FL

Y

When programmers new to servlet programming are writing code for request dispatching, they often make the common mistake of passing an incorrect path to the getRequestDispatcher method.

A big difference exists between the getRequestDispatcher method of the ServletContext interface and that belonging to the ServletRequest interface. The one you use depends on the location of the javax.servlet.ServletContext interface, you pass a path that is relative to the root of the

TE

AM

ServletContext. If you use the getRequestDispatcher method of the javax.servlet.ServletRequest

When you are creating a RequestDispatcher object from a servlet named FirstServlet to include or forward the request to another servlet called SecondServlet, the easiest way is to place the class files of both FirstServlet and SecondServlet in the same directory. This way, FirstServlet can be invoked from the URL http://domain/VirtualDir/servlet/FirstServlet and SecondServlet can be called from the URL http://domain/VirtualDir/servlet/SecondServlet . You then can use the getRequestDispatcher from the ServletRequest interface, passing the name of the second servlet.

In FirstServlet, you can write the following code: public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

RequestDispatcher rd = request.getRequestDispatcher("SecondServlet");

rd.include(request, response);

} or public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Team-Fly ®

RequestDispatcher rd = request.getRequestDispatcher("SecondServlet");

rd.forward(request, response);

}

Because both FirstServlet and SecondServlet are in the same directory, you don't need to include the forward slash (/) character before SecondServlet. In this case, you don't need to worry about the paths of both servlets.

Another option is to do it the harder way by passing the following String to the getRequestDispatcher of ServletRequest:

"/servlet/SecondServlet"

If you are to use the getRequestDispatcher from the ServletContext, you must pass

"/VirtualDir/servlet/SecondServlet" as the path argument, such as the following: public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

RequestDispatcher rd = getServletContext().getRequestDispatcher("/servlet/SecondServlet");

rd.include(request, response);

} or public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

RequestDispatcher rd = getServletContext().getRequestDispatcher("/servlet/SecondServlet");

rd.forward(request, response);

}

To use the getNamedDispatcher method, your code would become public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

RequestDispatcher rd =

getServletContext().getNamedDispatcher("SecondServlet");

rd.include(request, response);

} or public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

RequestDispatcher rd =

getServletContext().getNamedDispatcher("SecondServlet");

rd.forward(request, response);

59

}

Of course, when you use the getNamedDispatcher method, you must register the second servlet in your deployment descriptor. Here is an example:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>FirstServlet</servlet-name>

<servlet-class>FirstServlet</servlet-class>

</servlet>

<servlet>

<servlet-name>SecondServlet</servlet-name>

<servlet-class>SecondServlet</servlet-class>

</servlet>

</web-app>

If you are including from a doPost method, the doPost method of the second servlet will be invoked. If including from a doGet method, the doGet method of the second servlet will be called.

Warning

If you change the resource included in your servlet, you need to restart Tomcat for the change to take effect. This is required because the included servlet is never invoked directly. After the included servlet is loaded, its timestamp is never compared again.

The following sections give you a closer look at the use of the RequestDispatcher interface.

Note

Note that in the olden days (which are not so long ago, of course), servlet chaining was the technique used to perform what RequestDispatcher can do. Servlet chaining is not part of the J2EE specification, however, and its use is dependent on specific servlet containers.

You may still find this term in old literature on servlets.

Including Other Resources

On many occasions, you may want to include other resources inside your servlet. For example, you may have a collection of JavaScript functions that you want to include in the response to the user. Separating non-servlet content makes sure that modularity is maintained. In this case, a

JavaScript programmer can work independently of the servlet programmer. The page containing the JavaScript functions can then be included using the include method of a RequestDispatcher.

Another time you may want to include other resources in your servlet might be when you want to include the output of a servlet whose output is a link to a randomly selected advertisement banner.

By separating into a separate servlet the code that selects the banner, the same code can be included in more than one servlet, and formatting can be done by modifying the included servlet solely.

The include method of the RequestDispatcher interface may be called at any time. The target servlet has access to all aspects of the request object, but can only write information to the

ServletOutputStream or Writer object of the response object. The target servlet also can commit a

60

response by either writing content past the end of the response buffer or explicitly calling the flush method of the ServletResponse interface. The included servlet cannot set headers or call any method that affects the header of the response.

When a servlet is being called from within an include method, it is sometimes necessary for that servlet to know the path by which it was invoked. The following request attributes are set and accessible from the included servlet via the getAttribute method on the request object:

• javax.servlet.include.request_uri javax.servlet.include.context_path javax.servlet.include.servlet_path javax.servlet.include.path_info javax.servlet.include.query_string

These attributes are not set if the included servlet was obtained by using the getNamedDispatcher method.

Including Static Content

Sometimes you need to include static content, such as HTML pages or image files that are prepared by a web graphic designer. You can do this by using the same technique for including dynamic resources that you've been reading about in this chapter.

The following example shows a servlet named FirstServlet that includes an HTML file named

AdBanner.html. The servlet class file is located in the WEB-INF\classes directory, whereas the

AdBanner.html file, like other HTML files, resides in the application directory. In other words, using the myApp application, the AdBanner.html file resides in the myApp directory, whereas the servlet class file is in myApp/WEB-INF/classes directory. The servlet is given in

Listing 3.11

and the HTML file is given in Listing 3.12

.

Listing 3.11 Including Static Content

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

RequestDispatcher rd = request.getRequestDispatcher("/AdBanner.html");

rd.include(request, response);

}

}

Listing 3.12 The AdBanner.html File

<HTML>

<HEAD>

<TITLE>Banner</TITLE>

</HEAD>

<BODY>

<IMG SRC=myApp/images/banner.jpg>

61

</BODY>

</HTML>

Including Another Servlet

The second example shows a servlet (FirstServlet) that includes another servlet (SecondServlet).

The second servlet simply sends the included request parameter to the user. The FirstServlet is given in

Listing 3.13

and the SecondServlet is presented in

Listing 3.14

. The output of the

example is given in Figure 3.17

.

Figure 3.17. The included request parameters.

Listing 3.13 FirstServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Included Request Parameters</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<B>Included Request Parameters</B><BR>");

RequestDispatcher rd = request.getRequestDispatcher("/servlet/SecondServlet?name=budi");

62

rd.include(request, response);

out.println("</BODY>");

out.println("</HTML>");

}

}

Listing 3.14 SecondServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class SecondServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

Enumeration enum = request.getAttributeNames();

while (enum.hasMoreElements()) {

String attributeName = (String) enum.nextElement();

out.println(attributeName + ": " +

request.getAttribute(attributeName) + "<BR>");

}

}

}

Forwarding Processing Control

Unlike the include method, the forward method of the RequestDispatcher interface may be called only by the calling servlet if no output has been committed to the client. If output exists in the response buffer that has not been committed, the buffer must be cleared before the target servlet's service method is called. If the response has been committed prior to calling the forward method, an IllegalStateException will be thrown. For example, the servlet in

Listing 3.15

will raise an error

because the flushBuffer method is called before the forward method.

Listing 3.15 Forwarding Control After the Buffer Is Flushed

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Included Request Parameters</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<B>Included Request Parameters</B><BR>");

response.flushBuffer();

RequestDispatcher rd =

request.getRequestDispatcher("/servlet/SecondServlet");

63

rd.forward(request, response);

out.println("asdfaf</BODY>");

out.println("</HTML>");

}

}

The forward method also can be used to forward the request to a static content. Again, the flushBuffer method must not be called beforehand.

The forward method is also a good replacement for the sendRedirect method of the

HttpServletResponse interface. You may recall that with the sendRedirect method there is a round trip to the client. If you are redirecting the user to a servlet or a page in the current application, you can use the forward method instead. There is no round trip to the browser when using the forward method; therefore, this gives the user a faster response.

The following example rewrites the Login servlet from

Listing 3.6

. Instead of using the

sendRedirect method, the servlet uses a RequestDispatcher to forward the request to the

WelcomeServlet servlet when the login was successful. The code for the modified Login servlet is given in

Listing 3.16

and the code for the WelcomeServlet servlet is shown in

Listing 3.17

.

Listing 3.16 The LoginServlet Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class LoginServlet extends HttpServlet {

private void sendLoginForm(HttpServletResponse response,

boolean withErrorMessage)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Login</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

if (withErrorMessage)

out.println("Login failed. Please try again.<BR>");

out.println("<BR>");

out.println("<BR>Please enter your user name and password.");

out.println("<BR><FORM METHOD=POST>");

out.println("<BR>User Name: <INPUT TYPE=TEXT NAME=userName>");

out.println("<BR>Password: <INPUT TYPE=PASSWORD NAME=password>");

out.println("<BR><INPUT TYPE=SUBMIT VALUE=Submit>");

out.println("</FORM>");

out.println("</BODY>");

out.println("</HTML>");

}

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

sendLoginForm(response, false);

}

64

public void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException,

IOException {

String userName = request.getParameter("userName");

String password = request.getParameter("password");

if (userName != null && password != null &&

userName.equals("jamesb") && password.equals("007")) {

RequestDispatcher rd = request.getRequestDispatcher("WelcomeServlet");

rd.forward(request, response);

}

else {

sendLoginForm(response, true);

}

}

}

Listing 3.17 The WelcomeServlet Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class WelcomeServlet extends HttpServlet {

public void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException,

IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Welcome</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<P>Welcome to the Bulbul's and Boni's Web

Site.</P>");

out.println("</BODY>");

out.println("</HTML>");

}

}

Note

If a request is dispatched from doGet, the doGet method of the destination servlet will be invoked. If it is from doPost, the doPost method of the destination servlet will be invoked.

Summary

In this chapter, you have learned how to use some of the classes and interfaces from the javax.servlet.http package. You have been shown a number of examples that demonstrate the use of HttpServlet, HttpServletRequest and HttpServletResponse.

65

In addition, this chapter introduced you to the RequestDispatcher interface. This interface is useful for including other resources and forwarding the request to another resource.

The next chapter discusses database access using the Java Database Connectivity (JDBC) technology. This is an important chapter considering that almost all non-trivial web applications involve accessing data in a database.

66

Chapter 4. Accessing Databases with JDBC

Most web applications use a database. Database accessing and programming therefore play a significant role in web development. In this chapter, you examine how data can be stored, retrieved, and manipulated. In Java, the technology that enables database access and manipulation is called Java Database Connectivity (JDBC).

JDBC has two parts: the JDBC Core Application Programming Interface (API) and the JDBC

Optional Package API. The JDBC Core API is the main part of JDBC and when people talk about

JDBC, they often are referring to this part.

The JDBC Core API is part of the Java 2, Standard Edition (J2SE) and takes the form of the classes and interfaces in the java.sql package. At the time of writing, the most recent version is 3.0.

You use the members of the java.sql package primarily for basic database programming.

The JDBC Optional Package API is specified in the javax.sql package and is currently in version

2.0. The javax.sql package supports connection pooling, distributed transactions, rowsets, and so on. Of these, connection pooling is the most important in servlet programming; it is therefore explored in this chapter. You can download this package from http://java.sun.com/products/jdbc/download.html

.

JDBC is a broad topic, and a complete discussion of its object model requires a book of its own.

This chapter starts with a look at the object model in the java.sql package, but does not attempt to explain JDBC thoroughly. Some of the features in JDBC do not even suit our needs in web programming. For example, JDBC supports cursors that can scroll back, but using this type of cursor in a servlet is not tolerable for efficiency reasons. If you want to know more about JDBC, refer to the JDBC web site, http://java.sun.com/products/jdbc/index.html

.

With the exception of the section, "Connection Pooling," toward the end of this chapter, the examples use the interfaces and classes of the java.sql package. A discussion of this package at the beginning of this chapter provides the uninitiated reader with enough JDBC knowledge to build database-enabling servlets. However, the discussion assumes familiarity with Structured Query

Language (SQL). After the initial discussion, this chapter provides an easy passage to database programming in servlets in the section, "

Four Steps to Getting to the Database ." (If you are

already a JDBC expert, you may want to skip that section.)

The java.sql Package

The java.sql package provides the API for accessing and processing data in a data source. The most important members of the java.sql package are as follows:

The DriverManager class

The Driver interface

The Connection interface

The Statement interface

The ResultSet interface

The PreparedStatement interface

The ResultSetMetaData interface

Each of the types is briefly discussed in the following sections.

67

The DriverManager Class

The DriverManager class provides static methods for managing JDBC drivers. Each JDBC driver you want to use must be registered with the DriverManager. The JDBC driver of the database to which you want to connect is supplied either by the database vendor or a third party. You use different JDBC drivers for different database servers. For example, the JDBC driver for Microsoft

SQL Server is different from the one used to access Oracle databases. JDBC drivers are discussed in more detail in the section, "

Four Steps to Getting to the Database ."

To load a JDBC driver from a servlet or JSP page, you copy the JDBC driver file for a particular database server (normally a .jar file) to the WEB-INF\lib directory under your application directory. Create the lib directory, if it doesn't exist, and then use the following code: try {

Class.forName("JDBC.driver");

} catch (ClassNotFoundException e) {

// driver not found

}

In this case, JDBC.driver is the fully qualified name of the JDBC driver class. This name can be found in the documentation accompanying the JDBC driver. java.sql.Connection object. This method has three overloads whose signatures are as follows:

FL public static Connection getConnection(String url, String user,

String password)

AM

The Driver Interface

TE

The Driver interface is implemented by every JDBC driver class. The driver class itself is loaded and registered with the DriverManager, and the DriverManager can manage multiple drivers for any given connection request. In the case where there are multiple drivers registered, the

DriverManager will ask each driver in turn to try to connect to the target URL.

The Connection Interface

The Connection interface represents a connection to the database. An instance of the Connection interface is obtained from the getConnection method of the DriverManager class.

close

The close method immediately closes and releases a Connection object instead of waiting for it to be released automatically. Its signature is as follows: public void close() throws SQLException

isClosed

You use this method to test whether the Connection object is closed. The signature of this method is as follows:

Team-Fly ®

public boolean isClosed() throws SQLException

createStatement

The createStatement method is used to create a Statement object for sending SQL statements to the database. If the same SQL statement is executed many times, it is more efficient to use a

PreparedStatement object.

This method has two overloads with the following signatures: public Statement createStatement() throws SQLException public Statement createStatement

(int resultSetType, int resultSetConcurrency) throws SQLException

prepareStatement

You use the prepareStatement method to create a PreparedStatement object. Its signature is as follows: public PreparedStatement prepareStatement()throws SQLException

getAutoCommit

The getAutoCommit method returns a boolean specifying the current auto-commit state. The signature of this method is as follows: public boolean getAutoCommit() throws SQLException

This method returns true if auto-commit is enabled and false if auto-commit is not enabled. By default, auto-commit is enabled.

setAutoCommit

The setAutoCommit method sets the auto-commit state of the Connection object. Its signature is as follows: public void setAutoCommit(boolean autocommit) throws SQLException

commit

You use the commit method to commit a transaction. The signature of this method is as follows: public void commit() throws SQLException

rollback

You use the rollback method to roll back a transaction. Its signature is as follows: public void rollback() throws SQLException

The Statement Interface

69

You use the statement interface method to execute an SQL statement and obtain the results that are produced. The two most important methods of this interface are executeQuery and executeUpdate.

executeQuery

The executeQuery method executes an SQL statement that returns a single ResultSet object. Its signature is as follows: public ResultSet executeQuery(String sql) throws SQLException

executeUpdate

The executeUpdate method executes an insert, update, and delete SQL statement. The method returns the number of records affected by the SQL statement execution, and its signature is as follows: public int executeUpdate(String sql)

The ResultSet Interface

The ResultSet interface represents a table-like database result set. A ResultSet object maintains a cursor pointing to its current row of data. Initially, the cursor is positioned before the first row.

The following are some important methods of the ResultSet interface.

isFirst

The isFirst method indicates whether the cursor points to the first record in the ResultSet. Its signature is as follows: public boolean isFirst() throws SQLException

isLast

The isLast method indicates whether the cursor points to the last record in the ResultSet. Its signature is as follows: public boolean isLast() throws SQLException

next

The next method moves the cursor to the next record, returning true if the current row is valid and false if there are no more records in the ResultSet object. The method's signature is as follows: public boolean next() throws SQLException

getMetaData

The getMetaData method returns the ResultSetMetaData object representing the meta data of the

ResultSet. The signature of the method is as follows: public ResultSetMetaData getMetaDate() throws SQLException

70

In addition to the previous methods, you can use several getXXX methods to obtain the value of the specified column in the row pointed by the cursor. In this case, XXX represents the data type returned by the method at the specified index, and each getXXX method accepts the index position of the column in the ResultSet. The column index 1 indicates the first column. The signature of this method is as follows: public XXX getXXX(int columnIndex) throws SQLException

For example, the getString method has the following signature and returns the specified cell as

String: public String getString(int columnIndex) throws SQLException

The PreparedStatement Interface

The PreparedStatement interface extends the Statement interface and represents a precompiled

SQL statement. You use an instance of this interface to execute efficiently an SQL statement multiple times.

The ResultSetMetaData Interface

The ResultSetMetaData interface represents the meta data of a ResultSet object. The following sections introduce the most important methods.

getColumnCount

The getColumnCount method returns the number of columns in the ResultSet whose meta data is represented by the ResultSetMetaData object. Its signature is as follows: public int getColumnCount() throws SQLException

getColumnName

The getColumnName method returns the column name as the specified column index. Its signature is as follows: public String getColumnName(int columnIndex) throws SQLException

The first column is indicated by index number 1.

Four Steps to Getting to the Database

This section explains what it takes to access a database and manipulate data in it.

Before you can manipulate data in a database, you need to connect to that database server. After you get the connection, you can communicate with the database server. You can send an SQL query to retrieve data from a table, update records, insert new records, or delete data you no longer need. You also can do more than manipulate data: You can invoke a stored procedure, create a table, and more.

Accessing a database with JDBC can be summarized in the following four steps:

71

1. Load the JDBC database driver.

2. Create a connection.

3. Create a statement.

4. Create a resultset, if you expect the database server to send back some data.

The discussion of each of these steps can be found in the following sections.

Step 1: Load a JDBC Database Driver

Database servers have their own proprietary "languages" for communication. This means that if you want to communicate with a database server, you need to understand its language. Fortunately, there are "translators" that can interface Java code with these database servers. These translators take the form of JDBC drivers. In other words, if you want to access a particular database, you need to get the JDBC driver for that database.

JDBC Drivers are available for most popular databases today. Oracle, Sybase, DB2, Microsoft

SQL Server, MySQL—you name it. Drivers are even available for Open Database Connectivity

(ODBC), which means that if you can't find a JDBC driver for a certain database but that database can be connected through ODBC, you still can access the database through ODBC.

These JDBC drivers come at various prices and quality. Some are free and some are pricey. Some are slow, and some are lightning fast. The list of JDBC drivers can be found at http://industry.java.sun.com/products/jdbc/drivers .

Driver Types

Not all JDBC drivers are created equal. As mentioned previously, some are fast and some are slow.

Slower drivers are not necessarily inefficient code. Some drivers are slower than others due to their architectural limitation. Depending on the architecture, a JDBC driver can fall into one of four types: Type 1, Type 2, Type 3, and Type 4.

JDBC started with Type 1 drivers. Today this type is normally the slowest, used only when you have no other alternative. Type 1 drivers are drivers that provide access to ODBC drivers and also are called the JDBC-ODBC Bridge driver. This driver is included in the J2SE and J2EE distribution and originally played an important role to help JDBC gain market acceptance. Why the bridge? At the moment JDBC was conceived, ODBC had already ruled the database connectivity world. Sun played a good strategy by enabling Java programmers to access any database server that could be accessed through ODBC.

As previously mentioned, you don't use Type 1 drivers in production, unless you can't find other drivers for that database. For rapid prototyping, however, these drivers are acceptable. For example, if you need to prove a concept and a Microsoft Access database is all you have, the

JDBC-ODBC Bridge can allow access to it in no time.

Note that you need to set up an ODBC Data Source Name (DSN) on the computer you use to connect to the database. Some ODBC native code and, in many cases, native database client code must be loaded on each machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important.

Setting Up an ODBC Data Source Name

To set up an ODBC data source name, follow these steps:

72

1. Open the ODBC Data Source Administration dialog box from the Control

Panel.

2. Click the System DSN tab.

3. Click the Add button.

4. Select a driver name from the list of ODBC drivers.

5. Enter the needed information in the Setup dialog box that appears.

6. Click OK to close the dialog box.

Type 2 drivers are drivers written in part Java and part native API to convert JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine.

Type 3 drivers are drivers written to use the network protocol to translate JDBC API calls into a

DBMS-independent net protocol, which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible

JDBC API alternative—and most likely, all vendors of this solution will provide products suitable for Intranet use. In order for these products also to support Internet access, they must handle the additional requirements for security, access through firewalls, and so forth, that the web imposes.

Several vendors are adding JDBC technology-based drivers to their existing database middleware products.

Type 4 drivers are pure Java. They are written to use the native protocol to convert JDBC technology calls into the network protocol directly used by DBMSs. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Because many of these protocols are proprietary, the database vendors themselves will be the primary source for this style of driver.

Note

For the list of JDBC drivers for various databases, see http://industry.java.sun.com/products/jdbc/drivers .

Installing JDBC Drivers

Because JDBC drivers normally come in a .jar file, the first thing you need to do after you get the driver is tell Tomcat where to find it by copying the .jar file into the WEB-INF\lib directory under your application directory. Create the lib directory if it doesn't exist.

Note

If you are using the JDBC-ODBC bridge, you do not need to install the driver because it's already included in your Java Development Kit (JDK).

Now that the driver is within reach, you can create an instance of it using the static forName method of the Class class, passing the driver's fully qualified class name. The following is the code:

Class.forName(driverName)

For example, for a MySQL database, the most popular driver is the Type 4 driver developed by

Mark Matthews of Purdue University and downloadable from http://www.worldserver.com/mm.mysql/ . This driver is available under the GNU General Public

73

License. Assuming that you have downloaded it and made it available to your Java code, you can load it using the following code:

Class.forName("org.gjt.mm.mysql.Driver");

Of course, the driverName argument will be different if you are using a different driver for

MySQL.

For an ODBC database, the code that loads the driver is the following:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Or, if you are using the FreeTds Type 4 JDBC driver to connect to a Microsoft SQL Server, you use this code to load the driver:

Class.forName("com.internetcds.jdbc.tds.Driver");

Your JDBC driver should come with documentation that tells you the driver class name to use.

Note

Microsoft SQL Server 2000 has its own Type 4 JDBC Driver, downloadable from http://www.microsoft.com/sql/downloads/2000/jdbc.asp

.

If you plan to connect to different database servers in your code, you need to load all JDBC drivers for every database. For example, if you need to connect to an ODBC database as well as a

MySQL database, you load both drivers by using the following code:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Class.forName("org.gjt.mm.mysql.Driver");

Step 2: Creating a Connection

After you register a JDBC driver with the DriverManager, you can use it to get a connection to the database. In JDBC, a database connection is represented by the java.sql.Connection interface. You use the DriverManager class's getConnection method to obtain a Connection object.

As mentioned in the previous section, the getConnection method has three overloads, two of which are normally used. The first overload takes three arguments: url, userName, and password.

Its signature is as follows: public static Connection getConnection(String url,

String user, String password)

throws SQLException

The url part is the trickiest element in this method. The url is of this syntax: jdbc:subprotocol:subname

The subprotocol and subname parts depend on the database server you use. The documentation of the JDBC driver should tell you the subprotocol and subname to use.

If you are using a JDBC-ODBC bridge driver, the subprotocol is "odbc" and the subname is the

Data Source Name (DSN) for that database. For instance, for a DSN called MarketingData, your

URL will be:

74

jdbc:odbc:MarketingData

If you want to connect to a MySQL database, the subprotocol part is "mysql" and the subname part should be given the name of the machine and the database. For example, for a database named Fred, use the following: jdbc:mysql///Fred

If one of the drivers you loaded recognizes the JDBC URL passed to the getConnection method, that driver will try to establish a connection to the database specified in the URL. For example, the following code shows how you obtain a Connection object to a MySQL database named Fred in a server called robusta. You also pass the user "admin" and the password "secret" to the getConnection method.

Connection connection =

DriverManager.getConnection("jdbc:mysql///robusta/Fred", "admin",

"secret");

You use the following code to get access to an ODBC database whose DSN is MarketingData, using the user name "sa" and password "1945":

Connection connection =

DriverManager.getConnection("jdbc:odbc:MarketingData", "sa",

"1945");

If the connection does not require you to login, you can pass null as arguments for the user and password parts.

The other overload of the getConnection method allows you to pass the user and password information in the URL. Its signature is as follows: public static Connection getConnection(String url)

throws SQLException

For example, you can use the following URL to connect to a MySQL database named Fred in robustathat requires the user name "me" and password "pwd":

DriverManager.getConnection("jdbc:mysql://robusta/Fred?user=me&passwo rd=pwd");

Or, to connect to an ODBC database named MarketingData that is accessible without a login name and password, you use the following:

Connection connection =

DriverManager.getConnection("jdbc:odbc:MarketingData");

If one of the drivers you loaded recognizes the JDBC URL supplied to the method

DriverManager.getConnection, that driver will establish a connection to the DBMS specified in the JDBC URL.

The getConnection method is probably the first and the last method of the DriverManager class you need to know to write Java programs that access databases. Other methods are needed only if you are writing a JDBC driver yourself.

75

The Connection object obtained through the DriverManager class's getConnection method is an open connection you can use to pass your SQL statements to the database server. As such, you do not need to have a special method to open a Connection.

Let's see what we can do with it in the next subsection: "Step 3 Creating a Statement."

Step 3: Creating a Statement

After you have a Connection object, your SQL skill takes over. Basically, you can pass any SQL statement that your database server understands. The level of understanding is different from one server to another. For example, an Oracle database is comfortable with subqueries, whereas a

MySQL server is not. Also, whether your SQL statement will be executed successfully on the database server depends on the permission level of the user who passed the query to the database.

If the user has the permission to view all the tables in the database, you can pass an SQL SELECT statement to it and expect some return. If the user has the permission to update records but not to delete records, you can only update, not delete, records. You should understand these factors before you program your JDBC code.

After you have a Connection object from the DriverManage.getConnection method, you are ready to pass a SQL statement. To do this, you need to create another JDBC object called Statement.

You can do this using the createStatement method of the Connection interface. Although there are two overloads of this method, the one that you almost always use is the no-argument overload. Its signature is as follows: public Statement createStatement() throws SQLException

Therefore, to create a Statement object from an open Connection object, you write the following:

// connection is an open Connection object

Statement statement = connection.createStatement();

Next, use the methods in the Statement class interface to manipulate your data or data structure.

You will use two important methods: executeUpdate and executeQuery. The signatures for both methods are as follows: public int executeUpdate(String sql) throws SQLException public ResultSet executeQuery(String sql) throws SQLException

The executeUpdate and executeQuery Methods

Both executeUpdate and executeQuery methods accept a String containing an SQL statement. The SQL statement does not end with a DBMS statement terminator, which can vary from DBMS to DBMS. For example, Oracle uses a semicolon (;) to indicate the end of a statement, and Sybase uses the word go. The driver you are using will automatically supply the appropriate statement terminator, and you will not need to include it in your JDBC code.

The executeUpdate method executes an SQL INSERT, UPDATE, or DELETE statement and also data definition language (DDL) statements to create, drop, and alter tables. This method returns the row count for INSERT, UPDATE, or DELETE statements or returns 0 for SQL statements that return nothing.

The executeQuery method executes an SQL SELECT statement that returns data. This method returns a single ResultSet object that is discussed next. The ResultSet object

76

contains the data produced by the given query. This method never returns a null.

For example, to create a table named Addresses with two fields, you can use the following code:

String sql = "CREATE TABLE Addresses " +

"(FirstName VARCHAR(32), LastName VARCHAR(32)"; statement.executeUpdate(sql);

And, to insert a record in the Addresses table, you use the following code:

String sql = "INSERT INTO Addresses " +

"VALUES ('Don', 'Bradman')"; statement.executeUpdate(sql);

You use executeQuery when you expect a ResultSet object. You learn about the ResultSet interface in the next section.

Tip

The close method of Statement releases immediately this Statement object's database and

JDBC resources instead of waiting for this to happen when it is automatically closed at garbage collection. Releasing resources as soon as you are finished with them is good practice—that way, you avoid tying up database resources.

Step 4: Creating a ResultSet

A ResultSet is the representation of a database table that is returned from a Statement object. A

ResultSet object maintains a cursor pointing to its current row of data. When the cursor is first returned, it is positioned before the first row. To access the first row of the ResultSet, you need to call the next() method of the ResultSet interface.

The next() method moves the cursor to the next row and can return either a true or false value. It returns true if the new current row is valid; it returns false if there are no more rows. Normally, you use this method in a while loop to iterate through the ResultSet object.

To get the data from the ResultSet, you can use one of many the getXXX methods of ResultSet, such as getInt, getLong, and so on. getShort You use the getInt method, for example, to obtain the value of the designated column in the current row of this ResultSet object as an int in the Java programming language. The getLong gets the cell data as a long, etc. The most commonly used method is getString, which returns the cell data as a String. Using getString is preferable in many cases because you don't need to worry about the data type of the table field in the database.

The getString method, similar to other getXXX methods, has two overloads that allow you to retrieve a cell's data by passing either the column index or the column name. The signatures of the two overloads of getString are as follows: public String getString(int columnIndex) throws SQLException public String getString(String columnName) throws SQLException

The following example illustrates the use of the next() method as well as the getString method.

The code is used to retrieve the FirstName and LastName columns from a table called Users. It then iterates the returned ResultSet and prints to the console all the first names and last names in the format "first name:last name". As you consider the following code, assume that you already have a Statement object called statement:

77

String sql = "SELECT FirstName, LastName FROM Users";

ResultSet resultSet = statement.executeQuery(sql); while (resultSet.next()) {

System.out.println(resultSet.getString(1) + ":" + resultSet.getString("LastName") );

}

The first column is retrieved by passing its column index, which is 1 for the first column. The second column is obtained by passing its column name.

Another important method is the close method that closes the ResultSet object when it is no longer used. The close method releases this ResultSet object's database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed. A ResultSet object will be closed automatically when it is garbage collected or when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results. Always call the close method to explicitly close the ResultSet object. Completing your example code, you should put the following code right after you finish accessing the ResultSet object: resultSet.close();

Note that if an SQL query results in zero row, the Statement object will return a ResultSet object containing no row, not a null.

Putting It All Together

Y

This section summarizes the four steps just discussed by presenting an example that uses the

FL password "s3m1c0nduct0r" to login to the database server. The SQL statement queries two

AM

Listing

4.1

.

Listing 4.1 Accessing a Database

TE try {

Class.forName("com.internetcds.jdbc.tds.Driver");

Connection con = DriverManager.getConnection(

"jdbc:freetds:sqlserver://Lampoon/Registration",

"sa", " s3m1c0nduct0r");

System.out.println("got connection");

Statement s = con.createStatement();

String sql =

"INSERT INTO UserReg VALUES ('a', 'b', '12/12/2001', 'f')";

s.executeUpdate(sql);

sql = "SELECT FirstName, LastName FROM Users";

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

System.out.println(rs.getString(1) + " " + rs.getString(2));

}

rs.close();

s.close();

con.close();

} catch (ClassNotFoundException e1) {

System.out.println(e1.toString());

Team-Fly ®

} catch (SQLException e2) {

System.out.println(e2.toString());

} catch (Exception e3) {

System.out.println(e3.toString());

}

On my machine, the code returns the following at the console. The result displayed depends on the data stored in your table, of course.

Jimmy Barnes

Richard Myers

George Lucas

A Database-Based Login Servlet

As your first example of connecting a database from a servlet, I would like to present the type of servlet that is probably built most often: a Login servlet. Unlike the Login servlet in

Chapter 3 ,

"Writing Servlet Applications," in which you hard-coded the user name and password that log in a user, this servlet matches the entered user name and password against the values of the UserName and Password columns in a table called Users. This table may have other columns, but those other columns are not relevant here.

When the user types the URL in the Location or Address box and first calls the servlet, its doGet method is invoked. The servlet then does what a login servlet should do—challenges the user to type in a user name and password. What the doGet does is call the private method sendLoginForm, which sends the HTML page for the user to login. sendLoginForm(response, false);

The sendLoginForm method accepts two arguments: a HttpServletResponse object that the method can use to send output to the browser, and a boolean. This boolean is a flag to indicate whether an error message should be sent along with the form. The error message tells the user that the previous login has failed. When the servlet is first called, of course, no error message is sent; thus the false value is given for the second argument of the sendLoginForm method called from doGet. The sendLoginForm method is given in

Listing 4.2

. The Login page is shown in

Figure 4.1

.

Figure 4.1. The database-based Login servlet.

79

Listing 4.2 The LoginServlet's sendLoginForm Method

private void sendLoginForm(HttpServletResponse response,

boolean withErrorMessage)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Login</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

if (withErrorMessage)

out.println("Login failed. Please try again.<BR>");

out.println("<BR>");

out.println("<BR><H2>Login Page</H2>");

out.println("<BR>");

out.println("<BR>Please enter your user name and password.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>User Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=userName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password:</TD>");

out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD ALIGN=RIGHT COLSPAN=2>");

80

out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

The user can then type the user name and password to login and click the Submit button. Upon submit, the doPost method is invoked. The first thing it does is obtain the userName and password from the HttpServletRequest object, as follows:

String userName = request.getParameter("userName");

String password = request.getParameter("password");

Then, the method passes the userName and password to the login method. This method returns true if the user name and password are correct; otherwise, it returns false. On successful login, the request is dispatched to another servlet, as follows:

RequestDispatcher rd =

request.getRequestDispatcher("AnotherServlet"); rd.forward(request, response);

If the login failed, the doPost calls the sendLoginForm method again, this time with an error message, as follows: sendLoginForm(response, true);

The doPost method is given in Listing 4.3

.

Listing 4.3 The LoginServlet's doPost Method

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

String userName = request.getParameter("userName");

String password = request.getParameter("password");

if (login(userName, password)) {

RequestDispatcher rd =

request.getRequestDispatcher("AnotherServlet");

rd.forward(request, response);

}

else {

sendLoginForm(response, true);

}

}

Here is the part that does the authentication: the login method. The method tries to authenticate the user by trying to retrieve a record whose UserName field is userName and Password field is the same as password. If a record is found, the login succeeds; otherwise, the login fails.

The login method first loads the JDBC driver, as follows:

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

81

This example uses a JDBC-ODBC driver; however, as you learned in the previous section, you can use any other driver without changing the rest of your code.

With a JDBC driver, you can create a Connection object and call its createStatement method to create a Statement object, as follows:

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

Note that you use the getConnection method overload that accepts an argument—the URL.

When a Statement object is available, you can call its executeQuery method, passing an SQL statement of the following syntax:

SELECT UserName FROM Users

WHERE UserName=userName

AND Password=password

To determine whether there is any record in the ResultSet object, you can call its next() method.

This method returns true if there is a record; otherwise, it returns false. On true, the login method returns a true, indicating a successful login. A false return value indicates otherwise. The login

method is given in Listing 4.4

, and the complete code for LoginServlet is given in

Listing 4.5

.

Listing 4.4 The LoginServlet's login Method

boolean login(String userName, String password) {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

System.out.println("got connection");

Statement s = con.createStatement();

String sql = "SELECT UserName FROM Users" +

" WHERE UserName='" + userName + "'" +

" AND Password='" + password + "'";

ResultSet rs = s.executeQuery(sql);

if (rs.next()) {

rs.close();

s.close();

con.close();

return true;

}

rs.close();

s.close();

con.close();

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

catch (SQLException e) {

System.out.println(e.toString());

}

catch (Exception e) {

System.out.println(e.toString());

}

return false;

82

}

Listing 4.5 The LoginServlet Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.sql.*; import java.util.*; public class LoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

sendLoginForm(response, false);

} private void sendLoginForm(HttpServletResponse response,

boolean withErrorMessage)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Login</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

if (withErrorMessage)

out.println("Login failed. Please try again.<BR>");

out.println("<BR>");

out.println("<BR><H2>Login Page</H2>");

out.println("<BR>");

out.println("<BR>Please enter your user name and password.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>User Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=userName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password:</TD>");

out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD ALIGN=RIGHT COLSPAN=2>");

out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

} public void doPost(HttpServletRequest request,

83

HttpServletResponse response)

throws ServletException, IOException {

String userName = request.getParameter("userName");

String password = request.getParameter("password");

if (login(userName, password)) {

RequestDispatcher rd =

request.getRequestDispatcher("AnotherServlet");

rd.forward(request, response);

}

else {

sendLoginForm(response, true);

}

}

boolean login(String userName, String password) {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

System.out.println("got connection");

Statement s = con.createStatement();

String sql = "SELECT UserName FROM Users" +

" WHERE UserName='" + userName + "'" +

" AND Password='" + password + "'";

ResultSet rs = s.executeQuery(sql);

if (rs.next()) {

rs.close();

s.close();

con.close();

return true;

}

rs.close();

s.close();

con.close();

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

catch (SQLException e) {

System.out.println(e.toString());

}

catch (Exception e) {

System.out.println(e.toString());

}

return false;

}

}

The Single Quote Factor

The LoginServlet servlet in the previous section works fine, but not perfectly. The servlet passes the user name and password to the login method and the SQL statement is composed on the fly.

For example, for user name equals "jeff" and password "java", the SQL statement is as follows:

SELECT UserName

FROM Users

84

WHERE UserName='jeff'

AND Password='java'

The values for the user name and the password are enclosed in the single quote pairs, as in 'jeff ' and 'java'. A username can be anything, including a name that includes an apostrophe, such as

o'connor. This is also true for passwords. If the username is "o'connor" and password is "java," the

SQL statement will become the following:

SELECT UserName

FROM Users

WHERE UserName='o'connor'

AND Password='java'

The database engine will encounter a single quote character after the o in "o'connor," and think it sees the end of the value for UserName, and expect a space after it. The engine finds a c instead, and this is confusing to the database server. An error will be thrown.

Does this mean you can't let users have a username that contains an apostrophe? Fortunately, there is a work around. If a string value in an SQL statement contains an apostrophe, you just need to prefix the apostrophe with another apostrophe, resulting in the following SQL statement:

SELECT UserName

FROM Users

WHERE UserName='o''connor'

AND Password='java'

Now everything works correctly. The LoginServlet servlet in the previous example should be fixed by passing all values entered by the user to a method called fixSQLFieldValue, which accepts a String. This method will replace every occurrence of a single quote character in the

String with two single quote characters. The fixSQLFieldValue takes a String whose value may contain a single quote character and doubles every occurrence of it.

The fixSQLFieldValue method uses a StringBuffer with an initial capacity of 1.1 times the length of the argument passed in String object. The 1.1 is based on the estimate that the resulting SQL statement will be at most 10 percent longer. Here is the code:

StringBuffer fixedValue = new StringBuffer((int) (length* 1.1));

The statement then tests each character of the String in a for loop. If a character is a single quote, it appends two single quote characters to the StringBuffer; otherwise, the character itself is appended, as you see here: for (int i=0; i<length; i++) {

char c = value.charAt(i);

if (c == '\'')

fixedValue.append("''");

else

fixedValue.append(c);

}

The fixSqlFieldValue method is given in Listing 4.6

.

Listing 4.6 The fixSqlFieldValue Method

public static String fixSqlFieldValue(String value) {

if (value == null)

return null;

85

int length = value.length();

StringBuffer fixedValue =

new StringBuffer((int) (length * 1.1));

for (int i=0; i<length; i++) {

char c = value.charAt(i);

if (c == '\'')

fixedValue.append("''");

else

fixedValue.append(c);

}

return fixedValue.toString();

}

The login method in Listing 4.5

and Listing 4.6

must pass the userName and password values before composing the SQL statement. With the fixSqlFieldValue method included in the

LoginServlet servlet, the part that forms the SQL statement should be modified into the following line:

String sql = "SELECT UserName FROM Users" +

" WHERE UserName='" + fixSqlFieldValue(userName) + "'" +

" AND Password='" + fixSqlFieldValue(password) + "'";

Clearly, the fixSqlFieldValue method should be called every time you compose an SQL statement that includes a value from the user input. The method has been included in the StringUtil class that is part of the com.brainysoftware.java.package included in the CD of this book. The use of this method in the next sample code will be from this package. This at least saves having to write the same code in all classes that need it. This method in the StringUtil class is made static so that you can just call it with the following code: import com.brainysoftware.java.StringUtil

StringUtil.fixSqlFieldValue(string)

To use this class, you need to create a directory structure under the /WEB-INF/classes directory under your application directory; that is, you need to create a directory called com under the classes directory, the brainysoftware directory under com, the java directory under the brainysoftware directory, and copy the StringUtil.class there.

Inserting Data into a Table with RegistrationServlet

Inserting a record into a table is a common database task. An example of this is a servlet named

RegistrationServlet that takes user input to insert a record into a Users table. The table itself has columns as described in

Table 4.1

.

Id

Column

Name

Column

Type

Table 4.1. The Users Table

Description

Numeric An autonumber that serves as the primary key and is autoincremented by the database.

FirstName String

LastName String

UserName String

Password String

The first name of the user.

The last name of the user.

The user name for the user to login. No duplicate allowed.

The password for the user to login.

86

To insert a record containing a user's details, you need to retrieve the values entered by the user and compose an SQL Statement, such as the following:

INSERT INTO Users

(FirstName, LastName, UserName, Password)

VALUES

(firstName, lastName, userName, password)

The Id column is not included because it's an autonumber. A new unique number will be generated by the database server automatically for the Id column when you insert a new record into the table. Also note that the UserName column value must be unique. No two users can have the same user name.

When first called, the RegistrationServlet displays an HTML form with four text boxes, as shown in

Figure 4.2

.

Figure 4.2. The RegistrationServlet.

The user can then fill in the necessary details: first name, last name, and a self-chosen user name and password. The user name must be unique. If the user enters a user name that's already taken, the servlet will display an error message and present the same form again, with the previously

typed in values retained (see Figure 4.3

).

Figure 4.3. Failed registration because the user name has been taken.

87

entered values retained. present a clean form. The user then can enter another user's details if desired.

AM method accepts three arguments: an HttpServletRequest object, an HttpServletResponse object,

TE

Listing 4.7

. Note that when you need to

display a value in an HTML input box, you need to call the encodeHtmlTag method (which is also part of the com.brainysoftware.java.StringUtil class) just in case the value contains one of the four

HTML special characters, as described in

Chapter 3 . The RegistrationServlet therefore imports the

com.brainysoftware.java.StringUtil class.

Listing 4.7 The sendRegistrationForm Method

private void sendRegistrationForm(HttpServletRequest request,

HttpServletResponse response, boolean displayPreviousValues)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("<BR><H2>Registration Page</H2>");

out.println("<BR>Please enter the user details.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name</TD>");

out.print("<TD><INPUT TYPE=TEXT Name=firstName");

if (displayPreviousValues)

out.print(" VALUE=\"" +

Team-Fly ®

StringUtil.encodeHtmlTag(firstName) + "\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name</TD>");

out.print("<TD><INPUT TYPE=TEXT Name=lastName");

if (displayPreviousValues)

out.print(" VALUE=\"" +

StringUtil.encodeHtmlTag(lastName) + "\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>User Name</TD>");

out.print("<TD><INPUT TYPE=TEXT Name=userName");

if (displayPreviousValues)

out.print(" VALUE=\"" +

StringUtil.encodeHtmlTag(userName) + "\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password</TD>");

out.print("<TD><INPUT TYPE=PASSWORD Name=password");

if (displayPreviousValues)

out.print(" VALUE=\"" +

StringUtil.encodeHtmlTag(password) + "\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD><INPUT TYPE=RESET></TD>");

out.println("<TD><INPUT TYPE=SUBMIT></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

out.println("<BR>");

out.println("<BR>");

}

Unlike the form in the LoginServlet, however, the registration form does not include the <HTML> tag, the head section of the HTML, and the opening <BODY> tag. Nor does it contain the closing

</BODY> and </HTML> tags. Page headers can be sent to the browser by calling the sendPageHeader method, whose code is given in

Listing 4.8

.

Listing 4.8 The sendPageHeader Method

private void sendPageHeader(HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Registration Page</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

89

}

The page footer can be sent by calling the sendPageFooter method, listed in Listing 4.9

.

Listing 4.9 The sendPageFooter Method

private void sendPageFooter(HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

When first called, the servlet invokes its doGet method to send the registration form plus all necessary HTML tags to the browser. The doGet method is given in

Listing 4.10

.

Listing 4.10 The doGet Method

public void doGet(HttpServletRequest request, HttpServletResponse

response) throws ServletException, IOException {

sendPageHeader(response);

sendRegistrationForm(request, response, false);

sendPageFooter(response);

}

When the user submits the form, the doPost method is invoked. The doPost method first retrieves the values from the users, as follows: firstName = request.getParameter("firstName"); lastName = request.getParameter("lastName"); userName = request.getParameter("userName"); password = request.getParameter("password");

After opening a Connection object and creating a Statement object, the method needs to determine whether the user name has already been taken. It does so by trying to retrieve a record whose

UserName field value is userName, as follows:

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

String sql = "SELECT UserName FROM Users" +

" WHERE userName='" +

StringUtil.fixSQLFieldValue(userName) + "'";

ResultSet rs = s.executeQuery(sql);

If the ResultSet object returned by the Statement interface's executeQuery method has a record, its next method will return true, indicating that the user name has already been taken; otherwise, false is returned.

If the user name has been taken, a message of "The user name… has been taken" is assigned to the message String and the error flag is set. If not, an SQL statement will be composed on the fly and the executeUpdate method of the Statement object will be called to insert a new record into the

Users table, as seen in

Figure 4.4

.

Figure 4.4. Successful registration.

90

if (rs.next()) {

rs.close();

message = "The user name <B>" +

StringUtil.encodeHtmlTag(userName) +

"</B> has been taken. Please select another name.";

error = true;

} else {

rs.close();

sql = "INSERT INTO Users" +

" (FirstName, LastName, UserName, Password)" +

" VALUES" +

" ('" + StringUtil.fixSQLFieldValue(firstName) + "'," +

" '" + StringUtil.fixSQLFieldValue(lastName) + "'," +

" '" + StringUtil.fixSQLFieldValue(userName) + "'," +

" '" + StringUtil.fixSQLFieldValue(password) + "')";

int i = s.executeUpdate(sql);

if (i == 1) {

message = "Successfully added one user.";

}

}

The last part of the doPost method checks whether the message is null and whether the error flag has been set. If the message is not null, it is sent to the browser, as you see here: if (message != null) {

PrintWriter out = response.getWriter();

out.println("<B>" + message + "</B><BR>");

out.println("<HR><BR>");

}

If the error is set, the registration form is sent with the last argument equal to true, indicating the sendRegistrationForm to display the previously entered values. Otherwise, the sendRegistrationForm method is sent with the false value for the last argument, as you see here:

91

if (error == true)

sendRegistrationForm(request, response, true);

else

sendRegistrationForm(request, response, false);

sendPageFooter(response);

}

The doPost method is given in Listing 4.11

.

Listing 4.11 The doPost Method

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

sendPageHeader(response);

firstName = request.getParameter("firstName");

lastName = request.getParameter("lastName");

userName = request.getParameter("userName");

password = request.getParameter("password");

boolean error = false;

String message = null;

try {

Connection con = DriverManager.getConnection("jdbc:odbc:JavaWeb");

System.out.println("got connection");

Statement s = con.createStatement();

String sql = "SELECT UserName FROM Users" +

" WHERE userName='" + StringUtil.fixSQLFieldValue(userName) +

"'";

ResultSet rs = s.executeQuery(sql);

if (rs.next()) {

rs.close();

message = "The user name <B>"+

StringUtil.encodeHtmlTag(userName) + "</B> has been taken. Please select another name.";

error = true;

}

else {

rs.close();

sql = "INSERT INTO Users" +

" (FirstName, LastName, UserName, Password)" +

" VALUES" +

" ('" + StringUtil.fixSQLFieldValue(firstName) + "'," +

" '" + StringUtil.fixSQLFieldValue(lastName) + "'," +

" '" + StringUtil.fixSQLFieldValue(userName) + "'," +

" '" + StringUtil.fixSQLFieldValue(password) + "')";

int i = s.executeUpdate(sql);

if (i == 1) {

message = "Successfully added one user.";

}

}

s.close();

con.close();

}

catch (SQLException e) {

message = "Error." + e.toString();

error = true;

92

}

catch (Exception e) {

message = "Error." + e.toString();

error = true;

}

if (message != null) {

PrintWriter out = response.getWriter();

out.println("<B>" + message + "</B><BR>");

out.println("<HR><BR>");

}

if (error == true)

sendRegistrationForm(request, response, true);

else

sendRegistrationForm(request, response, false);

sendPageFooter(response);

}

You may have noticed that the code that loads the JDBC driver is missing from the doPost method.

Instead, it has been moved to the init method of the servlet. The JDBC driver needs to be loaded only once, so it is appropriate to put it in the init method, which is only called once during the life cycle of the servlet. The init method is given in

Listing 4.12

.

Listing 4.12 The init Method of the RegistrationServlet

public void init() {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

System.out.println("JDBC driver loaded");

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

}

The complete code of the RegistrationServlet servlet is given in Listing 4.13

.

Listing 4.13 The RegistrationServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import com.brainysoftware.java.StringUtil; public class RegistrationServlet extends HttpServlet {

private String firstName = "";

private String lastName = "";

private String userName = "";

private String password = "";

public void init() {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

System.out.println("JDBC driver loaded");

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

93

}

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {

sendPageHeader(response);

sendRegistrationForm(request, response, false);

sendPageFooter(response);

}

/**Process the HTTP Post request*/

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

sendPageHeader(response);

firstName = request.getParameter("firstName");

lastName = request.getParameter("lastName");

userName = request.getParameter("userName");

password = request.getParameter("password");

boolean error = false;

String message = null;

try {

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

System.out.println("got connection");

Statement s = con.createStatement();

String sql = "SELECT UserName FROM Users" +

" WHERE userName='" + StringUtil.fixSQLFieldValue(userName) +

"'";

ResultSet rs = s.executeQuery(sql);

if (rs.next()) {

rs.close();

message = "The user name <B>" +

StringUtil.encodeHtmlTag(userName) +

"</B> has been taken. Please select another name.";

error = true;

}

else {

rs.close();

sql = "INSERT INTO Users" +

" (FirstName, LastName, UserName, Password)" +

" VALUES" +

" ('" + StringUtil.fixSQLFieldValue(firstName) + "'," +

" '" + StringUtil.fixSQLFieldValue(lastName) + "'," +

" '" + StringUtil.fixSQLFieldValue(userName) + "'," +

" '" + StringUtil.fixSQLFieldValue(password) + "')";

int i = s.executeUpdate(sql);

if (i == 1) {

message = "Successfully added one user.";

}

}

s.close();

con.close();

}

catch (SQLException e) {

message = "Error." + e.toString();

error = true;

94

}

catch (Exception e) {

message = "Error." + e.toString();

error = true;

}

if (message != null) {

PrintWriter out = response.getWriter();

out.println("<B>" + message + "</B><BR>");

out.println("<HR><BR>");

}

if (error == true)

sendRegistrationForm(request, response, true);

else

sendRegistrationForm(request, response, false);

sendPageFooter(response);

}

/**

* Send the HTML page header, including the title

* and the <BODY> tag

*/

private void sendPageHeader(HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Registration Page</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

}

/**

* Send the HTML page footer, i.e. the </BODY>

* and the </HTML>

*/

private void sendPageFooter(HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

/**Send the form where the user can type in

* the details for a new user

*/

private void sendRegistrationForm(HttpServletRequest request,

HttpServletResponse response, boolean displayPreviousValues)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("<BR><H2>Registration Page</H2>");

out.println("<BR>Please enter the user details.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name</TD>");

out.print("<TD><INPUT TYPE=TEXT Name=firstName");

95

if (displayPreviousValues)

out.print(" VALUE=\"" + StringUtil.encodeHtmlTag(firstName) +

"\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name</TD>");

out.print("<TD><INPUT TYPE=TEXT Name=lastName");

if (displayPreviousValues)

out.print(" VALUE=\"" + StringUtil.encodeHtmlTag(lastName) +

"\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>User Name</TD>");

out.print("<TD><INPUT TYPE=TEXT Name=userName");

if (displayPreviousValues)

out.print(" VALUE=\"" + StringUtil.encodeHtmlTag(userName) +

"\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password</TD>");

out.print("<TD><INPUT TYPE=PASSWORD Name=password");

if (displayPreviousValues)

out.print(" VALUE=\"" + StringUtil.encodeHtmlTag(password) +

"\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD><INPUT TYPE=RESET></TD>");

out.println("<TD><INPUT TYPE=SUBMIT></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

out.println("<BR>");

out.println("<BR>");

}

}

Displaying All Records

Displaying data is inevitable when you program with a database. You can achieve this task easily with the knowledge of JDBC you have learned so far. Which data you need to display depends on your application. In this section and the next, you will display data and format it in an HTML table.

This section displays all records in the Users table, and the next section implements a Search Page that displays data selectively.

Displaying all records could not be simpler. You need only to open a Connection, create a

Statement object, and execute a query to produce a ResultSet object. You then iterate each record

96

in a while loop. The code is very straightforward and is given in

Listing 4.14

. The output of this

servlet is shown in

Figure 4.5

.

Figure 4.5. Displaying all records from a table.

Listing 4.14 Displaying All Records in the Users Table

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.sql.*; import com.brainysoftware.java.StringUtil; public class DataViewerServlet extends HttpServlet {

/**Load JDBC driver*/

public void init() {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

System.out.println("JDBC driver loaded");

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

}

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Display All Users</TITLE>");

out.println("</HEAD>");

97

out.println("<BODY>");

out.println("<CENTER>");

out.println("<BR><H2>Displaying All Users</H2>");

out.println("<BR>");

out.println("<BR>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TH>First Name</TH>");

out.println("<TH>Last Name</TH>");

out.println("<TH>User Name</TH>");

out.println("<TH>Password</TH>");

out.println("</TR>");

String sql = "SELECT FirstName, LastName, UserName, Password" +

" FROM Users";

try {

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

System.out.println("got connection");

Statement s = con.createStatement();

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

out.println("<TR>");

out.println("<TD>" +

out.println("<TD>" +

out.println("<TD>" +

StringUtil.encodeHtmlTag(rs.getString(3)) + "</TD>");

out.println("<TD>" +

out.println("</TR>");

}

rs.close();

s.close();

con.close();

TE

}

catch (SQLException e) {

}

catch (Exception e) {

}

out.println("</TABLE>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

public void doPost(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

doGet(request, response);

}

}

Search Page

Team-Fly ®

In many cases, displaying all records is not preferable. More often than not, you need only to display data selectively. For example, someone might try to find the details of a person called

Jones without knowing the person's first name. Displaying all the users does not help much, especially if you have a large number of records in the table. The page is more useful if you can let the user specify a keyword and display all records that match the keyword.

In this example, you will write a SearchServlet that lets the user enter a keyword that could be the first name, the last name, or even part of the first name or last name. The appearance of this servlet

output is shown in Figure 4.6

.

Figure 4.6. The SearchServlet.

The main part of this servlet is the sendSearchResult method that connects to the database, executes the following SQL statement, and sends the result to the browser.

SELECT FirstName, LastName, UserName, Password

FROM Users

WHERE FirstName LIKE '%keyword%'

OR LastName LIKE '%keyword%'

The code is given in Listing 4.15

.

Listing 4.15 The SearchServlet Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import com.brainysoftware.java.StringUtil; public class SearchServlet extends HttpServlet { private String keyword = "";

99

public void init() {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

System.out.println("JDBC driver loaded");

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

}

/**Process the HTTP Get request*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

sendPageHeader(response);

sendSearchForm(response);

sendPageFooter(response);

}

/**Process the HTTP Post request*/ public void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

keyword = request.getParameter("keyword");

sendPageHeader(response);

sendSearchForm(response);

sendSearchResult(response);

sendPageFooter(response);

} void sendSearchResult(HttpServletResponse response)

throws IOException {

PrintWriter out = response.getWriter();

try {

Connection con = DriverManager.getConnection("jdbc:odbc:JavaWeb");

System.out.println("got connection");

Statement s = con.createStatement();

out.println("<TABLE>");

out.println("<TR>");

out.println("<TH>First Name</TH>");

out.println("<TH>Last Name</TH>");

out.println("<TH>User Name</TH>");

out.println("<TH>Password</TH>");

out.println("</TR>");

String sql = "SELECT FirstName, LastName, UserName, Password" +

" FROM Users" +

" WHERE FirstName LIKE '%" +

StringUtil.fixSqlFieldValue(keyword) + "%'" +

" OR LastName LIKE '%" + StringUtil.fixSqlFieldValue(keyword) +

"%'";

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

out.println("<TR>");

out.println("<TD>" + StringUtil.encodeHtmlTag(rs.getString(1))

+ "</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(rs.getString(2))

+ "</TD>");

100

out.println("<TD>" + StringUtil.encodeHtmlTag(rs.getString(3))

+ "</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(rs.getString(4))

+ "</TD>");

out.println("</TR>");

}

s.close();

con.close();

}

catch (SQLException e) {

}

catch (Exception e) {

}

out.println("</TABLE>");

}

/**

* Send the HTML page header, including the title

* and the <BODY> tag

*/ private void sendPageHeader(HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Displaying Selected Record(s)</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

}

/**

* Send the HTML page footer, i.e. the </BODY>

* and the </HTML>

*/ private void sendPageFooter(HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

/**Send the form where the user can type in

* the details for a new user

*/ private void sendSearchForm(HttpServletResponse response)

throws IOException {

PrintWriter out = response.getWriter();

out.println("<BR><H2>Search Form</H2>");

out.println("<BR>Please enter the first name, last name or part of any.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.print("Name: <INPUT TYPE=TEXT Name=keyword");

out.println(" VALUE=\"" + StringUtil.encodeHtmlTag(keyword) + "\"");

out.println(">");

out.println("<INPUT TYPE=SUBMIT>");

101

out.println("</FORM>");

out.println("<BR>");

out.println("<BR>");

}

}

An Online SQL Tool

When working with a database, you may want to change data in a database for testing. When connecting to a database from a servlet, however, it is often the case that the database resides somewhere beyond your physical reach. Oftentimes, the only way to connect to the database is through the database client program. Of course, the client program needs to be installed on the computer you are using to connect to the database. This is not good if you need to be mobile, or if you need to be able to connect to the database from different locations. Because the database is available to a servlet, you can also make it available online.

The program given in this application is an online SQL tool that lets you manipulate your data or data structure by using a web browser. You can type in any SQL statement and send it to the server to be executed by the database server. If the database server returns a ResultSet, the tool displays it in the form of a table. If the database server sends an error message, that also is displayed in the form. The form is shown in

Figure 4.7

.

Figure 4.7. The online SQL Tool.

The user can type an SQL statement in the box. Figures

4.8

and 4.9

show how the form looks

when the database server returns a ResultSet and when it notifies the user that it has successfully executed an SQL that affects one record.

102

Figure 4.8. The SQL Tool with a returned ResultSet.

Figure 4.9. The SQL Tool after inserting a new record.

When first called, the servlet will invoke the doGet method that calls the sendSqlForm. The latter

sends the SQL form to the browser. The doGet method is given in Listing 4.16

.

Listing 4.16 The doGet Method of the SQLToolServlet

103

public void doGet(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException {

sendSqlForm(request, response);

}

The sendSqlForm method does what its name implies: it sends the SQL form. The method is given in

Listing 4.17

.

Listing 4.17 The sendSqlForm Method

private void sendSqlForm(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>SQL Tool Servlet</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<BR><H2>SQL Tool</H2>");

out.println("<BR>Please type your SQL statement in the following box.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.println("<TEXTAREA NAME=sql COLS=80 ROWS=8>");

String sql = request.getParameter("sql");

// Reprint the previously entered SQL in the TextArea

if (sql != null)

out.println(sql);

out.println("</TEXTAREA>");

out.println("<BR>");

out.println("<INPUT TYPE=SUBMIT VALUE=Execute>");

out.println("</FORM>");

out.println("<BR>");

out.println("<HR>");

out.println("<BR>");

if (sql != null) {

executeSql(sql.trim(), response);

}

out.println("</BODY>");

out.println("</HTML>");

}

The sendSqlForm method retrieves the sql value from the HttpServletRequest object. When this method is called from the doGet method, the sql parameter is null. When called from the doPost method, however, the sql parameter is not null. When the latter is the case, the executeSql method is called.

The executeSql method accepts a String containing the SQL statement, which it tries to execute, and a HttpServletResponse object that it can write to for sending text to the browser. The executeSql method is given in

Listing 4.18

.

104

Listing 4.18 The executeSql Method

public void executeSql(String sql, HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

try {

//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

System.out.println("got connection");

Statement s = con.createStatement();

if (sql.toUpperCase().startsWith("SELECT")) {

out.println("<TABLE BORDER=1>");

ResultSet rs = s.executeQuery(sql);

ResultSetMetaData rsmd = rs.getMetaData();

// Write table headings

int columnCount = rsmd.getColumnCount();

out.println("<TR>");

for (int i=1; i<=columnCount; i++) {

out.println("<TD><B>" + rsmd.getColumnName(i) +

"</B></TD>\n");

}

out.println("</TR>");

while (rs.next()) {

out.println("<TR>");

for (int i=1; i<=columnCount; i++) {

out.println("<TD>"+

StringUtil.encodeHtmlTag(rs.getString(i)) + "</TD>" );

}

out.println("</TR>");

}

rs.close();

out.println("</TABLE>");

}

else {

int i = s.executeUpdate(sql);

out.println("Record(s) affected: " + i);

}

s.close();

con.close();

out.println("</TABLE>");

}

catch (SQLException e) {

out.println("<B>Error</B>");

out.println("<BR>");

out.println(e.toString());

}

catch (Exception e) {

out.println("<B>Error</B>");

out.println("<BR>");

out.println(e.toString());

}

}

}

The complete code of the SQLToolServlet is given in Listing 4.19

.

105

Listing 4.19 The SQLToolServlet Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import com.brainysoftware.java.StringUtil; public class SQLToolServlet extends HttpServlet {

/**Load the JDBC driver*/

public void init() {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

System.out.println("JDBC driver loaded");

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

}

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

sendSqlForm(request, response);

}

/**Process the HTTP Post request*/

public void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

sendSqlForm(request, response);

}

/**Send the form where the user can type in

* an SQL statement to be processed

*/

private void sendSqlForm(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>SQL Tool Servlet</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<BR><H2>SQL Tool</H2>");

out.println("<BR>Please type your SQL statement in

Âthe following box.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.println("<TEXTAREA NAME=sql COLS=80 ROWS=8>");

String sql = request.getParameter("sql");

// Reprint the previously entered SQL in the TextArea

if (sql != null)

out.println(sql);

106

out.println("</TEXTAREA>");

out.println("<BR>");

out.println("<INPUT TYPE=SUBMIT VALUE=Execute>");

out.println("</FORM>");

out.println("<BR>");

out.println("<HR>");

out.println("<BR>");

if (sql != null) {

executeSql(sql.trim(), response);

}

out.println("</BODY>");

out.println("</HTML>");

}

/**execute the SQL */

public void executeSql(String sql, HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

try {

//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

System.out.println("got connection");

Statement s = con.createStatement();

if (sql.toUpperCase().startsWith("SELECT")) {

out.println("<TABLE BORDER=1>");

ResultSet rs = s.executeQuery(sql);

ResultSetMetaData rsmd = rs.getMetaData();

// Write table headings

int columnCount = rsmd.getColumnCount();

out.println("<TR>");

for (int i=1; i<=columnCount; i++) {

out.println("<TD><B>" + rsmd.getColumnName(i) +

"</B></TD>\n");

}

out.println("</TR>");

while (rs.next()) {

out.println("<TR>");

for (int i=1; i<=columnCount; i++) {

out.println("<TD>" +

StringUtil.encodeHtmlTag(rs.getString(i)) + "</TD>" );

}

out.println("</TR>");

}

rs.close();

out.println("</TABLE>");

}

else {

int i = s.executeUpdate(sql);

out.println("Record(s) affected: " + i);

}

s.close();

con.close();

out.println("</TABLE>");

}

catch (SQLException e) {

107

out.println("<B>Error</B>");

out.println("<BR>");

out.println(e.toString());

}

catch (Exception e) {

out.println("<B>Error</B>");

out.println("<BR>");

out.println(e.toString());

}

}

}

Should I Keep the Connection Open?

All the examples given up to this point in this chapter have closed the Connection object after the servlet services the request. However, you might ask the following question: If the servlet is called more than once and it opens a Connection object with the same arguments (url, user, and password) each time, wouldn't it better to leave the Connection object open for future use; that is, for when the servlet is called again? programming. Being able to save CPU cycles by keeping the Connection object is very tempting.

In many reference books, however, including those of non-Java web programming, you are always

FL

Actually, an open connection is not taboo. Whether to leave the Connection object open really the response time will be faster if you can access the database without having to open a

TE

AM

Connection object. For example, you can make the object variable of the Connection object class servlet first initializes. On subsequent requests, the Connection is already open, so the user will experience faster response.

A servlet can be accessed by multiple users at the same time, however. The bad news is that the underlying architecture of the Connection object will allow only one query to be processed at a time. As a result, only one user can use the connection at a time. The others will have to queue.

Considering that modern databases allow multiple connections, this is really a waste.

The conclusion is that if your servlet is accessed only by a single user at a time, leaving the

Connection object open makes the response time faster. If you can't guarantee that there will not be simultaneous accesses to the servlet, however, response time will start to decrease because the second and subsequent users have to wait until the first user gets serviced.

That's why, except in some rare cases, you should always close your Connection object. Rather than having the Connection object open, a technique called connection pooling is implemented by the driver to manage the Connection objects to a database so that multiple connections can be pooled. A connection can be used and, when finished, returned to the pool to be used by another request.

Team-Fly ®

Transactions

A transaction is a unit of work that can comprise one or more SQL operations. In the examples you have seen so far, every SQL operation is executed and the change is committed (made permanent) on the database right after the SQL statement is executed.

In some cases, however, a set of SQL operations must succeed or fail as a whole. If one of the

SQL statements fails, the other SQL statements in the group must also be rolled back. Consider the following scenario.

In an online store a customer purchases several books. When the customer checks out and pays using a credit card, the following things must happen:

1. A record must be added to the Orders table specifying the order, including the delivery address and the credit card details. This operation results in an OrderId used to identify each item in the OrderDetails table.

2. A record must be inserted into the OrderDetails table for each purchase item. Each item is linked to the Orders table using the OrderId value returned by the previous SQL operation.

Now, if everything goes smoothly, both SQL statements will be executed successfully in the database. Things can go wrong, however. Say, for example, the first operation is committed successfully but the second SQL statement fails. In this case, the order details are lost and the customer won't get anything. The customer's credit card will still be debited by the amount of the purchase, however, because a record is added to the Orders table.

In this case, you want both SQL statements to succeed or fail as a whole. You can do this using a transaction. Upon a failed transaction, you can notify the customer so that he or she can try to check out again.

By default, a Connection object's auto-commit state is true, meaning that the database is updated when an SQL statement is executed. If you want to group a set of SQL statements in one transaction, you must first tell the Connection object not to update the change until it is explicitly notified to do so. You do this by calling the setAutoCommit method and passing false as its argument, as follows: connection.setAutoCommit(false);

Then, you can execute all the SQL statements in the group normally, using the executeQuery and the updateQuery methods. After the last call to the executeQuery or the updateQuery method, you call the commit method of the Connection object to make the database changes permanent, such as connection.commit();

If you don't call the commit method within a specified time, all SQL statements will be rolled back after calling the setAutoCommit method. Alternatively, you can roll back the transaction explicitly by calling the Connection object's rollback method: connection.rollback();

Note

You learn how to use transactions further when you build a shopping cart in

Chapter 18 ,

"Developing E-Commerce Applications."

109

Connection Pooling

Creating a Connection object is one of the most expensive operations in database programming.

This is especially true when the Connection object is used for only one or two SQL operations, as demonstrated in the servlets discussed in this chapter.

To make the use of Connection objects more efficient, those objects are not pooled. When the application starts, a certain number of Connection objects are created and stored in a pool. When a database client, such as a servlet, needs to use a Connection object, it does not create the object but instead requests one from the pool. When the client is finished with it, the Connection object is returned to the pool.

You can create a pool of Connection objects programmatically; however, there is an easier and more robust way: by using the connection pooling feature of the JDBC Optional Package. The good thing about this feature is that the connection pooling is transparent. There is no single line of code that the programmer needs to change to use it.

To use the connection pooling feature in the javax.sql package, you need to connect to the data source using the javax.sql.DataSource interface. The code for getting a connection utilizes JNDI, which is briefly discussed in

Chapter 28 , "Enterprise JavaBeans." The code is as follows:

Context context = new InitialContext();

DataSource ds = (DataSource)context.lookup("jdbc/myDB");

Connection connection = ds.getConnection(user, password)

Summary

Database access is one of the most important aspects of web programming. Java has its own technology for this called JDBC, whose functionality is wrapped in a package called java.sql. In this chapter, you have seen various members of this package and learned how to use them. You also have learned how to create servlets that access a database. A couple of servlets have been created that illustrate various real-life applications.

110

Chapter 5. Session Management

The Hypertext Transfer Protocol (HTTP) is the network protocol that web servers and client browsers use to communicate with each other. HTTP is the language of the web. HTTP connections are initiated by a client browser that sends an HTTP request. The web server then responds with an HTTP response and closes the connection. If the same client requests another resource from the server, it must open another HTTP connection to the server. The server always closes the connection as soon as it sends the response, whether or not the browser user needs some other resource from the server.

This process is similar to a telephone conversation in which the receiver always hangs up after responding to the last remark/question from the caller. For example, a call goes something like this:

Caller dials. Caller gets connected.

Caller: "Hi, good morning."

Receiver: "Good morning."

Receiver hangs up.

Caller dials again. Caller gets connected.

Caller: "May I speak to Dr. Zeus, please?"

Receiver: "Sure."

Receiver hangs up.

Caller dials again, and so on, and so on.

Putting this in a web perspective, because the web server always disconnects after it responds to a request, the web server does not know whether a request comes from a user who has just requested the first page or from a user who has requested nine other pages before. As such, HTTP is said to be stateless.

Being stateless has huge implications. Consider, for example, a user who is shopping at an online store. As usual, the process starts with the user searching for a product. If the product is found, the user then enters the quantity of that product into the shopping cart form and submits it to the server. But, the user is not yet checking out—she still wants to buy something else. So she searches the catalog again for the second product.The first product order has now been lost, however, because the previous connection was closed and the web server does not remember anything about the previous connection.

The good news is that web programmers can work around this, and this chapter discusses techniques for that. The solution is called user session management. The web server is forced to associate HTTP requests and client browsers.

What Is Session Management?

111

You know that HTTP statelessness has a deep impact on web application programming. To see the problem more clearly, consider the LoginServlet in

Chapter 3 , "Writing Servlet Applications," and

Chapter 4 , "Accessing Databases with JDBC." The skeleton is presented here:

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

sendLoginForm(response, false);

} public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

String userName = request.getParameter("userName");

String password = request.getParameter("password");

if (login(userName, password)) {

// login successful, display the information

}

else {

// login failed, re-send the Login form

sendLoginForm(response, true);

}

}

The Login servlet is used to require users to enter a valid user name and pass-word before they can see some information. When a user first requests the servlet, the Login form is displayed. The user then can enter a user name and password and submit the form. Assuming that the form uses the

POST method, the user information is captured in the doPost method, which does the authentication by calling the login method. If the login was successful, the information is displayed. If not, the Login form is sent again.

What if you have another servlet that also only allows authorized users to view the information?

This second servlet does not know whether the same user has successfully logged in to the first servlet. Consequently, the user will be required to log in again!

This is, of course, not practical. Every time a user goes to request a protected servlet, he or she has to login again even though all the servlets are part of the same application. This easily pushes the user to the edge of frustration and most likely results in a lost customer.

Fortunately, there are ways to get around this, using techniques for remembering a user's session.

Once users have logged in, they do not have to login again. The application will remember them.

This is called session management.

Session management, also called session tracking, goes beyond simply remembering a user who has successfully logged in. Anything that makes the application remember information that has been entered or requested by the user can be considered session management. Session management does not change the nature of HTTP statelessness—it simply provides a way around it.

By principle, you manage a user's session by performing the following to servlets/pages that need to remember a user's state:

1. When the user requests a servlet, in addition to sending the response, the servlet also sends a token or an identifier.

112

2. If the user does not come back with the next request for the same or a different servlet, that is fine. If the user does come back, the token or identifier is sent back to the server.

Upon encountering the token, the next servlet should recognize the identifier and can do a certain action based on the token. When the servlet responds to the request, it also sends the same or a different token. This goes on and on with all the servlets that need to remember a user's session.

You will use four techniques for session management. They operate based on the same principle, although what is passed and how it is passed is different from one to another. The techniques are as follows:

URL rewriting

Hidden fields

Cookies

Session objects

Which technique you use depends on what you need to do in your application. Each of the

techniques is discussed in the sections below. The section, " Knowing Which Technique to Use ,"

concludes the chapter.

URL Rewriting

With URL rewriting, you append a token or identifier to the URL of the next servlet or the next resource. You can send parameter name/value pairs using the following format: url?name1=value1&name2=value2&…

A name and a value is separated using an equal sign (=); a parameter name/value pair is separated from another parameter name/value pair using the ampersand (&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a servlet, you can use the HttpServletRequest interface's getParameter method to obtain a parameter value. For instance, to obtain the value of the second parameter, you write the following: request.getParameter(name2);

The use of URL rewriting is easy. When using this technique, however, you need to consider several things:

The number of characters that can be passed in a URL is limited. Typically, a browser can pass up to 2,000 characters.

The value that you pass can be seen in the URL. Sometimes this is not desirable. For example, some people prefer their password not to appear on the URL.

You need to encode certain characters—such as & and ? characters and white spaces— that you append to a URL.

As an example, you will build an application that you can use to administer all registered persons in a database. The application uses the Users table created in

Chapter 4 and allows you to do the

following:

1. Enter a keyword that will become the search key for the first name and the last name columns of the Users table.

2. Display all persons that match the keyword.

113

3. In addition to the data for each record, there are Delete and Update hyperlinks. The user id is included in the hyperlinks.

4. If the Delete hyperlink is clicked, the corresponding person will be deleted from the Users table.

5. If the Update hyperlink is clicked, the corresponding person's details will be displayed in a form. You then can change the data and submit the form to update that person's record.

The Administration application is shown in Figures

5.1

, 5.2

, and

5.3

.

Figure 5.1. The Administration's Search page.

Figure 5.2. The Administrations Delete page.

114

Figure 5.3. The Administration's Update page.

The first servlet, the SearchServlet, is similar to the one in

Chapter 4 . The doGet method sends the

form for the user to type in a keyword. This keyword could be a first name, a last name, or part of a first name or a last name. To allow more flexibility, this example separates the form from the rest of the page. Therefore, you send the page header and page footer separately. The doGet

method is given in Listing 5.1

.

115

Listing 5.1 The doGet Method of the SearchServlet

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

sendPageHeader(response);

sendSearchForm(response);

sendPageFooter(response);

}

The page header contains the head part of the HTML page, including the page title and the opening <BODY> tag. To send the page header, you call the sendPageHeader method. The page footer contains the bottom part of the page, that is, the closing </BODY> and </HTML> tags.

Calling the sendPageFooter method will send the page footer.

The sendSearchForm method sends the HTML form. This form uses the POST method and, when submitted, this form will send the keyword to the server. The server then invokes the doPost method whose code is given in

Listing 5.2

.

Listing 5.2 The doPost Method of the SearchServlet

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

keyword = request.getParameter("keyword");

sendPageHeader(response);

sendSearchForm(response);

sendSearchResult(response);

sendPageFooter(response);

}

The first thing doPost does is retrieve the keyword from the HttpServletRequest object and store it in a class-level variable keyword. It then sends the page header, the search form, the search result, and the page footer to the browser.

The sendSearchResult method forms an SQL select statement that incorporates the keyword, in the following syntax:

SELECT Id, FirstName, LastName, UserName, Password

FROM Users

WHERE FirstName LIKE '%keyword%'

OR LastName LIKE '%keyword%'

Note that the % character represents any text of zero length or more. This means that jo% will find jo, john, jones, and so on. Note, however, that this wildcard character is different from one database server to another and you should consult your database server documentation before using it.

Because the value entered by the user as the keyword can contain a single quote character, you use the StringUtil class's fixSqlFieldValue method to "fix" the keyword. StringUtil class is part of the com.brainysoftware.java package that can be found on the accompanying CD. You need to copy the StringUtil.java file into the com/brainysoftware/java/ directory under the directory where you put your source files. See

Chapter 3 for more information on how to use the StringUtil class.

You compose the SQL statement using the following code:

116

String sql =

"SELECT Id, FirstName, LastName, UserName, Password" +

" FROM Users" +

" WHERE FirstName LIKE '%" +

StringUtil.fixSqlFieldValue(keyword) + "%'" +

" OR LastName LIKE '%" +

Once the SQL statement is executed, the returned ResultSet can be looped through to get its cell data. Of particular interest is the call to the getString method passing the integer 1. This returns the

Id for that person. The Id is important because it is used as the token for that person. The Id is passed in the URL to the DeleteServlet as well as to the UpdateServlet, as follows: out.println("<TD><A HREF=DeleteServlet?id=" + id +

">Delete</A></TD>"); out.println("<TD><A HREF=UpdateServlet?id=" + id +

">Update</A></TD>");

Therefore, for a person with an Id of 6, the hyperlink to the DeleteServlet will be:

<A HREF=DeleteServlet?id=6>Delete</A>

And for a person with an Id of 8, the hyperlink to the UpdateServlet is

<A HREF=UpdateServlet?id=8>Delete</A>

See how information has been added to the URL?

The complete listing of the SearchServlet is presented in

Listing 5.3

.

Listing 5.3 The SearchServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import com.brainysoftware.java.StringUtil; public class SearchServlet extends HttpServlet {

private String keyword = "";

public void init() {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

System.out.println("JDBC driver loaded");

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

}

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

sendPageHeader(response);

sendSearchForm(response);

117

sendPageFooter(response);

}

/**Process the HTTP Post request*/

public void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

keyword = request.getParameter("keyword");

sendPageHeader(response);

sendSearchForm(response);

sendSearchResult(response);

sendPageFooter(response);

}

void sendSearchResult(HttpServletResponse response)

throws IOException {

PrintWriter out = response.getWriter();

try {

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

System.out.println("got connection");

Statement s = con.createStatement();

out.println("<TABLE>");

out.println("<TR>");

out.println("<TH>First Name</TH>");

out.println("<TH>Last Name</TH>");

out.println("<TH>User Name</TH>");

out.println("<TH>Password</TH>");

FL

Y

out.println("<TH></TH>");

out.println("<TH></TH>");

out.println("</TR>");

String sql =

"SELECT Id, FirstName, LastName, UserName, Password" +

" FROM Users" +

TE

AM

" WHERE FirstName LIKE '%" +

StringUtil.fixSqlFieldValue(keyword) + "%'" +

" OR LastName LIKE '%" +

StringUtil.fixSqlFieldValue(keyword) + "%'";

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

String id = rs.getString(1);

out.println("<TR>");

out.println("<TD>" + StringUtil.encodeHtmlTag(rs.getString(2))

+ "</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(rs.getString(3))

+ "</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(rs.getString(4))

+ "</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(rs.getString(5))

+ "</TD>");

out.println("<TD><A HREF=DeleteServlet?id=" + id +

">Delete</A></TD>");

out.println("<TD><A HREF=UpdateServlet?id=" + id +

">Update</A></TD>");

out.println("</TR>");

}

s.close();

con.close();

Team-Fly ®

}

catch (SQLException e) {

}

catch (Exception e) {

}

out.println("</TABLE>");

}

/**

* Send the HTML page header, including the title

* and the <BODY> tag

*/

private void sendPageHeader(HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Displaying Selected Record(s)</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

}

/**

* Send the HTML page footer, i.e. the </BODY>

* and the </HTML>

*/

private void sendPageFooter(HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

/**Send the form where the user can type in

* the details for a new user

*/

private void sendSearchForm(HttpServletResponse response)

throws IOException {

PrintWriter out = response.getWriter();

out.println("<BR><H2>Search Form</H2>");

out.println("<BR>Please enter the first name, last name or part of any.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.print("Name: <INPUT TYPE=TEXT Name=keyword");

out.print(" VALUE=\"" + StringUtil.encodeHtmlTag(keyword) + "\"");

out.println(">");

out.println("<INPUT TYPE=SUBMIT>");

out.println("</FORM>");

out.println("<BR>");

out.println("<BR>");

}

}

The DeleteServlet takes the value of id appended to the URL and deletes the record of the person having that id.

119

Retrieving the id is achieved by using the getParameter method of the HttpServletRequest interface:

String id = request.getParameter("id");

After you get the id, an SQL statement can be composed, as follows:

String sql = "DELETE FROM Users WHERE Id=" + id;

Next, you can create a Connection object and a Statement object, and use the latter to execute the

SQL statement:

Connection con = DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement(); recordAffected = s.executeUpdate(sql);

The code for the DeleteServlet is given in Listing 5.4

. Note that in the DeleteServlet, and in the

UpdateServlet, there is no code for loading the JDBC driver. This has been done in the

SearchServlets and the driver stays on for other servlets that need to connect to the same database.

Listing 5.4 The DeleteServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; public class DeleteServlet extends HttpServlet {

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

int recordAffected = 0;

try {

String id = request.getParameter("id");

String sql = "DELETE FROM Users WHERE Id=" + id;

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

recordAffected = s.executeUpdate(sql);

s.close();

con.close();

}

catch (SQLException e) {

}

catch (Exception e) {

}

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Deleting A Record</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

if (recordAffected == 1)

120

out.println("<P>Record deleted.</P>");

else

out.println("<P>Error deleting record.</P>");

out.println("<A HREF=SearchServlet>Go back</A> to the Search page");

}

}

The UpdateServlet gets the id passed in the URL and sends a form containing the user details of the person with that id. The user can update the first name, the last name, or the password for that person, but not the user name. Therefore, the first name, last name, and the password are represented in text boxes, whereas the user name is displayed as HTML text.

The business rule for this servlet states that the user name cannot be changed because it's been guaranteed unique at the time of data insertion. Allowing this value to change can break this restriction. Of course, how you implement a servlet depends on your own requirement and business rules. The UpdateServlet is called by clicking the URL in the SearchServlet. The URL always carries an id for the person whose details are to be changed. This request invokes the

UpdateServlet's doGet method that sends the page header, the update form, and the page footer.

The doGet method is presented in

Listing 5.5

.

Listing 5.5 The doGet Method of the UpdateServlet

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

sendPageHeader(response);

sendUpdateForm(request, response);

sendPageFooter(response);

} sendUpdateForm first retrieves the id from the URL using the getParameter method, as follows:

String id = request.getParameter("id");

The method then connects to the database to retrieve the details from the Users table. The SQL statement for that is simply the following:

SELECT FirstName, LastName, UserName, Password

FROM Users

WHERE Id=id

Then the method will send the details in an HTML form, similar to the one shown earlier in Figure

5.3

.

The interesting part of the code is when the <FORM> tag is sent: out.println("<BR><FORM METHOD=POST ACTION=" +

request.getRequestURI() + "?id=" + id + ">");

Normally, you won't have an ACTION attribute in your form because the form is to be submitted to the same servlet. This time, however, you need to append the value of the id to the URL.

Therefore, you use the getRequestURI method to get the current Uniform Resource Identifier

(URI) and append the following information, such as

?id=6

121

for the user with an id of 6.

When the user submits the form, the doPost method of the UpdateServlet will be invoked. The doPost method is given in

Listing 5.6

.

Listing 5.6 The doPost Method of the UpdateServlet

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

sendPageHeader(response);

updateRecord(request, response);

sendPageFooter(response);

}

The important method called from doPost is the updateRecord method. The updateRecord method first retrieves the values of id, firstName, lastName, and password using the getParameter method.

Note that the id is retrieved from the URL and the others from the request body, as follows:

String id = request.getParameter("id");

String firstName = request.getParameter("firstName");

String lastName = request.getParameter("lastName");

String password = request.getParameter("password");

With these values, you can compose the SQL that will update the record. It has the following syntax:

UPDATE Users

SET FirstName=firstName,

LastName=lastName,

Password=password

WHERE Id=id

Then you can execute the SQL as usual:

Connection con = DriverManager.getConnection(dbUrl);

Statement s = con.createStatement(); int i = s.executeUpdate(sql);

Now, the executeUpdate should return the number of records affected by the SQL statement.

Because the id is unique, it should return 1 as the number of records affected. If it is 1, you simply send a message saying, "Record updated". If it is not 1 because an unexpected error occurred, say,

"Error updating record". if (i == 1)

out.println("Record updated"); else

out.println("Error updating record");

The complete code for the UpdateServlet is given in Listing 5.7

.

Listing 5.7 The UpdateServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*;

122

import java.util.*; import java.sql.*; import com.brainysoftware.java.StringUtil; public class UpdateServlet extends HttpServlet {

private String dbUrl = "jdbc:odbc:JavaWeb";

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

sendPageHeader(response);

sendUpdateForm(request, response);

sendPageFooter(response);

}

/**Process the HTTP Post request*/

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

sendPageHeader(response);

updateRecord(request, response);

sendPageFooter(response);

}

/**

* Send the HTML page header, including the title

* and the <BODY> tag

*/

private void sendPageHeader(HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Updating Record</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

}

/**

* Send the HTML page footer, i.e. the </BODY>

* and the </HTML>

*/

private void sendPageFooter(HttpServletResponse response)

throws ServletException, IOException {

PrintWriter out = response.getWriter();

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

/**Send the form where the user can type in

* the details for a new user

*/

private void sendUpdateForm(HttpServletRequest request,

HttpServletResponse response) throws IOException {

String id = request.getParameter("id");

PrintWriter out = response.getWriter();

out.println("<BR><H2>Update Form</H2>");

123

out.println("<BR>Please edit the first name, last name or password.");

out.println("<BR>");

try {

String sql = "SELECT FirstName, LastName," +

" UserName, Password" +

" FROM Users" +

" WHERE Id=" + id;

Connection con = DriverManager.getConnection(dbUrl);

Statement s = con.createStatement();

ResultSet rs = s.executeQuery(sql);

if (rs.next()) {

String firstName = rs.getString(1);

String lastName = rs.getString(2);

String userName = rs.getString(3);

String password = rs.getString(4);

out.println("<BR><FORM METHOD=POST ACTION=" +

request.getRequestURI() + "?id=" + id + ">");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name</TD>");

out.print("<TD><INPUT TYPE=TEXT Name=firstName");

out.print(" VALUE=\"" + StringUtil.encodeHtmlTag(firstName)

+ "\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name</TD>");

out.print("<TD><INPUT TYPE=TEXT Name=lastName");

out.print(" VALUE=\"" + StringUtil.encodeHtmlTag(lastName)

+ "\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>User Name</TD>");

out.print("<TD>" + StringUtil.encodeHtmlTag(userName) +

"</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password</TD>");

out.print("<TD><INPUT TYPE=PASSWORD Name=password");

out.print(" VALUE=\"" + StringUtil.encodeHtmlTag (password)

+ "\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD><INPUT TYPE=RESET></TD>");

out.println("<TD><INPUT TYPE=SUBMIT></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

}

s.close();

con.close();

}

catch (SQLException e) {

out.println(e.toString());

}

catch (Exception e) {

out.println(e.toString());

124

}

}

void updateRecord(HttpServletRequest request, HttpServletResponse response) throws IOException {

String id = request.getParameter("id");

String firstName = request.getParameter("firstName");

String lastName = request.getParameter("lastName");

String password = request.getParameter("password");

PrintWriter out = response.getWriter();

try {

String sql = "UPDATE Users" +

" SET FirstName='" + StringUtil.fixSqlFieldValue(firstName) +

"'," + " LastName='" + StringUtil.fixSqlFieldValue(lastName) + "'," +

" Password='" + StringUtil.fixSqlFieldValue(password) + "'" +

" WHERE Id=" + id;

Connection con = DriverManager.getConnection(dbUrl);

Statement s = con.createStatement();

int i = s.executeUpdate(sql);

if (i == 1)

out.println("Record updated");

else

out.println("Error updating record");

s.close();

con.close();

}

catch (SQLException e) {

out.println(e.toString());

}

catch (Exception e) {

out.println(e.toString());

}

out.println("<A HREF=SearchServlet>Go back</A> to the Search

Page");

}

}

Hidden Fields

Another technique for managing user sessions is by passing a token as the value for an HTML hidden field. Unlike the URL rewriting, the value does not show on the URL but can still be read by viewing the HTML source code. Although this method also is easy to use, an HTML form is always required.

Using Hidden Fields

As the first example to illustrate the use of this technique, you will modify the sendUpdateForm method in the UpdateServlet in

Listing 5.7

. To try this example, you need to change the

sendUpdateForm method in the UpdateServlet. This servlet should still be used with the

SearchServlet and the DeleteServlet, given in Listings

5.3

and

5.4

. The two servlets are not

modified, and the code won't be repeated here.

The new sendUpdateForm method is given in Listing 5.8

.

Listing 5.8 The Modified sendUpdateForm Method in UpdateServlet

125

private void sendUpdateForm(HttpServletRequest request,

HttpServletResponse response)

throws IOException {

String id = request.getParameter("id");

PrintWriter out = response.getWriter();

out.println("<BR><H2>Update Form</H2>");

out.println("<BR>Please edit the first name, last name or password.");

out.println("<BR>");

try {

String sql = "SELECT FirstName, LastName," +

" UserName, Password" +

" FROM Users" +

" WHERE Id=" + id;

Connection con = DriverManager.getConnection(dbUrl);

Statement s = con.createStatement();

ResultSet rs = s.executeQuery(sql);

if (rs.next()) {

String firstName = rs.getString(1);

String lastName = rs.getString(2);

String userName = rs.getString(3);

String password = rs.getString(4);

out.println("<BR><FORM METHOD=POST>");

out.print("<INPUT TYPE=HIDDEN Name=id VALUE=" + id + ">");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name</TD>");

out.print("<TD><INPUT TYPE=TEXT Name=firstName");

out.print(" VALUE=\"" + StringUtil.encodeHtmlTag(firstName) +

"\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name</TD>");

out.print("<TD><INPUT TYPE=TEXT Name=lastName");

out.print(" VALUE=\"" + StringUtil.encodeHtmlTag(lastName) +

"\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>User Name</TD>");

out.print("<TD>" + StringUtil.encodeHtmlTag(userName) +

"</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password</TD>");

out.print("<TD><INPUT TYPE=PASSWORD Name=password");

out.print(" VALUE=\"" + StringUtil.encodeHtmlTag(password) +

"\"");

out.println("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD><INPUT TYPE=RESET></TD>");

out.println("<TD><INPUT TYPE=SUBMIT></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

}

s.close();

con.close();

126

}

catch (SQLException e) {

out.println(e.toString());

}

catch (Exception e) {

out.println(e.toString());

}

}

If you run this application in a web browser, you will be able to see that the id is not appended to the URL. Therefore, you don't need the ACTION attribute in the form. The id is now written to a

HIDDEN field as follows: out.print("<INPUT TYPE=HIDDEN Name=id VALUE=" + id + ">");

When the form is submitted, the hidden field is sent along with the other input elements' values of the form. On the servlet, the id still can be retrieved using the getParameter method.

Splitting Forms

The second example of the use of the hidden field occurs when you want to split a large form into several smaller ones for the sake of user-friendliness. Again, for this example, you will use the now familiar Users table. You will write an application that the user can use to insert a new record to the Users table, similar to the one in

Chapter 4 . Instead of having one form in which the user

can enter the first name, the last name, the user name, and the password at the same time, however, the form is split into two smaller forms. The first form will accept the first name and the last name.

The user name and password can be entered on the second form. When the second form is submitted, all four values must be sent to a third servlet that composes and executes an SQL insert statement.

In this example, you will use three servlets for each page in the process. They are simply called

Page1Servlet, Page2Servlet, and Page3Servlet. Page1Servlet does not do much except send an

HTML form with two text fields. You can replace this servlet with a static HTML file if you want.

Page1Servlet is shown in

Figure 5.4

.

Figure 5.4. Page 1.

127

TE

AM

Y second form as well as the values from the first form. It is shown in

Figure 5.5

.

FL

When the second form is submitted, all four values go to Page3Servlet. You could insert a new record to the database. For brevity, however, you will simply display the values without trying to access any database. The result from the Page3Servlet is shown in

Figure 5.6

.

Team-Fly ®

Figure 5.6. Page 3.

Now, let's dissect the code.

As mentioned, Page1Servlet is a simple HTML form. It is given in

Listing 5.9

.

Listing 5.9 Page1Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class Page1Servlet extends HttpServlet {

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

sendPage1(response); }

/**Process the HTTP Post request*/

public void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

sendPage1(response);

}

void sendPage1(HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Page 1</TITLE>");

129

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

out.println("<H2>Page 1</H2>");

out.println("<BR>");

out.println("<BR>");

out.println("Please enter your first first name and last name.");

out.println("<BR>");

out.println("<BR>");

out.println("<FORM METHOD=POST ACTION=Page2Servlet>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name&nbsp;</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=firstName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name&nbsp;</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=lastName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD><INPUT TYPE=RESET></TD>");

out.println("<TD><INPUT TYPE=SUBMIT VALUE=Submit></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

}

One thing to note is that you use the ACTION attribute for the form, as you see here: out.println("<FORM METHOD=POST ACTION=Page2Servlet>");

The value for the ACTION attribute is Page2Servlet, which makes sure that the form will be submitted to Page2Servlet.

Page2Servlet retrieves the first name and last name from the form in Page1Servlet and retains them in hidden fields. These hidden fields are included in a form that also sends the two text input

for user name and password. The code for this servlet is given in Listing 5.10

.

Listing 5.10 Page2Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import com.brainysoftware.java.StringUtil; public class Page2Servlet extends HttpServlet {

String page1Url = "Page1Servlet";

String firstName;

String lastName;

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

130

response.sendRedirect(page1Url);

}

/**Process the HTTP Post request*/

public void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException, IOException {

firstName = request.getParameter("firstName");

lastName = request.getParameter("lastName");

if (firstName == null || lastName == null)

response.sendRedirect(page1Url);

sendPage2(response);

}

void sendPage2(HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Page 2</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

out.println("<H2>Page 2</H2>");

out.println("<BR>");

out.println("Please enter your user name and password.");

out.println("<BR>");

out.println("<BR>");

out.println("<BR>");

out.println("<FORM METHOD=POST ACTION=Page3Servlet>");

out.println("<INPUT TYPE=HIDDEN NAME=firstName VALUE=\"" +

StringUtil.encodeHtmlTag(firstName) + "\">");

out.println("<INPUT TYPE=HIDDEN NAME=lastName VALUE=\"" +

StringUtil.encodeHtmlTag(lastName) + "\">");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>User Name&nbsp;</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=userName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password&nbsp;</TD>");

out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD><INPUT TYPE=RESET></TD>");

out.println("<TD><INPUT TYPE=SUBMIT VALUE=Submit></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

}

If you enter "Tim" and "O'Connor" as the first name and last name into the first form, the HTML source code passed back to Page 2 is as follows (look at the lines in bold where the values of the previous form are passed back to the browser):

131

<HTML>

<HEAD>

<TITLE>Page 2</TITLE>

</HEAD>

<BODY>

<CENTER>

<H2>Page 2</H2>

<BR>

<BR>

Please enter your user name and password.

<BR>

<BR>

<FORM METHOD=POST ACTION=Page3Servlet>

<INPUT TYPE=HIDDEN NAME=firstName VALUE="Tim">

<INPUT TYPE=HIDDEN NAME=lastName VALUE="O'Connor">

<TABLE>

<TR>

<TD>User Name&nbsp;</TD>

<TD><INPUT TYPE=TEXT NAME=userName></TD>

</TR>

<TR>

<TD>Password&nbsp;</TD>

<TD><INPUT TYPE=PASSWORD NAME=password></TD>

</TR>

<TR>

<TD><INPUT TYPE=RESET></TD>

<TD><INPUT TYPE=SUBMIT VALUE=Submit></TD>

</TR>

</TABLE>

</FORM>

</CENTER>

</BODY>

</HTML>

Finally, Listing 5.11

presents the Page3Servlet that retrieves all the values from the second form.

Listing 5.11 Page3Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import com.brainysoftware.java.StringUtil; public class Page3Servlet extends HttpServlet {

String page1Url = "Page1Servlet";

String firstName;

String lastName;

String userName;

String password;

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.sendRedirect(page1Url);

}

/**Process the HTTP Post request*/

public void doPost(HttpServletRequest request, HttpServletResponse response) throws

132

ServletException,IOException {

firstName = request.getParameter("firstName");

lastName = request.getParameter("lastName");

userName = request.getParameter("userName");

password = request.getParameter("password");

if (firstName == null || lastName == null ||

userName == null || password == null)

response.sendRedirect(page1Url);

// display all the values from the previous forms

displayValues(response);

}

void displayValues(HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Page 3</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

out.println("<H2>Page 3 (Finish)</H2>");

out.println("<BR>");

out.println("<BR>");

out.println("Here are the values you have entered.");

out.println("<BR>");

out.println("<BR>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name: &nbsp;</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(firstName) +

"</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name: &nbsp;</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(lastName) +

"</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>User Name: &nbsp;</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(userName) +

"</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password: &nbsp;</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(password) +

"</TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

}

Multiple Forms in One Servlet

The previous example demonstrated how you could retain values in hidden fields in three servlets.

Using more than one servlet is probably the last thing you want to do for a simple application,

133

considering the maintenance involved for each servlet. This example shows the same application using only one servlet.

The problem with using one servlet is that each form will submit to the same servlet and the same doPost method will be invoked. How do you know which form to display next? The solution is simply done by incorporating a hidden field called page with a value of the form number. In the first form, the page field will have the value of 1, and in the second form this field will have the value of 2.

When the servlet is first called, the doGet method is invoked. What it does is very predictable: send the first form to the browser using the sendPage1 method: sendPage1(response);

When the first form is submitted, it will invoke the doPost method because the form uses the

POST method. The doPost method will retrieve the value of the parameter called page using the getParameter method. It should always find a value. However, if for some reason it does not, the method simply sends the first form and returns, as you see here:

String page = request.getParameter("page"); if (page == null) {

sendPage1(response);

return;

}

If a value for page is found, it could be 1 or 2. If 1 is returned, the previous request is from the first page; therefore Page 2 should be sent. The request that submits the first form must be accompanied by the parameters firstName and lastName, however. In other words, both the getParameter("firstName") and getParameter("lastName") must not return null. The values themselves could be blank strings, as is the case if the user does not type anything in the text boxes. However, a valid request from the first page must carry these parameters: if (page.equals("1")) {

if (firstName == null || lastName == null)

sendPage1(response);

else

sendPage2(response);

}

If either firstName or lastName is not found, the sendPage1 is called again because the request is not valid.

If the first page is okay, the doPost method calls the sendPage2 method, which sends the second form as well as the previous values from the first form.

If the value for page is 2, the previous page must come from the second page and four parameters must be present in the request: firstName, lastName, userName, and password. Missing one of the values is a sufficient reason to resend the first page, as shown here: else if (page.equals("2")) {

if (firstName == null || lastName == null ||

userName == null || password == null)

sendPage1(response);

else

displayValues(response);

}

134

If the value for page is 2 and all the other values are found, the displayValues method is called and it displays all the four values from the first and second forms.

The complete code is given in

Listing 5.12

.

Listing 5.12 MultipleFormsServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import com.brainysoftware.java.StringUtil; public class MultipleFormsServlet extends HttpServlet {

String firstName;

String lastName;

String userName;

String password;

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

sendPage1(response);

}

/**Process the HTTP Post request*/

public void doPost(HttpServletRequest request, HttpServletResponse response) throws

ServletException,IOException {

String page = request.getParameter("page");

firstName = request.getParameter("firstName");

lastName = request.getParameter("lastName");

userName = request.getParameter("userName");

password = request.getParameter("password");

if (page == null) {

sendPage1(response);

return;

}

if (page.equals("1")) {

if (firstName == null || lastName == null)

sendPage1(response);

else

sendPage2(response);

}

else if (page.equals("2")) {

if (firstName == null || lastName == null ||

userName == null || password == null)

sendPage1(response);

else

displayValues(response);

}

}

void sendPage1(HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Page 1</TITLE>");

135

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

out.println("<H2>Page 1</H2>");

out.println("<BR>");

out.println("<BR>");

out.println("Please enter your first first name and last name.");

out.println("<BR>");

out.println("<BR>");

out.println("<FORM METHOD=POST>");

out.println("<INPUT TYPE=HIDDEN NAME=page VALUE=1>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name&nbsp;</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=firstName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name&nbsp;</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=lastName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD><INPUT TYPE=RESET></TD>");

out.println("<TD><INPUT TYPE=SUBMIT VALUE=Submit></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

void sendPage2(HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Page 2</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

out.println("<H2>Page 2</H2>");

out.println("<BR>");

out.println("<BR>");

out.println("Please enter your user name and password.");

out.println("<BR>");

out.println("<BR>");

out.println("<FORM METHOD=POST>");

out.println("<INPUT TYPE=HIDDEN NAME=page VALUE=2>");

out.println("<INPUT TYPE=HIDDEN NAME=firstName VALUE=\"" +

StringUtil.encodeHtmlTag(firstName) + "\"></TD>");

out.println("<INPUT TYPE=HIDDEN NAME=lastName VALUE=\"" +

StringUtil.encodeHtmlTag(lastName) + "\"></TD>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>User Name&nbsp;</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=userName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password&nbsp;</TD>");

136

out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD><INPUT TYPE=RESET></TD>");

out.println("<TD><INPUT TYPE=SUBMIT VALUE=Submit></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

void displayValues(HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Page 3</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

out.println("<H2>Page 3 (Finish)</H2>");

out.println("<BR>");

out.println("<BR>");

out.println("Here are the values you have entered.");

out.println("<BR>");

out.println("<BR>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name: &nbsp;</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(firstName) +

"</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name: &nbsp;</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(lastName) +

"</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>User Name: &nbsp;</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(userName) +

"</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password: &nbsp;</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(password) +

"</TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

}

137

Cookies

The third technique that you can use to manage user sessions is by using cookies. A cookie is a small piece of information that is passed back and forth in the HTTP request and response. Even though a cookie can be created on the client side using some scripting language such as JavaScript, it is usually created by a server resource, such as a servlet. The cookie sent by a servlet to the client will be passed back to the server when the client requests another page from the same application.

Cookies were first specified by Netscape (see http://home.netscape.com/newsref/std/cookie_spec.html

) and are now part of the Internet standard as specified in RFC 2109: The HTTP State Management Mechanism. Cookies are transferred to and from the client in the HTTP headers.

In servlet programming, a cookie is represented by the Cookie class in the javax.servlet.http package. You can create a cookie by calling the Cookie class constructor and passing two String objects: the name and value of the cookie. For instance, the following code creates a cookie object called c1. The cookie has the name "myCookie" and a value of "secret":

Cookie c1 = new Cookie("myCookie", "secret");

You then can add the cookie to the HTTP response using the addCookie method of the

HttpServletResponse interface: response.addCookie(c1);

FL

Y cookie after an output has been written to the HttpServletResponse object. Otherwise, an exception will be thrown.

The following example shows how you can create two cookies called userName and password and and its code is given in

Listing 5.13

.

TE

AM

When it is first invoked, the doGet method of the servlet is called. The method creates two cookies and adds both to the HttpServletResponse object, as follows:

Cookie c1 = new Cookie("userName", "Helen");

Cookie c2 = new Cookie("password", "Keppler"); response.addCookie(c1); response.addCookie(c2);

Next, the doGet method sends an HTML form that the user can click to send another request to the servlet: response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Cookie Test</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("Please click the button to see the cookies sent to you.");

out.println("<BR>");

out.println("<FORM METHOD=POST>");

Team-Fly ®

out.println("<INPUT TYPE=SUBMIT VALUE=Submit>");

out.println("</FORM>");

out.println("</BODY>");

out.println("</HTML>");

The form does not have any element other than a submit button. When the form is submitted, the doPost method is invoked. The doPost method does two things: It iterates all the headers in the request to show how the cookies are conveyed back to the server, and it retrieves the cookies and displays their values.

To display all the headers in the HttpServletRequest method, it first retrieves an Enumeration object containing all the header names. The method then iterates the Enumeration object to get the next header name and passes the header name to the getHeader method to display the value of that header, as you see here:

Enumeration enum = request.getHeaderNames(); while (enum.hasMoreElements()) {

String header = (String) enum.nextElement();

out.print("<B>" + header + "</B>: ");

out.print(request.getHeader(header) + "<BR>");

}

To retrieve cookies, you use the getCookies method of the HttpServletRequest interface. This method returns a Cookie array containing all cookies in the request. It is your responsibility to loop through the array to get the cookie you want, as follows:

Cookie[] cookies = request.getCookies(); int length = cookies.length; for (int i=0; i<length; i++) {

Cookie cookie = cookies[i];

out.println("<B>Cookie Name:</B> " +

cookie.getName() + "<BR>");

out.println("<B>Cookie Value:</B> " +

cookie.getValue() + "<BR>");

}

The headers and cookies are displayed in Figure 5.7

.

Figure 5.7. The headers containing cookies and the cookies' values.

139

Listing 5.13 Sending and Receiving Cookies

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class CookieServlet extends HttpServlet {

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

Cookie c1 = new Cookie("userName", "Helen");

Cookie c2 = new Cookie("password", "Keppler");

response.addCookie(c1);

response.addCookie(c2);

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Cookie Test</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("Please click the button to see the cookies sent to you.");

out.println("<BR>");

out.println("<FORM METHOD=POST>");

out.println("<INPUT TYPE=SUBMIT VALUE=Submit>");

out.println("</FORM>");

out.println("</BODY>");

out.println("</HTML>");

}

/**Process the HTTP Post request*/

140

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Cookie Test</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<H2>Here are all the headers.</H2>");

Enumeration enum = request.getHeaderNames();

while (enum.hasMoreElements()) {

String header = (String) enum.nextElement();

out.print("<B>" + header + "</B>: ");

out.print(request.getHeader(header) + "<BR>");

}

out.println("<BR><BR><H2>And, here are all the cookies.</H2>");

Cookie[] cookies = request.getCookies();

int length = cookies.length;

for (int i=0; i<length; i++) {

Cookie cookie = cookies[i];

out.println("<B>Cookie Name:</B> " + cookie.getName() + "<BR>");

out.println("<B>Cookie Value:</B> " + cookie.getValue() +

"<BR>");

}

out.println("</BODY>");

out.println("</HTML>");

}

}

Another example of a servlet that uses cookies is a Login servlet that utilizes cookies to carry the user name and password information. The use of cookies is more appropriate than both URL rewriting and hidden values. First, unlike URL rewriting, the values of the cookies are not directly visible (you don't want this sensitive information to be seen by anyone). Second, you don't need to use any form, which is the requirement of using hidden fields.

Using cookes has a disadvantage, however: The user can choose not to accept them. Even though browsers leave the factories with the cookie setting on, any user can (accidentally) change this setting. The normal practice is therefore to use cookies with warnings to the user if the application does not work as expected. The warning could be a simple message telling the user to activate his cookie setting, or it could be a hyperlink to a page that thoroughly describes how to set the cookie setting in various browsers.

So, here it is: the CookieLoginServlet that modifies the previous LoginServlet in Chapter 4 . The

complete code is given in

Listing 5.14

. If the cookie setting is not on, the servlet will send a

message. The servlet also will send a message if the authentication fails (see

Figure 5.8

).

Figure 5.8. CookieLoginServlet.bmp.

141

An important part of the listing that deserves an explanation is the part that redirects the user to another resource when the login is successful. First, you need to create two cookies called userName and password and add them to the HttpServletResponse object. The cookies will always go back to the server when the user gets redirected to another resource. This resource can then retrieve the cookies and do the authentication again against the same database. This way, the user does not have to log in more than once.

Next, you need the code that redirects the user. Normally, to redirect a user, you would use the sendRedirect method. When you need to send cookies at the same time, however, redirecting using the sendRedirect method will not make the cookies get passed back to the server. As an alternative, you use a META tag of the following syntax:

<META HTTP-EQUIV=Refresh CONTENT=x;URL=ContentServlet>

This META tag will make the browser request another resource as indicated in the URL part. x indicates the number of seconds the browser will wait before the redirection occurs.

The code that does these two things is given here:

if (login(userName, password)) {

//send cookie to the browser

Cookie c1 = new Cookie("userName", userName);

Cookie c2 = new Cookie("password", password);

response.addCookie(c1);

response.addCookie(c2);

response.setContentType("text/html");

PrintWriter out = response.getWriter();

//response.sendRedirect does not work here.

// use a Meta tag to redirect to ContentServlet

out.println(

"<META HTTP-EQUIV=Refresh CONTENT=0;URL=ContentServlet>");

}

142

Listing 5.14 CookieLoginServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import com.brainysoftware.java.StringUtil; public class CookieLoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

sendLoginForm(response, false);

}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String userName = request.getParameter("userName");

String password = request.getParameter("password");

if (login(userName, password)) {

//send cookie to the browser

Cookie c1 = new Cookie("userName", userName);

Cookie c2 = new Cookie("password", password);

response.addCookie(c1);

response.addCookie(c2);

response.setContentType("text/html");

PrintWriter out = response.getWriter();

//response.sendRedirect does not work here.

// use a Meta tag to redirect to ContentServlet

out.println("<META HTTP-EQUIV=Refresh

CONTENT=0;URL=ContentServlet>");

}

else {

sendLoginForm(response, true);

}

}

private void sendLoginForm(HttpServletResponse response, boolean withErrorMessage)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Login</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

if (withErrorMessage) {

out.println("Login failed. Please try again.<BR>");

out.println("If you think you have entered the correct user name" + " and password, the cookie setting in your browser might be off." +

"<BR>Click <A HREF=InfoPage.html>here</A> for information" +

" on how to turn it on.<BR>");

}

out.println("<BR>");

143

out.println("<BR><H2>Login Page</H2>");

out.println("<BR>");

out.println("<BR>Please enter your user name and password.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>User Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=userName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password:</TD>");

out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD ALIGN=RIGHT COLSPAN=2>");

out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

public static boolean login(String userName, String password) {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

String sql = "SELECT UserName FROM Users" +

" WHERE UserName='" + StringUtil.fixSqlFieldValue(userName) +

"'" +

" AND Password='" + StringUtil.fixSqlFieldValue(password) +

"'";

ResultSet rs = s.executeQuery(sql);

if (rs.next()) {

rs.close();

s.close();

con.close();

return true;

}

rs.close();

s.close();

con.close();

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

catch (SQLException e) {

System.out.println(e.toString());

}

catch (Exception e) {

System.out.println(e.toString());

}

return false;

}

}

144

The second resource (such as another servlet) has to check the presence of the two cookies before displaying its supposedly important content. A servlet called ContentServlet is created to demonstrate this. The CookieLoginServlet will redirect the user to this servlet upon a successful login. The ContentServlet is given in

Listing 5.15

.

Listing 5.15 ContentServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class ContentServlet extends HttpServlet {

public String loginUrl = "CookieLoginServlet";

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String userName = null;

String password = null;

Cookie[] cookies = request.getCookies();

if (cookies != null) {

int length = cookies.length;

for (int i=0; i<length; i++) {

Cookie cookie = cookies[i];

if (cookie.getName().equals("userName"))

userName = cookie.getValue();

else if (cookie.getName().equals("password"))

password = cookie.getValue();

}

}

if (userName == null || password == null

|| !CookieLoginServlet.login(userName, password)) {

response.sendRedirect(loginUrl);

}

// This is an authorized user, okay to display content

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Welcome</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("Welcome.");

out.println("</BODY>");

out.println("</HTML>");

}

/**Process the HTTP Post request*/

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

doGet(request, response);

}

}

After studying the previous example, you might wonder why you need to create two cookies that hold the value for the user name and password, respectively. Can't you just use a cookie that

145

contains the value of true to indicate a previous successful login? The ContentServlet can just find this cookie and doesn't have to authenticate the user name and password again, hence saving a database manipulation.

This might sound better; however, a clever user can create a cookie at the client side. Knowing that a successful cookie carries a special flag, the user can create the cookie and get authenticated without having to know a valid user name and password.

Anticipating a Failed Redirection

When you need to do redirection while using cookies for managing user sessions—even when everything looks perfect—a redirection might fail. In the code that is supposed to redirect the user, you should provide a link that the user can manually click should the automatic redirection fail.

Note

If you are testing a cookie and find that the code does not work as expected, close your browser to delete the cookie.

Persisting Cookies

The cookies you created in the previous example last as long as the browser is open. When the browser is closed, the cookies are deleted. You can choose to persist cookies so that they last longer. The javax.servlet.http.Cookie class has the setMaxAge method that sets the maximum age of the cookie in seconds.

In the next example, you will create a Login servlet that uses a cookie that persists for 10,000 seconds. If the user closes the browser but comes back within 10,000 seconds, he or she does not have to enter a user name again.

Figure 5.9

shows the Login page in which the user name has been

supplied by the server.

Figure 5.9. Persistent Cookie servlet.

146

The servlet is called PersistentCookieServlet and is given in Listing 5.16

.

Listing 5.16 PersistentCookieServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import com.brainysoftware.java.StringUtil; public class PersistentCookieServlet extends HttpServlet {

String persistedUserName;

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

Cookie[] cookies = request.getCookies();

int length = cookies.length;

for (int i=0; i<length; i++) {

Cookie cookie = cookies[i];

if (cookie.getName().equals("userName"))

persistedUserName = cookie.getValue();

}

sendLoginForm(response, false);

}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String userName = request.getParameter("userName");

String password = request.getParameter("password");

if (login(userName, password)) {

//send cookie to the browser

Cookie c1 = new Cookie("userName", userName);

147

Cookie c2 = new Cookie("password", password);

c1.setMaxAge(10000);

response.addCookie(c1);

response.addCookie(c2);

response.setContentType("text/html");

PrintWriter out = response.getWriter();

//response.sendRedirect does not work here.

// use a Meta tag to redirect to ContentServlet

out.println("<META HTTP-EQUIV=Refresh

CONTENT=0;URL=ContentServlet>");

}

else {

sendLoginForm(response, true);

}

}

private void sendLoginForm(HttpServletResponse response, boolean withErrorMessage)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Login</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

if (withErrorMessage) {

FL

Y

out.println("Login failed. Please try again.<BR>");

out.println("If you think you have entered the correct user off." +

AM

"<BR>Click <A HREF=InfoPage.html>here</A> for information" +

}

out.println("<BR>");

TE

out.println("<BR><H2>Login Page</H2>");

out.println("<BR>");

out.println("<BR>Please enter your user name and password.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>User Name:</TD>");

out.print("<TD><INPUT TYPE=TEXT NAME=userName");

if (persistedUserName != null)

out.print(" VALUE=\"" + persistedUserName + "\"");

out.print("></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password:</TD>");

out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD ALIGN=RIGHT COLSPAN=2>");

out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>");

out.println("</TR>");

out.println("</TABLE>");

Team-Fly ®

out.println("</FORM>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

public static boolean login(String userName, String password) {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

String sql = "SELECT UserName FROM Users" +

" WHERE UserName='" + StringUtil.fixSqlFieldValue(userName) +

"'" + " AND Password='" + StringUtil.fixSqlFieldValue(password) + "'";

ResultSet rs = s.executeQuery(sql);

if (rs.next()) {

rs.close();

s.close();

con.close();

return true;

}

rs.close();

s.close();

con.close();

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

catch (SQLException e) {

System.out.println(e.toString());

}

catch (Exception e) {

System.out.println(e.toString());

}

return false;

}

}

When a user requests the PersistentCookieServlet, either the first time or a subsequent time, the doGet method is invoked. What this method does is browse through the Cookie collection obtained from the getCookies() method of the javax.servlet.http.HttpServletResponse interface.

For each Cookie, the code tests whether the cookie name is "userName". If it is, the cookie value is assigned to the persistentUserName field as follows:

Cookie[] cookies = request.getCookies(); int length = cookies.length; for (int i=0; i<length; i++) {

Cookie cookie = cookies[i];

if (cookie.getName().equals("userName"))

persistedUserName = cookie.getValue();

}

Then, the doGet method calls the sendLoginForm method to send the Login form that the user can use to log in: sendLoginForm(response, false);

149

When the user submits the Login form, the doPost method in the PersistentCookieServlet is invoked. The doPost method first tries to retrieve the userName and password values entered by the user, as you see here:

String userName = request.getParameter("userName");

String password = request.getParameter("password");

It then sends the userName and password values to the login method. This method will return true if the userName and password are valid. Upon successful login, two cookies, c1 and c2, will be created. c1 is called userName, and c2 is named password: if (login(userName, password)) {

//send cookie to the browser

Cookie c1 = new Cookie("userName", userName);

Cookie c2 = new Cookie("password", password);

The c1 cookie is set to last for 10,000 seconds using the setMaxAge method, as follows: c1.setMaxAge(10000);

Then, the doPost method sends both c1 and c2 to the browser and redirects the browser to another servlet, as the following code shows: response.addCookie(c1); response.addCookie(c2); response.setContentType("text/html");

PrintWriter out = response.getWriter();

//response.sendRedirect does not work here.

// use a Meta tag to redirect to ContentServlet out.println(

"<META HTTP-EQUIV=Refresh CONTENT=0;URL=ContentServlet>");

If the user comes back within 10,000 seconds, the browser will send the userName cookie back to the server and the cookie will be found in the doGet method.

The login method called from the doPost method sets up a database connection and sends the following SQL statement:

SELECT UserName FROM Users

WHERE UserName='userName'

AND Password='password'

If the SQL statement execution returns a non-empty ResultSet object, a user account by that name and password is found and the login method returns true: public static boolean login(String userName, String password) {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

String sql = "SELECT UserName FROM Users" +

" WHERE UserName='" + StringUtil.fixSqlFieldValue(userName) +

"'" +

" AND Password='" + StringUtil.fixSqlFieldValue(password) +

"'";

ResultSet rs = s.executeQuery(sql);

150

if (rs.next()) {

rs.close();

s.close();

con.close();

return true;

}

rs.close();

s.close();

con.close();

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

catch (SQLException e) {

System.out.println(e.toString());

}

catch (Exception e) {

System.out.println(e.toString());

}

return false;

}

}

Checking Whether Cookie Setting Is On

All the cookie-related examples assume that the user browser's cookie setting is on. Even though browsers leave the factory with this setting on, the user can turn this off. One approach to solving this problem is to send a warning message if the application does not work as expected. The other option is to check this setting automatically. This option can be explained with an example of a servlet called CheckCookieServlet.

What the servlet does is simple enough. It sends a response that forces the browser to come back for the second time. With the first response, it sends a cookie. When the browser comes back for the second time, the servlet checks whether the request carries the cookie sent previously. If the cookie is there, it can be concluded that the browser setting for cookies is on. Otherwise, it could be that the user is using a very old browser that does not recognize cookies at all, or the cookie support for that browser is off.

The CheckCookieServlet is given in

Listing 5.17

.

Listing 5.17 CheckCookieServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class CheckCookieServlet extends HttpServlet {

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

if (request.getParameter("flag") == null) {

// the first request

Cookie cookie = new Cookie("browserSetting", "on");

response.addCookie(cookie);

151

String nextUrl = request.getRequestURI() + "?flag=1";

out.println("<META HTTP-EQUIV=Refresh CONTENT=0;URL="+ nextUrl

+">");

}

else {

// the second request

Cookie[] cookies = request.getCookies();

if (cookies != null) {

int length = cookies.length;

boolean cookieFound = false;

for (int i=0; i<length; i++) {

Cookie cookie = cookies[i];

if (cookie.getName().equals("browserSetting") &&

cookie.getValue().equals("on")) {

cookieFound = true;

break;

}

}

if (cookieFound) {

out.println("Your browser's cookie setting is on.");

}

else {

out.println("Your browser does not support cookies or" +

" the cookie setting is off.");

}

}

}

/**Process the HTTP Post request*/

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

doGet(request, response);

}

}

Session Objects

Of the four techniques for session management covered in this chapter, the Session object, represented by the javax.servlet.http.HttpSession interface, is the easiest to use and the most powerful. For each user, the servlet can create an HttpSession object that is associated with that user only and can only be accessed by that particular user. The HttpSession object acts like a

Hashtable into which you can store any number of key/object pairs. The HttpSession object is accessible from other servlets in the same application. To retrieve an object previously stored, you need only to pass the key.

An HttpSession object uses a cookie or URL rewriting to send a token to the client. If cookies are used to convey session identifiers, the client browsers are required to accept cookies.

Unlike previous techniques, however, the server does not send any value. What it sends is simply a unique number called the session identifier. This session identifier is used to associate a user with a Session object in the server. Therefore, if there are 10 simultaneous users, 10 Session objects will be created in the server and each user can access only his or her own HttpSession object.

The way an HttpSession object is created for a user and retrieved in the next requests is illustrated in

Figure 5.10

.

152

Figure 5.10. How session tracking works with the HttpSession object.

Figure 5.10

shows that there are four steps in session tracking using the HttpSession object:

1. An HttpSession object is created by a servlet called Servlet1. A session identifier is generated for this HttpSession object. In this example, the session identifier is 1234, but in reality, the servlet container will generate a longer random number that is guaranteed to be unique. The HttpSession object then is stored in the server and is associated with the generated session identifier. Also the programmer can store values immediately after creating an HttpSession.

2. In the response, the servlet sends the session identifier to the client browser.

3. When the client browser requests another resource in the same application, such as

Servlet2, the session identifier is sent back to the server and passed to Servlet2 in the javax.servlet.http.HttpServletRequest object.

4. For Servlet2 to have access to the HttpSession object for this particular client, it uses the getSession method of the javax.servlet.http.HttpServletRequest interface. This method automatically retrieves the session identifier from the request and obtains the HttpSession object associated with the session identifier.

Note

What if the user never comes back after an HttpSession object is created? Then the servlet container waits for a certain period of time and removes that HttpSession object. One worry about using Session objects is scalability. In some servlet containers, Session objects are stored in memory, and as the number of users exceeds a certain limit, the server eventually runs out of memory.

One solution to this memory problem when using Session objects is to save Session objects to the database or disk. However, the Servlet 2.3 Specification does not clearly state how a servlet container should do this. If you are using Tomcat 4, however, your

Session objects will be moved to secondary storage once the number of Session objects has exceeded some value.

The getSession method of the javax.servlet.http.HttpServletRequest interface has two overloads.

They are as follows:

HttpSession getSession()

HttpSession getSession(boolean create)

153

The first overload returns the current session associated with this request, or if the request does not have a session identifier, it creates a new one.

The second overload returns the HttpSession object associated with this request if there is a valid session identifier in the request. If no valid session identifier is found in the request, whether a new HttpSession object is created depends on the create value. If the value is true, a new

HttpSession object is created if no valid session identifier is found in the request. Otherwise, the getSession method will return null.

Now that you know how session management works using the HttpSession object, let's have a look at the javax.servlet.http.HttpSession interface in more detail.

The javax.servlet.http.HttpSession Interface

This interface has the following methods:

• getAttribute getAttributeNames getCreationTime getId getLastAccessedTime getMaxInactiveInterval getServletContext getSessionContext getValue getValueNames invalidate isNew putValue removeAttribute removeValue setAttribute setMaxInactiveInterval

Each of the methods is discussed below.

getAttribute

This method retrieves an attribute from the HttpSession object. The return value is an object of type Object; therefore you may have to downcast the attribute to its original type. To retrieve an attribute, you pass the name associated with the attribute. This method returns an

IllegalStateException if it is called upon an invalidated HttpSession object.

The signature for this method is as follows: public Object getAttribute(String name) throws IllegalStateException

getAttributeNames

The getAttributeNames method returns a java.util.Enumeration containing all attribute names in the HttpSession object. This method returns an IllegalStateException if it is called upon an invalidated HttpSession object.

The signature is as follows:

154

public java.util.Enumeration getAttributeNames() throws

IllegalStateException

getCreationTime

The getCreationTime method returns the time that the HttpSession object was created, in milliseconds since January 1, 1970 00:00:00 GMT. This method returns an IllegalStateException if it is called upon an invalidated HttpSession object.

The signature for this method is as follows: public long getCreationTime() throws IllegalStateException

getId

The getID method returns the session identifier. The signature for this method is as follows: public String getId()

getLastAccessedTime

The getLastAccessedTime method returns the time the HttpSession object was last accessed by the client. The return value is the number of milliseconds lapsed since since January 1, 1970

00:00:00 GMT. The following is the method signature: public long getLastAccessedTime()

getMaxInactiveInterval

The getMaxInactiveInterval method returns the number of seconds the HttpSession object will be retained by the servlet container after it is last accessed before being removed. The signature of this method is as follows: public int getMaxInactiveInterval()

getServletContext

The getServletContext method returns the javax.servlet.ServletContext object the HttpSession object belongs to. The signature is as follows: public javax.servlet.ServletContext getServletContext

getSessionContext

This method is deprecated.

getValue

This method is deprecated.

getValueNames

This method is deprecated.

155

invalidate

The invalidate method invalidates the HttpSession object and unbinds any object bound to it. This method throws an IllegalStateException if this method is called upon an already invalidated

HttpSession object. The signature is as follows: public void invalidate() throws IllegalStateException

isNew

The isNew method indicates whether the HttpSession object was created with this request and the client has not yet joined the session tracking. This method returns an IllegalStateException if it is called upon an invalidated HttpSession object.

Its signature is as follows: public boolean isNew() throws IllegalStateException

putValue

This method is deprecated.

removeAttribute

The removeAttribute method removes an attribute bound to this HttpSession object. This method returns an IllegalStateException if it is called upon an invalidated HttpSession object.

Its signature is as follows: public void removeAttribute(String name) throws IllegalStateException

removeValue

This method is deprecated.

setAttribute

The setAttribute method adds a name/attribute pair to the HttpSession object. This method returns an IllegalStateException if it is called upon an invalidated HttpSession object. The method has the following signature: public void setAttribute(String name, Object attribute) throws

IllegalStateException

setMaxInactiveInterval

The setMaxInactiveInterval method sets the number of seconds from the time the HttpSession object is accessed the servlet container will wait before removing the HttpSession object. The signature is as follows: public void setMaxInactiveInterval(int interval)

Passing a negative number to this method will make this HttpSession object never expire.

156

Using HttpSession Object

The following example modifies the previous Login page and uses HttpSession objects. You don't need to create two cookies for both the user name and password. Because only the server can store and retrieve values from a HttpSession object, you can create a key called loggedIn with the value of "true" if the user has successfully logged in before.

The code is given in

Listing 5.18

.

Listing 5.18 The SessionLoginServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import java.sql.*; import com.brainysoftware.java.StringUtil; public class SessionLoginServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

sendLoginForm(response, false);

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String userName = request.getParameter("userName");

String password = request.getParameter("password");

if (login(userName, password)) {

//send cookie to the browser

HttpSession session = request.getSession(true);

session.setAttribute("loggedIn", new String("true"));

response.sendRedirect("Content2Servlet");

}

else {

sendLoginForm(response, true);

}

}

private void sendLoginForm(HttpServletResponse response, boolean withErrorMessage)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Login</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

if (withErrorMessage) {

out.println("Login failed. Please try again.<BR>");

out.println("If you think you have entered the correct user name" + " and password, the cookie setting in your browser might be off." +

157

"<BR>Click <A HREF=InfoPage.html>here</A> for information" +

" on how to turn it on.<BR>");

}

out.println("<BR>");

out.println("<BR><H2>Login Page</H2>");

out.println("<BR>");

out.println("<BR>Please enter your user name and password.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>User Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=userName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password:</TD>");

out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD ALIGN=RIGHT COLSPAN=2>");

out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

try {

FL

Y

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con =

AM

Statement s = con.createStatement(); TE

ResultSet rs = s.executeQuery(sql);

if (rs.next()) {

rs.close();

s.close();

con.close();

return true;

}

rs.close();

s.close();

con.close();

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

catch (SQLException e) {

System.out.println(e.toString());

}

catch (Exception e) {

System.out.println(e.toString());

}

return false;

Team-Fly ®

}

}

Listing 5.19 The Content2Servlet

Listing x: Content2Servlet import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class Content2Servlet extends HttpServlet {

public String loginUrl = "SessionLoginServlet";

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException {

HttpSession session = request.getSession();

if (session == null)

response.sendRedirect(loginUrl);

else {

String loggedIn = (String) session.getAttribute("loggedIn");

if (!loggedIn.equals("true"))

response.sendRedirect(loginUrl);

}

// This is an authorized user, okay to display content

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Welcome</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("Welcome.");

out.println("</BODY>");

out.println("</HTML>");

}

/**Process the HTTP Post request*/

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

doGet(request, response);

}

}

Session Tracking with URL-Rewriting

As mentioned previously, by default a session identifier is sent to the client browser and back to the server using a cookie. This means that the client browser must have its cookie support enabled.

Therefore, you need to perform browser cookie testing as explained in the previous section,

" Checking Whether Cookie Setting Is On ."

Alternatively, you can avoid the use of cookies by sending session identifiers in the URL using the

URL-rewriting technique. Fortunately, the Servlet API provides an easy way to append session identifier to the URL—using the encodeURL method of the javax.servlet.http.HttpServletResponse interface.

159

To use the URL-rewriting technique, pass any URL referenced to in a servlet into the encodeURL method of the javax.servlet.http.HttpServletResponse interface. For example, the following code: out.println("<a href=Servlet2>Click here</a>"); must be changed into the following: out.println("<a href=" + response.encodeURL("Servlet2") +

">Click here</a>");

This will add the session identifier to the end of the string, resulting in a URL similar to the following: http://localhost:8080/myApp/servlet/Servlet2;jsessionid=AB34898928342

9489234At where the number after jsessionid= is the session identifier.

One disadvantage of using URL rewriting as opposed to cookies in sending your session identifiers is that URL rewriting does not survive static pages. For example, if the user has to browse through some HTML page during his or her session, the session identifier will be lost.

The not-so-practical solution is of course to convert all static pages into servlets or JSP pages.

Knowing Which Technique to Use

Having learned the four techniques for managing user sessions, you may be wondering which one you should choose to implement.

Clearly, using Session objects is the easiest and you should use this if your servlet container supports swapping Session objects from memory to secondary storage. If you are using Tomcat 4, this feature is available to you.

One concern when using the Session objects is whether cookie support is enabled in the user browser. If it is, you have two options:

You can test the cookie support setting by using the technique described in the section

" Checking Whether Cookie Setting Is On ."

You can use URL-rewriting.

Appending your session identifier to the URL is a good technique, even though this creates some additional work for the programmer. However, this relieves you of having to rely on cookies.

Using cookies is not as flexible as using Session objects. However, cookies are the way to go if you don't want your server to store any client-related information or if you want the client information to persist when the browser is closed.

Finally, hidden fields are probably the least-often-used technique. If you need to split a form into several smaller ones, however, using hidden fields is the cheapest and most efficient method. You don't need to consume server resources to temporarily store the values from the previous forms, and you don't need to rely on cookies. I would suggest hidden fields over Session objects, URLrewriting, or cookies in this case.

160

Summary

In this chapter, you have learned that HTTP is a stateless protocol. You also have been shown the implications of this statelessness. Additionally you learned about four techniques you can use to manage user sessions. Each technique has been described, and examples have been built to demonstrate the technique.

161

Chapter 6. Application and Session Events

In

Chapter 3 , "Writing Servlet Applications," you learned how to use the ServletContext object to

share information among all the servlets in a web application. You also learned how to obtain this object so that you can use its methods. The ServletContext object is created by the servlet container, and, among other things, it has a method called setAttribute. That method causes the object to act like a Hashtable, where you can store an object that is identified by a key and later retrieve the object by passing the key.

In

Chapter 5 , "Session Management," you learned how to create and invalidate the HttpSession

object. You also learned how to use an HttpSession object to store user session information.

Similar to the ServletContext object, an Httpsession enables you to store key/object pairs. Unlike the ServletContext, which is accessible by all the servlets, an HttpSession object is linked to a particular user and is available only to that user.

In this chapter, you see a new feature in the Servlet 2.3 API Specification that has to do with both the ServletContext and HttpSession objects. This new feature supports application and sessionlevel events. If you use Tomcat 4, this new feature is available to you.

The concept is very simple, so let me provide you an overview.

In relation to the ServletContext object, the Servlet 2.3 API enables you to get notifications when the ServletContext object is created and destroyed, or when an attribute (a key/object pair) is created, removed, or replaced. The moments these things occur have now become Java events that you can listen to.

The question is, why would you want to know when these things happen? Surely you can live without these events; however, they can be very useful because you can write code that gets called automatically when one of the events happens. For example, you know that the ServletContext object is created by the servlet container when it initializes. You can therefore do certain things in response to this event, such as loading a JDBC driver or creating a database connection object. Or, you probably want to initialize a connection URL and store it as a variable in the ServletContext object so that it is accessible from all the servlets in the web application.

For events that get triggered when the ServletContext is destroyed, you can write code that does some cleanup, such as closing files or ending a database connection.

The same applies to events related to ContextServlet's attributes. For example, you can make a persistent page counter whose value gets written to a file every time the value is changed.

Assuming that you store this counter value as an attribute in the ServletContext object, you can write some I/O code that automatically executes when the ServletContext's attribute gets replaced, thus allowing for an accurate count.

Additionally, with an HttpSession object, you also can get notified when an HttpSession object is created or invalidated or when an attribute of a HttpSession object is added, removed, or replaced.

In this chapter, you will see various event classes and listener interfaces that support event notification for state changes in the ServletContext and the HttpSession objects.

Listening to Application Events

162

At the application level, the javax.servlet package provides two listener interfaces that support event notifications for state changes in the ServletContext object: the ServletContextListener interface and the ServletContextAttributesListener interface.

The ServletContextListener Interface

You can use the ServletContextListener interface to listen to the ServletContext life cycle events.

Its signature is given as follows: public interface ServletContextListener extends java.util.EventListener

Your listener class must implement this interface to listen to ServletContext life cycle events. The

ServletContextListener interface has two methods: contextInitialized and contextDestroyed. The signatures for these methods are the following: public void contextInitialized(ServletContextEvent sce) public void contextDestroyed(ServletContextEvent sce)

The contextInitialized method is called when the web application is ready to service requests. The method is called automatically by the servlet container when its own initialization process is finished. You can write code that needs to get executed when the application initializes, such as loading a JDBC driver, creating a database Connection object, or assigning initialization values to global variables.

The contextDestroyed method is invoked when the servlet context is about to be shut down. You can use this method to write code that needs to run when the application shuts down, such as closing a database connection or writing to the log.

Utilizing the contextInitialized method is similar to writing code in a servlet's init() method, and the contextDestroyed method has a similar effect as a servlet's destroy() method. However, using application events make the codes available throughout the whole application, not only from inside a servlet.

The ServletContextEvent Class

As you have seen, both methods of the ServletContextListener interface pass a

ServletContextEvent class. This class has the following signature: public class ServletContextEvent extends java.util.EventObject

The ServletContextEvent has only one method: getServletContext. This method returns the

ServletContext that is changed.

Deployment Descriptor

To use application events and include a servlet listener class, you must tell the servlet container by registering the listener class in the deployment descriptor. The <web-app> element must contain a

<listener> element like the following:

<web-app>

<listener>

<listener-class>

AppLifeCycleEvent

</listener-class>

163

</listener>

</web-app>

The <listener> element must come before the <servlet> part.

An Example: AppLifeCycleEvent Class

The following is a simple listener class that listens to the life cycle events of the ServletContext. It simply prints the string "Application initialized" when the ServletContext is initialized and

"Application destroyed" when the ServletContext is destroyed. The code for the program is given in

Listing 6.1

.

Listing 6.1 The AppLifeCycleEvent Class

import javax.servlet.ServletContextListener; import javax.servlet.ServletContextEvent; public class AppLifeCycleEvent implements ServletContextListener {

public void contextInitialized(ServletContextEvent cse) {

System.out.println("Application initialized");

}

public void contextDestroyed(ServletContextEvent cse) {

System.out.println("Application shut down");

}

}

For the AppLifeCycleEvent class to work, you must register it in the deployment descriptor. The deployment descriptor is given in

Listing 6.2

.

Listing 6.2 The Deployment Descriptor for the AppLifeCycleEvent Class

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<listener>

<listener-class>

AppLifeCycleEvent

</listener-class>

</listener>

</web-app>

Now, restart Tomcat and watch the console window. You should be able to see the string

"Application initialized" at the console.

If you want, you can have more than one listener class. To do this, list all the listener classes in the deployment descriptor, as follows:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

164

<web-app>

<listener>

<listener-class>

AppLifeCycleEvent1

</listener-class>

</listener>

<listener>

<listener-class>

AppLifeCycleEvent2

</listener-class>

</listener>

</web-app>

With a deployment descriptor like this, when Tomcat starts, it will call the contextInitialized method in the AppLifeCycleEvent1 class and then call the same method in the

AppLifeCycleEvent2 class.

Another Example: Loading a JDBC Driver and Setting a ServletContext Attribute

The following example uses the contextInitialized method in the ServletContextListener interface to load a JDBC driver and set a ServletContext attribute named "dbUrl" with a value of

"jdbc:mysql///Fred". Loading the JDBC driver here makes it available for the next access to the database.

The example has two classes: a listener class called AppLifeCycleEventDemo and a servlet named

ApplicationEventDemoServlet. The listener class provides a method (contextInitialized) that will be called automatically when the ServletContext object is initialized. This is where you put the code that loads the JDBC driver and sets a ServletContext attribute. The servlet is used to display

the attribute value. The AppLifeCycleEventDemo class is given in Listing 6.3

, and the

ApplicationEventDemoServlet in

Listing 6.4

.

Listing 6.3 AppLifeCycleEventDemo

import javax.servlet.ServletContext; import javax.servlet.ServletContextListener; import javax.servlet.ServletContextEvent; public class AppLifeCycleEventDemo implements ServletContextListener

{

public void contextInitialized(ServletContextEvent sce) {

System.out.println("Initializing Application …");

// Load the JDBC driver

try {

Class.forName("org.gjt.mm.mysql.Driver ");

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

// Get the ServletContext object

ServletContext servletContext = sce.getServletContext();

// Set a ServletContext attribute

servletContext.setAttribute("dbUrl", "jdbc:mysql///Fred");

System.out.println("Application initialized");

}

165

public void contextDestroyed(ServletContextEvent cse) {

System.out.println("Application shut down");

}

}

Note that before you can set a ServletContext attribute, you first need to obtain the ServletContext object using the getServletContext method of the ServletContextEvent class. This is shown in the following line of code from

Listing 6.3

.

ServletContext servletContext = sce.getServletContext();

In the servlet, to get an attribute from the ServletContext object, you need first to obtain the

ServletContext object. In a servlet that extends the javax.servlet.http.HttpServlet class, you can use the getServletContext method to achieve this, as demonstrated in the code in

Listing 6.4

.

Listing 6.4 The ApplicationEventDemoServlet Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ApplicationEventDemoServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Application Event Demo Servlet</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("Your database connection is ");

// get the ServletContext object

ServletContext servletContext = getServletContext();

// display the "dbUrl" attribute

out.println(servletContext.getAttribute("dbUrl"));

out.println("</BODY>");

out.println("</HTML>");

}

}

Listing 6.5

gives you the deployment descriptor you need for the application to work.

Listing 6.5 The Deployment Descriptor for the Example

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<listener>

<listener-class>

AppLifeCycleEventDemo

</listener-class>

</listener>

166

<servlet>

<servlet-name>

ApplicationEventDemo

</servlet-name>

<servlet-class>

ApplicationEventDemoServlet

</servlet-class>

</servlet>

</web-app>

After you compile both classes, restart Tomcat and direct your browser to the servlet URL. You should see something similar to

Figure 6.1

.

Figure 6.1. Obtaining an attribute value set when the application initializes.

Listening to ServletContextAttributeListener

In addition to a life cycle listener, you also can implement the ServletContextAttributeListener class to be notified when any attribute is added to the ServletContext or if any of the

ServletContext's attributes are changed or removed. Implementing this interface, you must provide implementations for its three methods: attributeAdded, attributeRemoved, and attributeReplace.

The signatures for those methods are as follows: public void attributeAdded(ServletContextAttributeEvent scae) public void attributeRemoved(ServletContextAttributeEvent scae) public void attributeReplaced(ServletContextAttributeEvent scae)

The attributeAdded method is called when a new attribute is added to the ServletContext object.

The attributeRemove method is called when an attribute is removed from the ServletContext object, and the attributeReplaced method is invoked when an attribute in the ServletContext object is replaced.

167

Note that attribute changes may occur concurrently. It is your responsibility to ensure that accesses to a common resource are synchronized.

Another Example: PageCounterServlet

As another example, consider the following application that provides a page counter for a servlet.

The servlet increments a counter every time it is requested, thus the name page counter. The value of the counter is stored as an attribute of the ServletContext object so that it can be accessed from any servlet in the application. However, if the servlet container crashes, you will not lose this value because the value is also written to a text file called counter.txt. Clearly, this is a type of application you can use to measure the popularity of your site.

The application consists of two classes. The first is a listener class named

AppAttributeEventDemo and the second is a servlet called PageCounterServlet.

The AppAttributeEventDemo implements both ServletContextListener interface and

ServletContextAttributeListener interface. In the contextInitialized method, you write the code that will read the counter value from the counter.txt file and use this value to initialize a

ServletContext attribute named pageCounter. As in the previous example, you need to obtain the

ServletContext object from the ServletContextEvent object passed to the contextInitialized method.

Every time the PageCounterServlet servlet is requested, it will increment the value of pageCounter.

When this happens, the attributeReplaced method of the listener class will be triggered. In this

Y called from the attributeReplaced method, is synchronized. Here is where you write the code to write pageCounter to the file.

The listener class is given in

Listing 6.6

compile these two classes, open your browser and type the URL for the servlet. You should see something similar to

Figure 6.2

.

TE

AM

Listing 6.7

. After you

Team-Fly ®

Listing 6.6 The AppAttributeEventDemo class

import javax.servlet.ServletContext; import javax.servlet.ServletContextListener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletContextAttributeEvent; import java.io.*; public class AppAttributeEventDemo

implements ServletContextListener, ServletContextAttributeListener

{

int counter;

String counterFilePath = "C:\\counter.txt";

public void contextInitialized(ServletContextEvent cse) {

try {

BufferedReader reader = new

BufferedReader(new FileReader(counterFilePath));

counter = Integer.parseInt( reader.readLine() );

reader.close();

System.out.println("Reading" + counter);

}

catch (Exception e) {

System.out.println(e.toString());

}

ServletContext servletContext = cse.getServletContext();

servletContext.setAttribute("pageCounter",

Integer.toString(counter));

System.out.println("Application initialized");

}

169

public void contextDestroyed(ServletContextEvent cse) {

System.out.println("Application shut down");

}

public void attributeAdded(ServletContextAttributeEvent scae) {

System.out.println("ServletContext attribute added");

}

public void attributeRemoved(ServletContextAttributeEvent scae) {

System.out.println("ServletContext attribute removed");

}

public void attributeReplaced(ServletContextAttributeEvent scae) {

System.out.println("ServletContext attribute replaced");

writeCounter(scae);

}

synchronized void writeCounter(ServletContextAttributeEvent scae) {

ServletContext servletContext = scae.getServletContext();

counter = Integer.parseInt((String)

servletContext.getAttribute("pageCounter"));

try {

BufferedWriter writer = new

BufferedWriter(new FileWriter(counterFilePath));

writer.write(Integer.toString(counter));

writer.close();

System.out.println("Writing");

}

catch (Exception e) {

System.out.println(e.toString());

}

}

}

Listing 6.7 The PageCounterServlet Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class PageCounterServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Page Counter</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

ServletContext servletContext = getServletContext();

int pageCounter = Integer.parseInt((String)

servletContext.getAttribute("pageCounter"));

pageCounter++;

out.println("You are visitor number " + pageCounter);

servletContext.setAttribute("pageCounter",

Integer.toString(pageCounter));

170

out.println("</BODY>");

out.println("</HTML>");

}

}

The deployment descriptor for the example is given in Listing 6.8

.

Listing 6.8 The Deployment Descriptor for the PageCounter Example

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<listener>

<listener-class>

AppAttributeEventDemo

</listener-class>

</listener>

<servlet>

<servlet-name>

PageCounter

</servlet-name>

<servlet-class>

PageCounterServlet

</servlet-class>

</servlet>

</web-app>

Note that the attributeReplaced also is called when the attributeAdded is triggered.

Listening to HttpSession Events

The javax.servlet.http package provides two interfaces that you can implement to listen to

HttpSession events: HttpSessionListener and HttpSessionAttributeListener. The first enables you to listen to a session's life cycle events, that is, the event that gets triggered when an HttpSession object is created and the event that is raised when an HttpSession object is destroyed. The second interface, HttpSessionAttributeListener, provides events that get raised when an attribute is added to, removed from, or modified in the HttpSession object.

The two interfaces are explained next.

The HttpSessionListener Interface

The HttpSessionListener interface has two methods: sessionCreated and sessionDestroyed. The signatures of the two methods are given here: public void sessionCreated(HttpSessionEvent se) public void sessionDestroyed(HttpSessionEvent se)

171

The sessionCreated method is automatically called when an HttpSession object is created. The sessionDestroyed method is called when an HttpSession object is invalidated. Both methods will be passed in an HttpSessionEvent class that you can use from inside the method.

The HttpSessionEvent class is derived from the java.util.EventObject class. The HttpSessionEvent class defines one new method called getSesssion that you can use to obtain the HttpSession object that is changed.

An Example: User Counter

The following example is a counter that counts the number of different users currently "in session." It creates an HttpSession object for a user the first time the user requests the servlet. If the user comes back to the same servlet, no HttpSession object will be created the second time.

Therefore, the counter is incremented only when an HttpSession object is created.

An HttpSession object can also be destroyed, however. When this happens, the counter must be decremented. For the counter to be accessible to all users, it is stored as an attribute in the

ServletContext object.

The example has two classes: the listener class and a servlet class that displays the counter value.

The listener class is named SessionLifeCycleEventDemo and implements both the

ServletContextListener interface and the HttpSessionListener interface. You need the first interface so that you can create a ServletContext attribute and assign it an initial value of 0. As you can guess, you put this code in the contextInitialized method, as in the following: public void contextInitialized(ServletContextEvent sce) {

servletContext = sce.getServletContext();

servletContext.setAttribute(("userCounter"),

Integer.toString(counter));

}

Notice that the ServletContext object is assigned to a class variable servletContext, making the

ServletContext object available from anywhere in the class.

The counter must be incremented when an HttpSession is created and decremented when an

HttpSession is destroyed. Therefore, you need to provide implementations for both sessionCreated and sessionDestroyed methods, as you see here: public void sessionCreated(HttpSessionEvent hse) {

System.out.println("Session created.");

incrementUserCounter();

} public void sessionDestroyed(HttpSessionEvent hse) {

System.out.println("Session destroyed.");

decrementUserCounter();

}

The sessionCreated method calls the synchronized method incrementUserCounter and the sessionDestroyed method calls the synchronized method decrementUserCounter.

The incrementUserCounter method first obtains an attribute called userCounter from the

ServletContext object, increments the counter, and stores the counter back to the userCounter attribute. synchronized void incrementUserCounter() {

172

counter = Integer.parseInt(

(String)servletContext.getAttribute("userCounter"));

counter++;

servletContext.setAttribute(("userCounter"),

Integer.toString(counter));

System.out.println("User Count: " + counter);

}

The decrementUserCounter method does the opposite. It first obtains the userCounter attribute from the ServletContext object, decrements the counter, and stores the counter back to the userCounter attribute, as you see here: synchronized void decrementUserCounter() {

int counter = Integer.parseInt(

(String)servletContext.getAttribute("userCounter"));

counter––;

servletContext.setAttribute(("userCounter"),

Integer.toString(counter));

System.out.println("User Count: " + counter);

}

The listener class is given in Listing 6.9

.

Listing 6.9 The SessionLifeCycleEventDemo Class

import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; public class SessionLifeCycleEventDemo

implements ServletContextListener, HttpSessionListener {

ServletContext servletContext;

int counter;

public void contextInitialized(ServletContextEvent sce) {

servletContext = sce.getServletContext();

servletContext.setAttribute(("userCounter"),

Integer.toString(counter));

}

public void contextDestroyed(ServletContextEvent sce) {

}

public void sessionCreated(HttpSessionEvent hse) {

System.out.println("Session created.");

incrementUserCounter();

}

public void sessionDestroyed(HttpSessionEvent hse) {

System.out.println("Session destroyed.");

decrementUserCounter();

}

synchronized void incrementUserCounter() {

counter = Integer.parseInt(

(String)servletContext.getAttribute("userCounter"));

counter++;

servletContext.setAttribute(("userCounter"),

Integer.toString(counter));

System.out.println("User Count: " + counter);

173

}

synchronized void decrementUserCounter() {

int counter = Integer.parseInt(

(String)servletContext.getAttribute("userCounter"));

counter—;

servletContext.setAttribute(("userCounter"),

Integer.toString(counter));

System.out.println("User Count: " + counter);

}

}

The second class of the application is the UserCounterServlet. This servlet displays the value of the userCounter ServletContext attribute whenever someone requests the servlet. The code that does this is written in the doGet method.

When the doGet method is invoked, you obtain the ServletContext object by calling the getServletContext method.

ServletContext servletContext = getServletContext();

Then, the method tries to obtain an HttpSession object from the HttpServletRequest object and creates one if no HttpSession object exists, as follows:

HttpSession session = request.getSession(true);

Next, you need to get the userCounter attribute from the ServletContext object: int userCounter = 0; userCounter = Integer.parseInt(

(String)servletContext.getAttribute("userCounter"));

The complete code for the servlet is given in Listing 6.10

.

Listing 6.10 The userCounterServlet Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class UserCounterServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

ServletContext servletContext = getServletContext();

HttpSession session = request.getSession(true);

int userCounter = 0;

userCounter =

Integer.parseInt((String)servletContext.getAttribute("userCounter"));

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>User Counter</TITLE>");

out.println("</HEAD>");

174

out.println("<BODY>");

out.println("There are " + userCounter + " users.");

out.println("</BODY>");

out.println("</HTML>");

}

}

For the example to work, you need to create a deployment descriptor as given in Listing 6.11

.

Listing 6.11 The Deployment Descriptor for the UserCounter Example

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<listener>

<listener-class>

SessionLifeCycleEventDemo

</listener-class>

</listener>

<servlet>

<servlet-name>

UserCounter

</servlet-name>

<servlet-class>

UserCounterServlet

</servlet-class>

</servlet>

</web-app>

After you compile the two classes, open your browser and type in the URL for the servlet. You should see something similar to

Figure 6.3

.

Figure 6.3. The user counter.

175

The HttpSessionAttributeListener Interface

The second session event listener interface is HttpSessionAttributeListener. You can implement this interface if you need to listen to events related to session attributes. The interface provides three methods: attributeAdded, attributeRemoved, and attributeReplaced. The signatures of the three methods are as follows: public void attributeAdded(HttpSessionBindingEvent sbe) public void attributeRemoved(HttpSessionBindingEvent sbe) public void attributeReplaced(HttpSessionBindingEvent sbe)

The attributeAdded method is called when an attribute is added to an HttpSession object. The attributeRemoved and attributeReplaced methods are called when an HttpSession attribute is removed or replaced, respectively.

All the methods receive an HttpSessionBindingEvent object whose class is described next.

The HttpSessionBindingEvent is derived from the HttpSessionEvent class so it inherits the getSession method. In addition, the HttpSessionBindingEvent class has two methods: getName and getValue. The signatures of the two methods are as follows: public String getName() public Object getValue()

The getName method returns the name of the attribute that is bound to an HttpSession or unbound from an HttpSession. The getValue method returns the value of an HttpSession attribute that has been added, removed, or replaced.

176

Summary

This chapter introduced application and session events and described the use of those events with a few examples. The ability to listen to these events are not very critical, however they can be very useful as shown in the examples in this chapter.

177

Chapter 7. Servlet Filtering

Filters are new in the Servlet 2.3 specification, enabling you to intercept a request before it reaches a resource. In other words, a filter gives you access to the HttpServletRequest and the

HttpServletResponse objects before they are passed in to a servlet.

Filters can be very useful. For example, you can write a filter that records all incoming requests and logs the IP addresses of the computers from which the requests originate. You also can use a filter as an encryption and decryption device. Other uses include user authentication, data compression, user input validation, and so on.

For a filter to intercept a request to a servlet, you must declare the filter with a <filter> element in the deployment descriptor and map the filter to the servlet using the <filter-mapping> element.

Sometimes you want a filter to work on multiple servlets. You can do this by mapping a filter to a

URL pattern so that any request that matches that URL pattern will be filtered.

You also can put a set of filters in a chain. The first filter in the chain will be called first and then pass control to the second filter, and so on. Filter chaining ensures that you can write a filter that does a specific task but adds some functionality in another filter.

This chapter starts with javax.servlet.Filter, an interface that a filter class must implement. The classes and interfaces.

FL

Y

An Overview of the API

When writing a filter, you basically deal with the following three interfaces in the javax.servlet package:

TE

Filter

AM

FilterConfig

FilterChain

These three interfaces are described in the next sections.

The Filter Interface

javax.servlet.Filter is an interface that you must implement when writing a filter. The life cycle of a filter is represented by this interface's three methods: init, doFilter, and destroy. Their signatures are given here: public void init(FilterConfig filterConfig) public void doFilter(HttpServletRequest request,

HttpServletResponse response, FilterChain chain) public void destroy()

A filter starts its life when its init method is called by the servlet container. The servlet container calls a filter's init method only once, when it finishes instantiating the filter. The servlet container will pass in the FilterConfig object that represents the filter configuration. Normally, you assign

Team-Fly ®

this object to an object variable so that the FilterConfig object will be available from other methods. Compare the init method with the init method of the Servlet interface.

The doFilter method is where the filtering is performed. The servlet container calls the doFilter method every time a user requests a resource, such as a servlet, to which the filter is mapped.

When doFilter is invoked, the servlet container passes in the HttpServletRequest object, the

HttpServletResponse object, and a FilterChain object. The HttpServletRequest and

HttpServletResponse objects are the same objects that will get passed to a servlet. You can manipulate these two objects. For example, you can add an attribute to the HttpServletRequest using the setAttribute method, or you can obtain the PrintWriter object of the HttpServletResponse and write to it. The FilterChain object is useful here so that you can pass control to the next resource. It will be explained in more detail when we discuss the FilterChain later in this chapter.

The doFilter method is analogous to the service method of the Servlet interface. The servlet container calls the destroy method to tell the filter that it will be taken out of service. The filter can then do some clean-up, if necessary. For instance, it can close a resource that it opened at initialization. The destroy method in the Filter interface is similar to the destroy method in the

Servlet interface.

The FilterConfig Interface

A FilterConfig object represents the configuration for the filter. This object allows you to obtain the ServletContext object and pass initialization values to the filter through its initial parameters, which you define in the deployment descriptor when declaring the filter.

The FilterConfig interface has four methods: getFilterName, getInitParameter, getInitParameterNames, and getServletContext. The signatures for these methods are as follows: public String getFilterName() public String getInitParameter(String parameterName) public java.util.Enumeration getInitParameterNames() public ServletContext getServletContext()

The getFilterName method returns the name of the filter and the getServletContext method returns the ServletContext object. The getInitParameterNames gives you an Enumeration containing all parameter names of the filter. You then can retrieve the value of each individual initial parameter using the getInitParameter, passing the parameter name.

The FilterChain Interface

As mentioned previously, a FilterChain object is passed in by the servlet container to the doFilter method of the filter class. Filters use the FilterChain object to invoke the next filter in the chain, or, if the filter is the last in the chain, to invoke the next resource (servlet).

The FilterChain interface has only one method: doFilter, whose signature is given as follows: public void doFilter(HttpServletRequest request, HttpServletResponse response)

Note

Don't confuse this method with the doFilter method of the Filter interface. The latter has three arguments.

179

You should always call the FilterChain interface's doFilter method to pass control over to the next filter. If you are using only one filter, the doFilter method passes control to the next resource, which can be a servlet you want to filter. Failure to call this method will make the program flow stop.

A Basic Filter

As an example of your first filter, I will present here a very basic filter that does nothing other than show its life cycle by printing a message to the console every time its method is invoked. This filter also declares a FilterConfig object reference called filterConfig. In the init method, you pass the FilterConfig object to this variable. Notice that the filter's doFilter method calls the doFilter method of the FilterChain object at the last line of the method. You can find the code for the filter, appropriately named BasicFilter, in

Listing 7.1

.

Listing 7.1 The BasicFilter Class

import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class BasicFilter implements Filter {

private FilterConfig filterConfig;

public void init(FilterConfig filterConfig) throws ServletException

{

System.out.println("Filter initialized");

this.filterConfig = filterConfig;

}

public void destroy() {

System.out.println("Filter destroyed");

this.filterConfig = null;

}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain)

throws IOException, ServletException {

System.out.println("doFilter");

chain.doFilter(request, response);

}

}

For the filter to work, you need to decide which servlet or servlets you want to filter and tell the servlet container by declaring the filter in the deployment descriptor using the <filter> element and the <filter-mapping> element. These two elements must come before any <listener> and <servlet>

elements. The deployment descriptor for this example is given in Listing 7.2

.

Listing 7.2 The Deployment Descriptor for this Example

180

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<!–– Define servlet-mapped and path-mapped filters ––>

<filter>

<filter-name>

Basic Filter

</filter-name>

<filter-class>

BasicFilter

</filter-class>

</filter>

<!–– Define filter mappings for the defined filters ––>

<filter-mapping>

<filter-name>

Basic Filter

</filter-name>

<servlet-name>

FilteredServlet

</servlet-name>

</filter-mapping>

<listener>

<listener-class>

SessionLifeCycleEventDemo

</listener-class>

</listener>

<servlet>

<servlet-name>

FilteredServlet

</servlet-name>

<servlet-class>

FilteredServlet

</servlet-class>

</servlet>

</web-app>

You can see that the filter name is Basic Filter and its class is BasicFilter. You also find a <filtermapping> element that maps the filter to a servlet called FilteredServlet. You need to create a servlet (that does anything) called FilteredServlet to see the example work.

After you compile the filter and servlet classes and modify your deployment descriptor, restart the servlet container. You should see the message sent from the filter's init method in the console.

Open your browser and type the URL to the FilteredServlet servlet. You should see more messages in the console that show how the filter is invoked before the servlet.

If you want to apply the filter to more than one servlet, you need only to repeat the <filtermapping> element for each servlet. For example, the filter applies to both FilteredServlet and

FilteredServlet2 in the following deployment descriptor in

Listing 7.3

.

Listing 7.3 The Deployment Descriptor that Applies the Filter to More than One

Servlet

<?xml version="1.0" encoding="ISO-8859-1"?>

181

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<!–– Define servlet-mapped and path-mapped filters ––>

<filter>

<filter-name>

Basic Filter

</filter-name>

<filter-class>

BasicFilter

</filter-class>

</filter>

<!–– Define filter mappings for the defined filters ––>

<filter-mapping>

<filter-name>

Basic Filter

</filter-name>

<servlet-name>

FilteredServlet

</servlet-name>

</filter-mapping>

<filter-mapping>

<filter-name>

Basic Filter

</filter-name>

<servlet-name>

FilteredServlet2

</servlet-name>

</filter-mapping>

<servlet>

<servlet-name>

FilteredServlet

</servlet-name>

<servlet-class>

FilteredServlet

</servlet-class>

</servlet>

<servlet>

<servlet-name>

FilteredServlet2

</servlet-name>

<servlet-class>

FilteredServlet2

</servlet-class>

</servlet>

</web-app>

Mapping a Filter with a URL

In addition to mapping a filter to a servlet or a number of servlets, you can map the filter to a URL pattern so all requests that match that pattern will invoke the filter.

182

Consider a servlet whose URL is similar to the following: http://localhost:8080/myApp/servlet/FilteredServlet

To map a filter to a URL pattern, you use the <filter-mapping> element of your deployment descriptor similar to the following:

<!–– Define filter mappings for the defined filters ––>

<filter-mapping>

<filter-name>

Logging Filter

</filter-name>

<url-pattern>/servlet/FilteredServlet</url-pattern>

</filter-mapping>

As an alternative, you can use /* to make the filter work for all static and dynamic resources, as follows:

<!–– Define filter mappings for the defined filters ––>

<filter-mapping>

<filter-name>

Logging Filter

</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

A Logging Filter

Here is another simple example of a filter that logs user IP addresses to the log file. The location of the log file is servlet container implementation specific. (See

Appendix A , "Tomcat Installation

and Configuration," for more information.)

The filter class is given in

Listing 7.4

.

Listing 7.4 The Logging Filter

import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class LoggingFilter implements Filter {

private FilterConfig filterConfig = null;

public void destroy() {

System.out.println("Filter destroyed");

this.filterConfig = null;

}

public void doFilter(ServletRequest request, ServletResponse response,

183

FilterChain chain)

throws IOException, ServletException {

System.out.println("doFilter");

// Log user's IP address.

ServletContext servletContext = filterConfig.getServletContext();

servletContext.log(request.getRemoteHost());

chain.doFilter(request, response);

}

public void init(FilterConfig filterConfig) throws ServletException

{

System.out.println("Filter initialized");

this.filterConfig = filterConfig;

}

}

Not much difference exists between this filter and the BasicFilter, except that the doFilter method obtains the ServletContext object and uses its log to record the client IP address obtained from the getRemoteHost method of the HttpServletRequest object. The following code shows this action:

// Log user's IP address.

ServletContext servletContext = filterConfig.getServletContext(); servletContext.log(request.getRemoteHost());

The deployment descriptor of this example is given in Listing 7.5

.

Listing 7.5 The Deployment Descriptor for the LoggingFilter

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<!–– Define servlet-mapped and path-mapped filters ––>

<filter>

<filter-name>

Logging Filter

</filter-name>

<filter-class>

LoggingFilter

</filter-class>

</filter>

<!–– Define filter mappings for the defined filters ––>

<filter-mapping>

<filter-name>

Logging Filter

</filter-name>

<servlet-name>

FilteredServlet

</servlet-name>

</filter-mapping>

<servlet>

<servlet-name>

FilteredServlet

</servlet-name>

184

<servlet-class>

FilteredServlet

</servlet-class>

</servlet>

</web-app>

Practically, any servlet named FilteredServlet will invoke the filter. Listing 7.6

gives you an example of such a servlet.

Listing 7.6 A Servlet to Be Used with LoggingFilter

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class FilteredServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>User Counter</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("IP:" + request.getRemoteHost());

out.println("</BODY>");

out.println("</HTML>");

}

}

Filter Configuration

You can pass some initial parameters to a filter in a FilterConfig object that gets passed into the init method of the Filter interface. The initial parameters are declared in the deployment descriptor using the <init-param> element under the <filter> element. For example, the following deployment descriptor in

Listing 7.7

describes a filter called MyFilter with two initial parameters:

adminPhone and adminEmail.

Listing 7.7 The Deployment Descriptor with a Filter with Two Initial Parameters

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<!–– Define servlet-mapped and path-mapped filters ––>

<filter>

<filter-name>

MyFilter

</filter-name>

<filter-class>

185

MyFilter

</filter-class>

<init-param>

<param-name>

adminPhone

</param-name>

<param-value>

0414789098

</param-value>

</init-param>

<init-param>

<param-name>

adminEmail

</param-name>

<param-value>

[email protected]

</param-value>

</init-param>

</filter>

</web-app>

You then can retrieve the values of the AdminPhone and AdminEmail parameters using the following code, which you should put under the doFilter method of a filter:

String adminPhone = filterConfig.getInitParameter("adminPhone");

String adminEmail = filterConfig.getInitParameter("adminEmail");

A Filter that Checks User Input

When you receive input from a user, the first thing you should do is to check whether the input is valid. If the input is invalid, you normally send an error message, telling the user that a correct entry is needed.

Sometimes the input is not totally invalid; it only contains leading or trailing empty spaces. In this case, you don't need to send an error message, but you can make the correction yourself; that is, when you ask users to enter their first names into the firstName box in an HTML form, you need to make sure that they type in something like "John" or "George", not "John" or "George" (with blank spaces). Normally in situations like this, you use the trim function of the String class when you obtain a parameter value, as follows:

String firstName = request.getParameter("firstName"); if (firstName != null)

firstName = firstName.trim();

If you have quite a large number of input boxes in the HTML form, however, you have to call the trim method for every parameter. Additionally, you need to do this in every servlet that accepts user input. A filter can help make this task easier.

You can write a filter that trims every parameter value in the HttpServletRequest object before the

HttpServletRequest object reaches a servlet. This way, you don't need to trim anything in your

186

servlet. You need to write only one filter to serve all servlets that need this service. In the example that follows, you get a chance to write a filter that trims all parameter values.

To ensure that the filter is able to trim all parameters in a HttpServletRequest object, do not hardcode the name of the parameter. Instead, use the getParameterNames method to obtain an

Enumeration containing all the parameter names. Next, you need to loop through the Enumeration to get the parameter values and call the trim method.

You can't change a parameter value, however, which means that it is not possible to trim it directly.

A closer look at the HttpServletRequest reveals that you can set its attribute. What you can do is to put trimmed parameter values as attributes. The parameter names become attribute names. Later, in the servlet, instead of retrieving user input from HttpServletRequest parameters, you can obtain the trimmed versions of the input from the HttpServletRequest attributes, as shown here:

Enumeration enum = request.getParameterNames(); while (enum.hasMoreElements()) {

String parameterName = (String) enum.nextElement();

String parameterValue = request.getParameter(parameterName);

request.setAttribute(parameterName, parameterValue.trim());

}

In your servlet, do the following to get a trimmed input value: request.getAttribute(parameterName);

Instead of retrieving a value using the getParameter method of the HttpServletRequest, you use its getAttribute method.

The filter that does this service is called TrimFilter and its code is given in Listing 7.8

.

Listing 7.8 The TrimFilter

import java.io.*; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.util.Enumeration; public class TrimFilter implements Filter {

private FilterConfig filterConfig = null;

public void destroy() {

System.out.println("Filter destroyed");

this.filterConfig = null;

}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain)

throws IOException, ServletException {

System.out.println("Filter");

Enumeration enum = request.getParameterNames();

while (enum.hasMoreElements()) {

String parameterName = (String) enum.nextElement();

String parameterValue = request.getParameter(parameterName);

187

request.setAttribute(parameterName, parameterValue.trim());

}

chain.doFilter(request, response);

}

public void init(FilterConfig filterConfig) throws ServletException

{

System.out.println("Filter initialized");

this.filterConfig = filterConfig;

}

}

To illustrate the filter's use, you can write a servlet that does the following:

Send an HTML form with four input boxes (firstName, lastName, userName, and password) when its doGet method is invoked.

Display the user input when its doPost method is invoked.

The servlet is called TrimFilteredServlet and is given in

Listing 7.9

.

Listing 7.9 TrimFilteredServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*;

FL

Y public class TrimFilteredServlet extends HttpServlet { response)

throws ServletException, IOException {

response.setContentType("text/html");

out.println("<HTML>");

TE

out.println("<HEAD>");

out.println("<TITLE>User Input Form</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

out.println("<BR>Please enter your details.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=firstName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=lastName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>User Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=userName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password:</TD>");

Team-Fly ®

out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD ALIGN=RIGHT COLSPAN=2>");

out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String firstName = (String) request.getAttribute("firstName");

String lastName = (String) request.getAttribute("lastName");

String userName = (String) request.getAttribute("userName");

String password = request.getParameter("password");

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Displaying Values</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

out.println("Here are your details.");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name:</TD>");

out.println("<TD>" + StringUtil(firstName) + "</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name:</TD>");

out.println("<TD>" + StringUtil(lastName) + "</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>User Name:</TD>");

out.println("<TD>" + StringUtil(userName) + "</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password:</TD>");

out.println("<TD>" + StringUtil(password) + "</TD>");

out.println("</TABLE>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

}

To work properly, your application needs the deployment descriptor in Listing 7.10

.

Listing 7.10 The Deployment Descriptor

<?xml version="1.0" encoding="ISO-8859-1"?>

189

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<!–– Define servlet-mapped and path-mapped filters ––>

<filter>

<filter-name>

Trim Filter

</filter-name>

<filter-class>

TrimFilter

</filter-class>

</filter>

<!–– Define filter mappings for the defined filters ––>

<filter-mapping>

<filter-name>

Trim Filter

</filter-name>

<servlet-name>

TrimFilteredServlet

</servlet-name>

</filter-mapping>

<servlet>

<servlet-name>

TrimFilteredServlet

</servlet-name>

<servlet-class>

TrimFilteredServlet

</servlet-class>

</servlet>

</web-app>

When you run the servlet, it will first display something similar to Figure 7.1

.

Figure 7.1. The doGet method.

190

Notice that in this form the user enters a last name with a leading blank space. When the user

submits the form, the browser will display the figure similar to Figure 7.2

.

Figure 7.2. The doPost method.

See how the trailing blank spaces have disappeared? This is evidence of the filter at work.

191

Filtering the Response

You also can filter the response. In this example, you write a filter that appends a header and a footer of every servlet in the application. The filter code is given in

Listing 7.11

.

Listing 7.11 The ResponseFilter Class

import java.io.*; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.util.Enumeration; public class ResponseFilter implements Filter {

private FilterConfig filterConfig = null;

public void destroy() {

System.out.println("Filter destroyed");

this.filterConfig = null;

}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain)

throws IOException, ServletException {

System.out.println("doFilter");

PrintWriter out = response.getWriter();

// this is added to the beginning of the PrintWriter

out.println("<HTML>");

out.println("<BODY>");

out.println("<CENTER>");

out.println("Page header");

out.println("<HR>");

chain.doFilter(request, response);

// this is added to the end of the PrintWriter

out.println("<HR>");

out.println("Page footer");

out.println("<CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

public void init(FilterConfig filterConfig) throws ServletException

{

System.out.println("Filter initialized");

this.filterConfig = filterConfig;

}

}

An example of a servlet that is filtered is given in Listing 7.12

.

192

Listing 7.12 The ResponseFilteredServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class ResponseFilteredServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<BR>Please enter your details.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=firstName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=lastName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>User Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=userName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password:</TD>");

out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD ALIGN=RIGHT COLSPAN=2>");

out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

}

}

For the example to work, you need a deployment descriptor, as given in Listing 7.13

.

Listing 7.13 The Deployment Descriptor

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<!–– Define servlet-mapped and path-mapped filters ––>

<filter>

<filter-name>

Response Filter

</filter-name>

<filter-class>

193

ResponseFilter

</filter-class>

</filter>

<!–– Define filter mappings for the defined filters ––>

<filter-mapping>

<filter-name>

Response Filter

</filter-name>

<servlet-name>

ResponseFilteredServlet

</servlet-name>

</filter-mapping>

<servlet>

<servlet-name>

ResponseFilteredServlet

</servlet-name>

<servlet-class>

ResponseFilteredServlet

</servlet-class>

</servlet>

</web-app>

The result of the filter in Listing 7.13

is shown in Figure 7.3

.

Figure 7.3. Filtering the HttpServletResponse.

When you view the source code for the HTML, it looks like this:

<HTML>

<BODY>

<CENTER>

Page header

194

<HR>

<BR>Please enter your details.

<BR>

<BR><FORM METHOD=POST>

<TABLE>

<TR>

<TD>First Name:</TD>

<TD><INPUT TYPE=TEXT NAME=firstName></TD>

</TR>

<TR>

<TD>Last Name:</TD>

<TD><INPUT TYPE=TEXT NAME=lastName></TD>

</TR>

<TR>

<TD>User Name:</TD>

<TD><INPUT TYPE=TEXT NAME=userName></TD>

</TR>

<TR>

<TD>Password:</TD>

<TD><INPUT TYPE=PASSWORD NAME=password></TD>

</TR>

<TR>

<TD ALIGN=RIGHT COLSPAN=2>

<INPUT TYPE=SUBMIT VALUE=Login></TD>

</TR>

</TABLE>

</FORM>

<HR>

Page footer

<CENTER>

</BODY>

</HTML>

Filter Chain

You can apply more than one filter to a resource. In this example, you create the UpperCaseFilter and use the TrimFilter and a DoublyFilteredServlet. The UpperCaseFilter is given in

Listing 7.14

,

and the DoublyFilteredServlet is given in Listing 7.15

.

Listing 7.14 The UpperCaseFilter

import java.io.*; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.util.Enumeration; public class UpperCaseFilter implements Filter {

private FilterConfig filterConfig = null;

public void destroy() {

System.out.println("Filter destroyed");

this.filterConfig = null;

195

}

public void doFilter(ServletRequest request, ServletResponse response,

FilterChain chain)

throws IOException, ServletException {

System.out.println("Filter");

Enumeration enum = request.getAttributeNames();

while (enum.hasMoreElements()) {

String attributeName = (String) enum.nextElement();

String attributeValue = (String) request.getAttribute(attributeName);

request.setAttribute(attributeName, attributeValue.toUpperCase());

}

chain.doFilter(request, response);

}

public void init(FilterConfig filterConfig) throws ServletException

{

System.out.println("Filter initialized");

this.filterConfig = filterConfig;

}

}

Listing 7.15 The DoublyFilteredServlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import com.brainysoftware.java.StringUtil; public class DoublyFilteredServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>User Input Form</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

out.println("<BR>Please enter your details.");

out.println("<BR>");

out.println("<BR><FORM METHOD=POST>");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=firstName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=lastName></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>User Name:</TD>");

out.println("<TD><INPUT TYPE=TEXT NAME=userName></TD>");

196

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password:</TD>");

out.println("<TD><INPUT TYPE=PASSWORD NAME=password></TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD ALIGN=RIGHT COLSPAN=2>");

out.println("<INPUT TYPE=SUBMIT VALUE=Login></TD>");

out.println("</TR>");

out.println("</TABLE>");

out.println("</FORM>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String firstName = (String) request.getAttribute("firstName");

String lastName = (String) request.getAttribute("lastName");

String userName = (String) request.getAttribute("userName");

String password = request.getParameter("password");

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD>");

out.println("<TITLE>Displaying Values</TITLE>");

out.println("</HEAD>");

out.println("<BODY>");

out.println("<CENTER>");

out.println("Here are your details.");

out.println("<TABLE>");

out.println("<TR>");

out.println("<TD>First Name:</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(firstName) +

"</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Last Name:</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag (lastName) +

"</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>User Name:</TD>");

out.println("<TD>" + StringUtil.encodeHtmlTag(userName) +

"</TD>");

out.println("</TR>");

out.println("<TR>");

out.println("<TD>Password:</TD>");

out.println("<TD>" + StringUtil. encodeHtmlTag(password) +

"</TD>");

out.println("</TABLE>");

out.println("</CENTER>");

out.println("</BODY>");

out.println("</HTML>");

}

}

197

Note

Notice that the filters in the filter chain modified attributes because you can't modify the parameters in the HTTP request object.

The deployment descriptor is given in Listing 7.16

.

Listing 7.16 The Deployment Descriptor for this Example

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<!–– Define servlet-mapped and path-mapped filters ––>

<filter>

<filter-name>

Trim Filter

</filter-name>

<filter-class>

TrimFilter

</filter-class>

</filter>

<filter>

<filter-name>

UpperCase Filter

</filter-name>

<filter-class>

UpperCaseFilter

</filter-class>

</filter>

<filter-mapping>

<filter-name>

Trim Filter

</filter-name>

<servlet-name>

DoublyFilteredServlet

</servlet-name>

</filter-mapping>

TE

AM

FL

Y

<filter-mapping>

<filter-name>

UpperCase Filter

</filter-name>

<servlet-name>

DoublyFilteredServlet

</servlet-name>

</filter-mapping>

<servlet>

<servlet-name>

DoublyFilteredServlet

</servlet-name>

<servlet-class>

DoublyFilteredServlet

Team-Fly ®

</servlet-class>

</servlet>

</web-app>

Finally, Figure 7.4

shows the two filters in action. User input is now trimmed and turned into uppercase characters.

Figure 7.4. The result of the doPost of the DoublyFilteredServlet.

Summary

This chapter introduced you to filters, a new feature in Servlet 2.3 specification that enables you to perform some operations before the HTTP request reaches the servlet. Writing a filter involves in three interfaces: Filter, FilterConfig, and FilterChain. For the filter to work on a certain resource, you need to declare the filter in the deployment descriptor using the <filter> element and map it to the resources it is supposed to filter using the <filter-mapping> element. You can map a filter to a servlet or a URL pattern.

The next chapter will present the second technology for writing Java web application—JavaServer

Pages (JSP).

199

Chapter 8. JSP Basics

JavaServer Pages (JSP) is another Java technology for developing web applications. JSP was released during the time servlet technology had gained popularity as one of the best web technologies available. JSP is not meant to replace servlets, however. In fact, JSP is an extension of the servlet technology, and it is common practice to use both servlets and JSP pages in the same web applications.

Authoring JSP pages is so easy that you can write JSP applications without much knowledge of the underlying API. If you want to be a really good Java web programmer, however, you need to know both JSP and servlets. Even if you use only JSP pages in your Java web applications, understanding servlets is still very important. As you will see in this chapter and the chapters to come, JSP uses the same techniques as those found in servlet programming. For example, in JSP you work with HTTP requests and HTTP responses, request parameters, request attributes, session management, cookies, URL-rewriting, and so on. This chapter explains the relation between JSP and servlets, introduces the JSP technology, and presents many examples that you can run easily.

Note

If you are not familiar with servlet technology, read this chapter only after reading

Chapters

1 to

7 , which focus specifically on creating and working with servlets.

What's Wrong with Servlets?

The history of web server-side programming in Java started with servlets. Sun introduced servlets in 1996 as small Java-based applications for adding dynamic content to web applications. Not much later, with the increasing popularity of Java, servlets took off to become one of the most popular technologies for Internet development today.

Servlet programmers know how cumbersome it is to program with servlets, however, especially when you have to send a long HTML page that includes little code. Take the snippet in

Listing 8.1

as an example. The code is a fragment from a servlet-based application that displays all parameter names and values in an HTTP request.

Listing 8.1 Displays All Parameter/Value Pairs in a Request Using a Servlet

import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; public class MyDearServlet extends HttpServlet {

//Process the HTTP GET request

public void doGet(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

doPost(request, response);

}

200

//Process the HTTP POST request

public void doPost(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("<HTML>");

out.println("<HEAD><TITLE>Using Servlets</TITLE></HEAD>");

out.println("<BODY BGCOLOR=#123123>");

//Get parameter names

Enumeration parameters = request.getParameterNames();

String param = null;

while (parameters.hasMoreElements()) {

param = (String) parameters.nextElement();

out.println(param + ":" + request.getParameter(param) +

"<BR>");

}

out.println("</BODY>");

out.println("</HTML>");

out.close();

} //End of doPost method

/* other parts of the class goes here

.

.

.

*/

} //End of class

Nearly half of the content sent from the doPost method is static HTML. However, each HTML tag must be embedded in a String and sent using the println method of the PrintWriter object. It is a tedious chore. Worse still, the HTML page may be much longer.

Another disadvantage of using servlets is that every single change will require the intervention of the servlet programmer. Even a slight graphical modification, such as changing the value of the

<BODY> tag's BGCOLOR attribute from #DADADA to #FFFFFF, will need to be done by the programmer (who in this case will work under the supervision of the more graphic-savvy web designer).

Sun understood this problem and soon developed a solution. The result was JSP technology.

According to Sun's web site, "JSP technology is an extension of the servlet technology created to support authoring of HTML and XML pages." Combining fixed or static template data with dynamic content is easier with JSP. Even if you're comfortable writing servlets, you will find in this chapter several compelling reasons to investigate JSP technology as a complement to your existing work.

What needs to be highlighted is that "JSP technology is an extension of the servlet technology."

This means that JSP did not replace servlets as the technology for writing server-side

Internet/intranet applications. In fact, JSP was built on the servlet foundation and needs the servlet technology to work.

JSP solves drawbacks in the servlet technology by allowing the programmer to intersperse code with static content, for example. If the programmer has to work with an HTML page template written by a web designer, the programmer can simply add code into the HTML page and save it

201

as a .jsp file. If at a later stage the web designer needs to change the HTML body background color, he or she can do it without wasting the charging-by-the-hour programmer's time. He or she can just open the .jsp file and edit it accordingly.

The code in

Listing 8.1

can be rewritten in JSP as shown

Listing 8.2

.

Listing 8.2 Displays All Parameter/Value Pairs in a Request Using JSP

<%@ page import="java.util.Enumeration" %>

<HTML>

<HEAD><TITLE>Using JSP</TITLE></HEAD>

<BODY BGCOLOR=#DADADA>

<%

//Get parameter names

Enumeration parameters = request.getParameterNames();

String param = null;

while (parameters.hasMoreElements()) {

param = (String) parameters.nextElement();

out.println(param + ":" + request.getParameter(param) +

"<BR>");

}

out.close();

%>

</BODY>

</HTML>

You can see that <HTML> tags stay as they are. When you need to add dynamic content, all you need to do is enclose your code in <% … %> tags.

Again, JSP is not a replacement for servlets. Rather, JSP technology and servlets together provide an attractive solution to web scripting/programming by offering platform independence, enhanced performance, separation of logic from display, ease of administration, extensibility into the enterprise, and most importantly, ease of use.

Running Your First JSP

This section invites you to write a simple JSP page and run it. The emphasis here is not on the architecture or syntax and semantics of a JSP page; instead the section demonstrates how to configure minimally the servlet/JSP container to run JSP. Tomcat 4 is used to run JSP applications.

If you have installed and configured Tomcat 4 for your servlet applications, there is no more to do.

If you haven't, see

Appendix A , "Tomcat Installation and Configuration."

Note

In the JSP context, Tomcat is often referred to as a "JSP container." Because Tomcat also is used to run servlets, however, it is more common to call it a servlet/JSP container.

After reading this section, you will understand how much JSP simplifies things for servlets. To make your JSP page run, all you need to do is configure your JSP container (Tomcat) and write a

JSP page. Configuration is only done once, at the beginning. No compilation is necessary.

Configuring Tomcat to Run a JSP Application

202

The first thing you need to do before you can run your JSP application is configure Tomcat so that it recognizes your JSP application. To configure Tomcat to run a particular JSP application, follow these steps:

1. Create a directory under %CATALINA_HOME%/webapps called myJSPApp. The directory structure is shown in

Figure 8.1

.

Figure 8.1. The JSP application directory structure for the myJSPApp application.

2. Add a subdirectory named WEB-INF under the myJSPApp directory.

3. Edit server.xml, the server configuration file, so Tomcat knows about this new JSP application. The server.xml file is located in the conf directory under

%CATALINA_HOME%. Open the file with your text editor and look for code similar to the following:

<Context path="/examples" docBase="examples" debug="0"

reloadable="true">

.

.

.

</Context>

Right after the closing tag </Context>, add the following code:

<Context path="/myJSPApp" docBase="myJSPApp" debug="0" reloadable="true">

</Context>

203

Now you can write your JSP file and store it under the myJSPApp file. Alternatively, to make it more organized, you can create a subdirectory called jsp under myJSPApp and store your JSP files there. If you do this, you don't need to change the setting in the server.xml file.

Writing a JSP File

A JSP page consists of interwoven HTML tags and Java code. The HTML tags represent the presentation part and the code produces the contents. In its most basic form, a JSP page can include only the HTML part, like the code shown in

Listing 8.3

.

Listing 8.3 The Simplest JSP Page

<HTML>

<HEAD>

</HEAD>

<BODY>

JSP is easy.

</BODY>

</HTML>

Save this file as SimplePage.jsp in the myJSPApp directory. Your directory structure should resemble

Figure 8.1

.

Now, start your web browser, and type the following URL: http://localhost:8080/myJSPApp/SimplePage.jsp

The browser is shown in Figure 8.2

.

Figure 8.2. Your first JSP page.

204

Other Examples

Of course, the code in

Listing 8.3

is not a really useful page, but it illustrates the point that a JSP page does not need to have code at all. If your page is purely static, like the one in Listing 8.3

, you

shouldn't put it in a JSP file because JSP files are slower to process than HTML files. You might want to use a JSP file for pure HTML tags, however, if you think the code might include Java code in the future. This saves you the trouble of changing all the links to this page at the later stage.

To write Java code in your JSP file, you embed the code in <% … %> tags. For example, the code in

Listing 8.4

is an example of intertwining Java code and HTML in a JSP file.

Listing 8.4 Interweaving HTML and Code

<HTML>

<HEAD>

</HEAD>

<BODY>

<%

out.println("JSP is easy");

%>

</BODY>

</HTML>

The code in Listing 8.4

produces the same output as the one in Listing 8.3

. Notice, however, the use of the Java code to send the text. If you don't understand what out.println does, bear with me for a moment—it is discussed in detail in the next section. For now, knowing that out.println is used to send a String to the web browser is sufficient.

Notice also that the output of a JSP page is plain text consisting of HTML tags. No code section of the page will be sent to the browser.

Another example is given in

Listing 8.5

. This snippet displays the string "Welcome. The server

time is now" followed by the server time.

Listing 8.5 Displaying the Server Time

<HTML>

<HEAD>

<TITLE>Displaying the server time</TITLE>

</HEAD>

<BODY>

Welcome. The server time is now

<%

java.util.Calendar now = java.util.Calendar.getInstance();

int hour = now.get(java.util.Calendar.HOUR_OF_DAY);

int minute = now.get(java.util.Calendar.MINUTE);

if (hour<10)

out.println("0" + hour);

else

out.println(hour);

out.println(":");

if (minute<10)

out.println("0" + minute);

205

else

out.println(minute);

%>

</BODY>

</HTML>

The code in Listing 8.5

displays the time in the hh:mm format. Therefore, if the hour is less than

10, a "0" precedes, which means that nine will be displayed as 09 instead of 9.

How JSP Works

Inside the JSP container is a special servlet called the page compiler. The servlet container is configured to forward to this page compiler all HTTP requests with URLs that match the .jsp file extension. This page compiler turns a servlet container into a JSP container. When a .jsp page is first called, the page compiler parses and compiles the .jsp page into a servlet class. If the compilation is successful, the jsp servlet class is loaded into memory. On subsequent calls, the servlet class for that .jsp page is already in memory; however, it could have been updated.

Therefore, the page compiler servlet will always compare the timestamp of the jsp servlet with the jsp page. If the .jsp page is more current, recompilation is necessary. With this process, once deployed, JSP pages only go through the time-consuming compilation process once.

You may be thinking that after the deployment, the first user requests for a .jsp page will experience unusually slow response due to the time spent for compiling the .jsp file into a jsp servlet. To avoid this unpleasant situation, a mechanism in JSP allows the .jsp pages to be precompiled before any user request for them is received. Alternatively, you deploy your JSP application as a web archive file in the form of a compiled servlet. This technique is discussed in

Chapter 16 , "Application Deployment."

The JSP Servlet Generated Code

When the JSP is invoked, Tomcat creates two files in the

C:\%CATALINA_HOME%\work\localhost\examples\jsp directory. Those two files are

SimplePage_ jsp.java and SimplePage_ jsp.class. When you open the SimplePage_ jsp.java file, you will see the following: package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import org.apache.jasper.runtime.*; public class SimplePage_jsp extends HttpJspBase {

static {

}

public SimplePage_jsp() {

}

206

private static boolean _jspx_inited = false;

public final void _jspx_init() throws org.apache.jasper.JasperException {

}

public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;

PageContext pageContext = null;

HttpSession session = null;

ServletContext application = null;

ServletConfig config = null;

JspWriter out = null;

Object page = this;

String _value = null;

try {

if (_jspx_inited == false) {

synchronized (this) {

if (_jspx_inited == false) {

_jspx_init();

_jspx_inited = true;

}

}

}

_jspxFactory = JspFactory.getDefaultFactory();

response.setContentType("text/html;charset=ISO-8859-1");

pageContext = jspxFactory.getPageContext(this,

request, response, "", true, 8192, true);

application = pageContext.getServletContext();

config = pageContext.getServletConfig();

session = pageContext.getSession();

out = pageContext.getOut();

// begin

[file="C:\\tomcat4\\bin\\..\\webapps\\examples\\jsp\\SimplePage.jsp"; from=(0, 2);to=(2,0)]

out.println("JSP is easy");

// end

// HTML // begin

[file="C:\\tomcat4\\bin\\..\\webapps\\examples\\jsp\\SimplePage.jsp"; from=(2, 2);to=(3,0)]

out.write("\r\n");

// end

}

catch (Throwable t) {

if (out != null && out.getBufferSize() != 0)

out.clearBuffer();

if (pageContext != null)

pageContext.handlePageException(t);

}

finally {

if (_jspxFactory != null)

_jspxFactory.releasePageContext(pageContext);

}

}

}

207

For now, I will defer a full explanation of the preceding code until you learn more about how the interfaces and classes are used to run a JSP page. You can read the section, "

The Generated

Servlet Revisited ," later in this chapter, to learn more about the code listed here.

The JSP API

The JSP technology is based on the JSP API that consists of two packages: javax.servlet.jsp and javax.servlet.jsp.tagext. Both packages are given in detail in

Appendix D , "The javax.servlet.jsp

Package Reference," and

Appendix E , "The javax.servlet.jsp.tagext Package Reference." This

chapter will discuss the classes and interfaces of the javax.servlet.jsp package and javax.servlet.jsp.tagext will be discussed in

Chapter 11 , "Using JSP Custom Tags."

In addition to these two packages, JSP also needs the two servlet packages—javax.servlet and javax.servlet.http. When you study the javax.servlet.jsp package, you will know why we say that

JSP is an extension of servlet technology and understand why it is important that a JSP application programmer understands the servlet technology well.

The javax.servlet.jsp package has two interfaces and four classes. The interfaces are as follows:

JspPage

HttpJspPage

The four classes are as follows:

JspEngineInfo

JspFactory

JspWriter

PageContext

TE

AM

In addition, there are also two exception classes: JspException and JspError.

The JspPage Interface

FL

Y

The JspPage is the interface that must be implemented by all JSP servlet classes. This may remind you of the javax.servlet.Servlet interface in

Chapter 1 , "The Servlet Technology," of course. And,

not surprisingly, the JspPage interface does extend the javax.servlet.Servlet interface.

The JSPPage interface has two methods, JspInit and JspDestroy, whose signatures are as follows: public void jspInit() public void jspDestroy() jspInit, which is similar to the init method in the javax.servlet.Servlet interface, is called when the

JspPage object is created and can be used to run some initialization. This method is called only once during the life cycle of the JSP page: the first time the JSP page is invoked.

The jspDestroy method is analogous with the destroy method of the javax.servlet.Servlet interface.

This method is called before the JSP servlet object is destroyed. You can use this method to do some clean-up, if you want.

Most of the time, however, JSP authors rarely make full use of these two methods. The following example illustrates how you can implement these two methods in your JSP page:

Team-Fly ®

<%!

public void jspInit() {

System.out.println("Init");

}

public void jspDestroy() {

System.out.println("Destroy");

}

%>

<%

out.println("JSP is easy");

%>

Notice that the first line of the code starts with <%!. You will find the explanation of this construct

in the Chapter 9 , "JSP Syntax."

The HttpJspPage Interface

This interface directly extends the JspPage interface. There is only one method: _ jspService. This method is called by the JSP container to generate the content of the JSP page. The _ jspService has the following signature: public void _jspService(HttpServletRequest request,

HttpServletResponse response) throws ServletException, IOException.

You can't include this method in a JSP page, such as in the following code:

<%!

public void jspInit() {

System.out.println("Init");

}

public void jspDestroy() {

System.out.println("Destroy");

}

public void _jspService(HttpServletRequest request,

HttpServletResponse response) throws ServletException,

IOException {

System.out.println("Service");

}

%>

This is because the page content itself represents this method. See the section " The Generated

Servlet Revisited ."

The JspFactory Class

The JspFactory class is an abstract class that provides methods for obtaining other objects needed for the JSP page processing. The class has the static method getDefaultFactory that returns a

JspFactory object. From the JspFactory object, a PageContext and a JspEngineInfo object can be obtained that are useful for the JSP page processing. These objects are obtained using the

JspFactory class's getEngineInfo method and the getPageContext method, whose signatures are given here: public abstract JspEngineInfo getEngineInfo() public abstract PageContext getPageContext (

Servlet requestingServlet, ServletRequest request,

ServletResponse response, String errorPageURL, boolean needsSession, int buffer, boolean autoFlush)

209

The following code is part of the _ jspService method that is generated by the JSP container:

JspFactory _jspxFactory = null;

PageContext pageContext = null; jspxFactory = JspFactory.getDefaultFactory();

.

.

. pageContext = _jspxFactory.getPageContext(this, request,

response, "", true, 8192, true);

The JspEngineInfo Class

The JspEngineInfo class is an abstract class that provides information on the JSP container. Only one method, getSpecificationVersion, returns the JSP container's version number. Because this is the only method currently available, this class does not have much use.

You can obtain a JspEngineInfo object using the getEngineInfo method of the JspFactory class.

The PageContext Class

PageContext represents a class that provides methods that are implementation-dependent. The

PageContext class itself is abstract, so in the _ jspService method of a JSP servlet class, a

PageContext object is obtained by calling the getPageContext method of the JspFactory class.

The PageContext class provides methods that are used to create other objects. For example, its getOut method returns a JspWriter object that is used to send strings to the web browser. Other methods that return servlet-related objects include the following:

• getRequest, returns a ServletRequest object getResponse, returns a ServletResponse object getServletConfig, returns a ServletConfig object getServletContext, returns a ServletContext object getSession, returns an HttpSession object

The JspWriter Class

The JspWriter class is derived from the java.io.Writer class and represents a Writer that you can use to write to the client browser. Of its many methods, the most important are the print and println methods. Both provide enough overloads that ensure you can write any type of data. The difference between print and println is that println always adds the new line character to the printed data.

Additional methods allow you to manipulate the buffer. For instance, the clear method clears the buffer. It throws an exception if some of the buffer's content has already been flushed. Similar to clear is the clearBuffer method, which clears the buffer but never throws any exception if any of the buffer's contents have been flushed.

The Generated Servlet Revisited

Now that you understand the various interfaces and classes in the javax.servlet.jsp package, analyzing the generated JSP servlet will make more sense.

210

When you study the generated code, the first thing you'll see is the following: public class SimplePage_jsp extends HttpJspBase {

The discussion should start with the questions, "What is HttpJspBase?"and "Why doesn't the JSP servlet class implement the javax.servlet.jsp.JspPage or javax.servlet.jsp.HttpJspPage interface?"

First, remember that the JSP specification defines only standards for writing JSP pages. A JSP page itself will be translated into a java file, which in turn will be compiled into a servlet class.

The two processes are implementation dependent and do not affect the way a JSP page author codes. Therefore, a JSP container has the freedom and flexibility to do the page translation in its own way. The JSP servlet-generated code presented in this chapter is taken from Tomcat. You can therefore expect a different Java file to be generated by other JSP containers.

In Tomcat, HttpJspBase is a class whose source can be found under the src\jasper\src\share\org\apache\jasper\runtime directory under the %CATALINA_HOME% directory.

Most importantly, the signature of this class is as follows: public abstract class HttpJspBase extends HttpServlet

implements HttpJspPage

Now you can see that HttpJspBase is an HttpServlet and it does implement the javax.servlet.jsp.HttpJspPage interface. The HttpJspBase is more like a wrapper class so that its derived class does not have to provide implementation for the interface's methods if the JSP page author does not override them. The complete listing of the class follows:

/*

* The Apache Software License, Version 1.1

*

* Copyright (c) 1999 The Apache Software Foundation. All rights

* reserved.

*

* Redistribution and use in source and binary forms, with or without

* modification, are permitted provided that the following conditions

* are met:

*

* 1. Redistributions of source code must retain the above copyright

* notice, this list of conditions and the following disclaimer.

*

* 2. Redistributions in binary form must reproduce the above copyright

* notice, this list of conditions and the following disclaimer in

* the documentation and/or other materials provided with the

* distribution.

*

* 3. The end-user documentation included with the redistribution, if

* any, must include the following acknowlegement:

* "This product includes software developed by the

* Apache Software Foundation (http://www.apache.org/)."

* Alternately, this acknowlegement may appear in the software itself,

* if and wherever such third-party acknowlegements normally appear.

*

* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software

211

* Foundation" must not be used to endorse or promote products derived

* from this software without prior written permission. For written

* permission, please contact [email protected]

*

* 5. Products derived from this software may not be called "Apache"

* nor may "Apache" appear in their names without prior written

* permission of the Apache Group.

*

* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED

* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES

* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE

* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR

* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,

* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT

* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF

* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED

AND

* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,

* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT

* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF

* SUCH DAMAGE.

* == == == == == == == == == == == == == == == == == == == == == ==

== == == == == == == == == == == ==

*

* This software consists of voluntary contributions made by many

* individuals on behalf of the Apache Software Foundation. For more

* information on the Apache Software Foundation, please see

* <http://www.apache.org/>.

*

*/

package org.apache.jasper.runtime; import java.io.IOException; import java.io.FileInputStream; import java.io.InputStreamReader; import java.net.URL; import java.net.MalformedURLException; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import org.apache.jasper.JasperException; import org.apache.jasper.Constants;

/**

* This is the subclass of all JSP-generated servlets.

*

* @author Anil K. Vijendran

*/ public abstract class HttpJspBase extends HttpServlet

implements HttpJspPage {

protected PageContext pageContext;

protected HttpJspBase() {

}

public final void init(ServletConfig config)

throws ServletException {

212

super.init(config);

jspInit();

}

public String getServletInfo() {

return Constants.getString ("jsp.engine.info");

}

public final void destroy() {

jspDestroy();

}

/**

* Entry point into service.

*/

public final void service(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException {

_jspService(request, response);

}

public void jspInit() {

}

public void jspDestroy() {

}

public abstract void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException;

}

Back to the generated JSP servlet class, remember that the JSP page source code is simply the following three lines of code:

<%

out.println("JSP is easy");

%>

There are no jspInit and jspDestroy methods in the source code, so there are no implementations for these two methods in the resulting servlet code. The three lines of code, however, translate into the _ jspService method. For reading convenience, the method is reprinted here. Notice that, for clarity, the comments have been removed. public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;

PageContext pageContext = null;

HttpSession session = null;

ServletContext application = null;

ServletConfig config = null;

JspWriter out = null;

Object page = this;

String _value = null;

try {

if (_jspx_inited == false) {

synchronized (this) {

if (_jspx_inited == false) {

_jspx_init();

213

_jspx_inited = true;

}

}

}

_jspxFactory = JspFactory.getDefaultFactory();

response.setContentType("text/html;charset=ISO-8859-1");

pageContext = jspxFactory.getPageContext(this,

request, response, "", true, 8192, true);

application = pageContext.getServletContext();

config = pageContext.getServletConfig();

session = pageContext.getSession();

out = pageContext.getOut();

out.println("JSP is easy");

out.write("\r\n");

}

catch (Throwable t) {

if (out != null && out.getBufferSize() != 0)

out.clearBuffer();

if (pageContext != null)

pageContext.handlePageException(t);

}

finally {

if (_jspxFactory != null)

_jspxFactory.releasePageContext(pageContext);

}

}

Implicit Objects

Having examined the generated JSP servlet source code, you know that the code contains several object declarations in its _ jspService method. Recall this part from the code in the preceding section: public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;

PageContext pageContext = null;

HttpSession session = null;

ServletContext application = null;

ServletConfig config = null;

JspWriter out = null;

Object page = this;

String _value = null;

try {

.

.

.

_jspxFactory = JspFactory.getDefaultFactory();

response.setContentType("text/html;charset=ISO-8859-1");

pageContext = jspxFactory.getPageContext(this,

request, response, "", true, 8192, true);

application = pageContext.getServletContext();

config = pageContext.getServletConfig();

session = pageContext.getSession();

214

out = pageContext.getOut();

.

.

.

}

You see that there are object references, such as pageContext, session, application, config, out, and so on. These object references are created whether they are used from inside the page. They are automatically available for the JSP page author to use! These objects are called implicit objects

and are summarized in the Table 8.1

.

Table 8.1. JSP Implicit Objects

Object Type

request javax.servlet.http.HttpServletRequest response javax.servlet.http.HttpServletResponse out javax.servlet.jsp.JspWriter session javax.servlet.http.HttpSession application javax.servlet.ServletContext config javax.servlet.ServletConfig pageContext javax.servlet.jsp.PageContext page javax.servlet.jsp.HttpJspPage exception java.lang.Throwable

By looking at Table 8.1

, you now know why you can send a String of text by simply writing:

<%

out.println("JSP is easy.");

%>

In the case of the code above, you use the implicit object out that represents a javax.servlet.jsp.JspWriter. All the implicit objects are discussed briefly in the following subsections.

request and response Implicit Objects

In servlets, both objects are passed in by the servlet container to the service method of the javax.servlet.http.HttpServlet class. Remember its signature? protected void service(HttpServletRequest request,

HttpServletResponse response)

throws ServletException, IOException

Note

If you want to review servlets, you can go back to Chapters

1 , "The Servlet Technology,"

and

Chapter 2 ," Inside Servlets," for more details.

In a servlet, before you send any output, you are required to call the setContentType of the

HttpServletResponse to tell the browser the type of the content, as in the following code: response.setContentType("text/html");

In JSP, this is done automatically for you in the generated JSP servlet class, as follows:

215

response.setContentType("text/html;charset=ISO-8859-1");

Having an HttpServletRequest and an HttpServletResponse, you can do anything you like as you would in a servlet. For example, the following JSP page retrieves the value of a parameter called firstName and displays it in the browser:

<HTML>

<HEAD>

<TITLE>Simple Page</TITLE>

</HEAD>

<BODY>

<%

String firstName = request.getParameter("firstName");

out.println("First name: " + firstName);

%>

</BODY>

</HTML>

The following example uses the sendRedirect method of the javax.servlet.http.HttpServletResponse to redirect the user to a different URL:

<%

response.sendRedirect("http://www.newriders.com");

%>

out Implicit Object

out is probably the most frequently used implicit object. You call either its print method or its println method to send text or other data to the client browser. In a servlet, you always need to call the getWriter method of the javax.servlet.http.HttpServletResponse interface to obtain a

PrintWriter before you can output anything to the browser, as follows:

PrintWriter out = response.getWriter();

In JSP, you don't need to do this because you already have an out that represents a javax.servlet.jsp.JspWriter object.

session Implicit Object

The session implicit object represents the HttpSession object that you can retrieve in a servlet by calling the getSession method of the javax.servlet.http.HttpServletRequest interface, as in the following code: request.getSession();

The following code is a JSP page that uses a session object to implement a counter:

<HTML>

<HEAD>

<TITLE>Counter</TITLE>

</HEAD>

<BODY>

<%

String counterAttribute = (String) session.getAttribute("counter");

int count = 0;

try {

216

count = Integer.parseInt(counterAttribute);

}

catch (Exception e) {

}

count++;

session.setAttribute("counter", Integer.toString(count));

out.println("This is the " + count + "th time you visited this page in this session.");

%>

</BODY>

</HTML>

See how session is readily available without efforts from the programmer's side?

Warning

Note that the session object is available only in a JSP page that participates in the session management. To decide whether or not your JSP page should participate in the session management, see the discussion of the session management as discussed in

Chapter 5 ,

"Session Management."

application

The application implicit object represents the javax.servlet.ServletContext object. In an

HttpServlet, you can retrieve the ServletContext method by using the getServletContext method.

config

The config implicit object represents a javax.servlet.ServletConfig object that in a servlet can be retrieved by using the getServletConfig method.

pageContext

The pageContext implicit object represents the javax.servlet.jsp.PageContext object discussed in the section, "

The PageContext Class ."

page

The page implicit object represents the javax.servlet.jsp.HttpJspPage interface explained in the section, "

The HttpJspPage Interface ."

exception

The exception object is available only on pages that have been defined as error pages.

Summary

This chapter is the introduction to the JSP technology. You may be able to author a JSP page without understanding the underlying API. However, mastering the classes and interfaces in the javax.servlet.jsp package and understanding how JSP extends the servlet technology provides you with the knowledge to write more powerful and efficient code.

217

Chapter 9. JSP Syntax

In

Chapter 8 , "JSP Basics," you learned that a JSP page can have Java code and HTML tags. More

formally, you can say that a JSP page has elements and template data. The elements, which also are called JSP tags, make up the syntax and semantics of JSP. Template data is everything else.

Template data includes parts that the JSP container does not understand, such as HTML tags.

There are three types of elements:

Directive elements

Scripting elements

Action elements

To write an effective JSP page, you need to understand all these elements well. Elements have two forms: the XML form and the <% … %> alternative form. The conversion between the XML form and the alternative form is presented at the end of the chapter in the section, "

Converting into

XML Syntax ."Template data remains as it is, normally passed through the client uninterpreted.

This chapter discusses the three types of JSP elements and comments. It also presents examples on how to use these elements. You will also learn how incorporating these elements affects the JSP servlets—servlets that result from the translation of JSP pages.

FL

Y

Directives

must translate a JSP page into a corresponding servlet. Directives have the following syntax:

TE

The asterisk (*) means that what is enclosed in the brackets can be repeated zero or more times.

The syntax can be re-written in a more informal way as follows:

<%@ directive attribute1="value1" attribute2="value2" ... %>

White spaces after the opening <%@ and before the closing %> are optional, but are recommended to enhance readability.

Warning

Note that an attribute value must be quoted.

Warning the three types of directives are as follows:

Page directives

Include directives

Tag library directives

The first two directives are discussed in detail in this chapter. Discussion on the tag library

directive is deferred until Chapter 11 , "Using JSP Custom Tags."

Team-Fly ®

The Page Directive

The Page directive has the following syntax:

<%@ page (attribute="value")* %>

Or, if you want to use the more informal syntax:

<%@ page attribute1="value1" attribute2="value2" ... %>

The Page directive supports 11 attributes. These attributes are summarized in Table 9.1

.

Attribute

language info String

Table 9.1. The Page Directive's Attributes

Value Type

Scripting language name "java"

Default Value

Depends on the JSP container contentType MIME type, character set import

"text/html;charset=ISO-8859-1"

None

Fully qualified class name or package name None buffer Buffer size or false autoFlush Boolean session Boolean isThreadSafe Boolean errorPage URL isErrorPage Boolean

8192

"true"

"true"

"true"

None

"false"

An example of the use of the Page directive is as follows:

<%@ page buffer="16384" session="false" %>

With JSP, you can specify multiple page directives in your JSP page, such as the following:

<%@ page buffer="16384" %>

<%@ page session="false" %>

Except for the import attribute, however, JSP does not allow you to repeat the same attribute within a page directive or in multiple directives on the same page.

The following is illegal because the info attribute appears more than once in a single page:

<%@ page info="Example Page" %>

<%@ page buffer="16384" %>

<%@ page info="Unrestricted Access" %>

The following also is illegal because the buffer attribute appears more than once in the same page directive:

<%@ page buffer="16384" info="Example Page" buffer="8192" %>

The following is legal, however, because the import attribute can appear multiple times:

<%@ page import="java.io.*" info="Example Page" %>

219

<%@ page import="java.util.Enumeration" %>

<%@ page import="com.brainysoftware.web.FileUpload" %>

Alternatively, imported libraries can appear in a single import attribute, separated by commas, as shown in the following code:

<%@ page import="java.io.*, java.util.Enumeration" %>

The following section discusses each attribute in more detail and examines the effect on the generated servlet.

The language Attribute

The language attribute specifies the scripting language used in the JSP page. By default, the value is "java" and all JSP containers must support Java as the scripting language. With Tomcat, this is the only accepted language. Other JSP containers might accept different languages, however.

Specifying this attribute, as in the following code, does not have any effect on the generated servlet:

<%@ page language="java" %>

<%

out.println("JSP is easy");

%>

In fact, this attribute is useful only in a JSP container that supports a language other than Java as the scripting language.

The info Attribute

The info attribute allows you to insert any string that later can be retrieved using the getServletInfo method. For example, you can add the following page directive with an info attribute:

<%@ page info="Written by Bulbul" %>

The JSP container then will create a public method getServletInfo in the resulting servlet. This method returns the value of the info attribute specified in the page. For the previous page directive, the getServletInfo method will be written as follows: public String getServletInfo() {

return "Written by Bulbul";

}

In the same JSP page, you can retrieve the info attribute's value by calling the getServletInfo method. For instance, the following JSP page will return "Written by Bulbul" on the client browser.

<%@ page info="Written by Bulbul" %>

<%

out.println(getServletInfo());

%>

The default value for this attribute depends on the JSP container.

The contentType Attribute

220

The contentType attribute defines the Multipurpose Internet Mail Extension (MIME) type of the

HTTP response sent to the client. The default value is "text/html;charset=ISO-8859-1" and this is reflected in _jspService method in the generated servlet. For example, this is the cleaned up version of the servlet that is generated from a JSP page that does not specify the contentType attribute in its page directive; that is, the default value is used: public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws java.io.IOException, ServletException {

.

.

.

try {

.

.

.

_jspxFactory = JspFactory.getDefaultFactory();

response.setContentType("text/html;charset=ISO-8859-1");

.

.

.

}

catch (Throwable t) {

.

.

.

}

finally {

.

.

.

}

}

You will want to use this attribute when working with pages that need to send characters in other encoding schemes. For example, the following directive tells the JSP container that the output should be sent using simplified Chinese characters:

<%@ page contentType="text/html;charset=GB2312" %>

The extends Attribute

The extends attribute defines the parent class that will be inherited by the generated servlet. You should use this attribute with extra care. In most cases, you should not use this attribute at all. In

Tomcat, the parent class that will be subclassed by the resulting servlet is HttpJspBase.

The import Attribute

The import attribute is similar to the import keyword in a Java class or interface. The attribute is used to import a class or an interface or all members of a package. You will definitely use this attribute often. Whatever you specify in the import attribute of a page directive will be translated into an import statement in the generated servlet class. By default, Tomcat specifies the following import statements in every generated servlet class. You don't need to import what has been imported by default: import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*;

221

import javax.servlet.jsp.tagext.*; import org.apache.jasper.runtime.*;

As an example, consider the following JSP page that imports the java.io package and the java.util.Enumeration interface:

<%@ page import="java.io.*" %>

<%@ page import="java.util.Enumeration" %>

The two will be added before the default import statements in the generated servlet class, as described in the following code fragment: import java.io.*; import java.util.Enumeration; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import org.apache.jasper.runtime.*;

The buffer Attribute

By default, a JSP page's content is buffered to increase performance. The default size of the buffer is 8Kb or 8192 characters.

Consider an example that specifies the buffer attribute with a size of 16Kb:

<%@ page buffer="16kb" %>

This attribute is reflected in the _jspService method in the generated servlet class, as in the following cleaned up code. The buffer size is passed to the getPageContext method of the javax.servlet.jsp.JspFactory class when creating a PageContext object. public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws java.io.IOException, ServletException {

.

.

.

try {

.

.

.

_jspxFactory = JspFactory.getDefaultFactory();

response.setContentType("text/html;charset=ISO-8859-1");

// 8192 in the following line represents the buffer size

pageContext = jspxFactory.getPageContext(this, request,

response, "", true, 16384, true);

.

.

.

}

catch (Throwable t) {

.

.

.

}

222

finally {

.

.

.

}

}

With the buffer attribute in a page directive, you can do two things:

Eliminate the buffer by specifying the value "none", as in the following code:

<%@ page buffer="none" %>

If you decide not to use a buffer, the getPageContext method will be invoked passing 0 as the buffer size, as in the following code: pageContext = _jspxFactory.getPageContext( this, request, response, "", true, 0, true);

Change the size of the buffer by assigning a number to the attribute. The attribute value represents the number in kilobytes. Therefore, "16" means 16Kb alias 16384 characters.

You can either write the number only, or the number plus "Kb". For example, "16" is the same as "16Kb".

The following example shows two page directives in two different JSP pages. The first cancels the use of the buffer, and the second changes the size of the buffer to 12Kb.

<%@ page import="java.io.*" buffer="none" %>

<%@ page import="java.io.*" buffer="12" %>

Warning

Note that the JSP container has the discretion to use a buffer size larger than specified to improve performance.

The autoFlush Attribute

The autoFlush attribute is related to the page buffer. When the value is "true", the JSP container will automatically flush the buffer when the buffer is full. If the value is "false", however, the JSP author needs to flush the buffer manually using the flush method of the JspWriter object, such as the following: out.flush();

For example, the following code specifies a false value for the autoFlush attribute:

<%@ page autoFlush="false" %>

The session Attribute

By default, a JSP page participates in the JSP container's session management. This is indicated by the declaration of a javax.servlet.http.HttpSession object reference and the creation of it through the getSession method of the javax.servlet.jsp.PageContext, as illustrated by the following code: public void _jspService(HttpServletRequest request,

223

HttpServletResponse response)

throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;

PageContext pageContext = null;

// declare an HttpSession object reference

HttpSession session = null;

try {

.

.

.

jspxFactory = JspFactory.getDefaultFactory();

response.setContentType("text/html;charset=ISO-8859-1");

pageContext = _jspxFactory.getPageContext(

this, request, response, "", true, 0, true);

application = pageContext.getServletContext();

config = pageContext.getServletConfig();

// create a HttpSession object

session = pageContext.getSession();

.

.

.

}

catch (Throwable t) {

.

.

.

}

finally {

.

.

.

}

}

Whether your JSP page participates in the session management is determined by the value of the session attribute in a page directive. By default this value is true; that is, the JSP page is part of the session management. I want to make an important point, however: You should not let your JSP

page participate in the session management unnecessarily because this consumes resources.

Because of this, you should always use the session attribute and assign it the value of "false" unless you are specifically needing session management.

When the value of this attribute is "false", no javax.servlet.http.HttpSession object reference is declared and no HttpSession object is created. As a result, the session implicit object is not available in the JSP page.

The following shows an example of the use of the session attribute:

<%@ page session="false" %>

The isThreadSafe Attribute

As discussed in Chapter 2 , "Inside Servlets," you can make a servlet thread-safe by inheriting the

javax.servlet.SingleThreadModel. You can control this behavior in the JSP page by using the isThreadSafe attribute, which by default has the value of "true". When the value of this attribute is true, you guarantee that simultaneous access to this page is safe. However, you can assign "false" to this attribute as in the following code:

224

<%@ page isThreadSafe="false" %>

By setting the isThreadSafe attribute to false, you are telling the JSP translator that you (the programmer of this page) cannot guarantee that simultaneous accesses to this page will be safe.

Therefore, you are asking the JSP translator to make this page thread-safe. This will make the generated servlet implement the javax.servlet.SingleThreadModel interface, as in the following signature of the JSP servlet class: public class SimplePage_jsp extends HttpJspBase

implements SingleThreadModel

In other words, when the value of this attribute is false, the JSP container will serialize multiple requests for this page; that is, the JSP container will wait until the JSP servlet finishes responding to a request before passing another request to it.

The errorPage Attribute

The errorPage attribute specifies the URL of an error page that will be displayed if an uncaught exception occurs in this current JSP page. Referring to the URL of the error page is sometimes tricky. The easiest solution is to store the error page in the same directory as the current JSP page.

In this case, you need only to mention the name of the error page, as in the following example:

<%@ page errorPage="ErrorPage.jsp" %>

<%

String name = request.getParameter("otherName");

// this will throw an exception because the parameter "otherName"

// does not exist, so name will be null.

// this will cause the ErrorPage.jsp to be displayed

name.substring(1, 1);

%>

When the page is called, the error page is displayed. An error page must specify the isErrorPage attribute in its page directive and the value of this attribute must be "true".

The following is an errorPage attribute that is assigned an error page in a URL:

<%@ page errorPage="/myJspApp/ErrorPage.jsp" %>

The isErrorPage Attribute

The isErrorPage attribute can accept the value of "true" or "false", and the default value is "false".

It indicates whether the current JSP page is an error page; that is, the page that will be displayed when an uncaught exception occurs in the other JSP page. If the current page is an error page, it has access to the exception implicit object, as explained in

Chapter 8 .

The include Directive

The include directive is the second type of the JSP directive elements. This directive enables JSP page authors to include the contents of other files in the current JSP page.

The include directive is useful if you have a common source that will be used by more than one

JSP page. Instead of repeating the same code in every JSP page, thus creating a maintenance problem, you can place the common code in a separate file and use an include directive from each

JSP page.

225

The included page itself can be static, such as an HTML file, or dynamic, such as another JSP page. If you are including a JSP page, the included JSP page itself can include another file.

Therefore, nesting include directives is permitted in JSP.

The syntax for the include directive is as follows:

<%@ include file="relativeURL" %>

The following is an example of how to include HTML files:

<%@ include file="includes/header.html" %>

<%

out.println("<BODY>");

// other content;

%>

<%@ include file="includes/footer.html" %>

Note

If the relativeURL part begins with a forward slash character (/), it is interpreted as an absolute path on the server. If relativeURL does not start with a "/", it is interpreted as relative to the current JSP page.

Now, we'll look at how included files are translated into the JSP servlet file. The following example is a simple JSP page that includes two HTML files: Header.html and Footer.html. Both included files are located under the includes subdirectory, which itself is under the directory that

hosts the current JSP file. The JSP page is called SimplePage.jsp and is given in Listing 9.1

. The

page simply displays the current server time. The Header.html is given in

Listing 9.2

and the

Footer.html in

Listing 9.3

. What you are interested in here is the generated servlet code.

Listing 9.1 A Simple JSP Page that Includes Two Files

<%@ page session="false" %>

<%@ page import="java.util.Calendar" %>

<%@ include file="includes/Header.html" %>

<%

out.println("Current time: " + Calendar.getInstance().getTime());

%>

<%@ include file="includes/Footer.html" %>

Listing 9.2 The Header.html File

<HTML>

<HEAD>

<TITLE>Welcome</TITLE>

<BODY>

Listing 9.3 The Footer.html File

</BODY>

</HTML>

The generated servlet is as follows: package org.apache.jsp;

226

import java.util.Calendar; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import org.apache.jasper.runtime.*; public class SimplePage_jsp extends HttpJspBase {

static {

}

public SimplePage_jsp() {

}

private static boolean _jspx_inited = false;

public final void _jspx_init() throws org.apache.jasper.JasperException {

}

public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;

PageContext pageContext = null;

ServletContext application = null;

ServletConfig config = null;

JspWriter out = null;

Object page = this;

String _value = null;

try {

if (_jspx_inited == false) {

synchronized (this) {

if (_jspx_inited == false) {

_jspx_init();

jspx_inited = true;

}

}

}

_jspxFactory = JspFactory.getDefaultFactory();

response.setContentType("text/html;charset=ISO-8859-1");

pageContext = _jspxFactory.getPageContext(

this, request, response, "", false, 8192, true);

application = pageContext.getServletContext();

config = pageContext.getServletConfig();

out = pageContext.getOut();

// HTML // begin

[file="C:\\tomcat4\\bin\\..\\webapps\\myJSPApp\\SimplePage.jsp";from=

(0,27); to=(1,0)]

out.write("\r\n");

// end

// HTML // begin

[file="C:\\tomcat4\\bin\\..\\webapps\\myJSPApp\\SimplePage.jsp";from=

(1,39); to=(2,0)]

227

out.write("\r\n");

// end

// HTML

// begin

[file="C:\\tomcat4\\bin\\..\\webapps\\myJSPApp\\includes\\Header.html

";

from=(0,0);to=(4,0)] out.write("<HTML>\r\n<HEAD>\r\n<TITLE>Welcome</TITLE>\r\n<BODY>\r\n");

// end

// HTML // begin

[file="C:\\tomcat4\\bin\\..\\webapps\\myJSPApp\\SimplePage.jsp";from=

(2,42); to=(3,0)]

out.write("\r\n");

// end

// begin

[file="C:\\tomcat4\\bin\\..\\webapps\\myJSPApp\\SimplePage.jsp";from=

(3,2);to

=(5,0)]

out.println("Current time: " +

Calendar.getInstance().getTime());

// end

// HTML // begin

(5,2);to

=(6,0)]

out.write("\r\n");

// end

// HTML // begin

";

TE

AM

from=(0,0);to=(2,0)]

FL

Y

out.write("</BODY>\r\n</HTML>\r\n");

// end

// HTML

// begin

[file="C:\\tomcat4\\bin\\..\\webapps\\myJSPApp\\SimplePage.jsp";from=

(6,42); to=(7,0)]

out.write("\r\n");

// end

}

catch (Throwable t) {

if (out != null && out.getBufferSize() != 0)

out.clearBuffer();

if (pageContext != null) pageContext.handlePageException(t);

}

finally {

if (_jspxFactory != null)

_jspxFactory.releasePageContext(pageContext);

}

}

Team-Fly ®

}

The lines in bold denote the beginning of the included file. Because all the included files are placed inline before being compiled, including files does not have any performance effect on the application.

The taglib Directive

The taglib, or tag library, directive can be used to extend JSP functionality. This is a broad topic and has been given a chapter of its own. (See

Chapter 11 , "Using JSP Custom Tags," for more

information.)

Scripting Elements

Scripting elements allow you to insert Java code in your JSP pages. There are three types of scripting elements:

Scriptlets

Declarations

Expressions

The three elements are discussed in the following sections.

Scriptlets

Throughout the previous chapters and up to this point in this chapter, you have seen scriptlets in the examples. Scriptlets are the code blocks of a JSP page. Scriptlets start with an opening <% tag and end with a closing %> tag.

Note

Directives also start with <% and end with %>. However, in a directive a @ follows the

<%.

The following JSP page is an example of using scriptlets. In the JSP page, you try to connect to a database and retrieve all records from a table called Users. Among the fields in the Users table are

FirstName, LastName, UserName, and Password. Upon obtaining a ResultSet object, you display all the records in an HTML table. The JSP page is given in

Listing 9.4

.

Listing 9.4 Displaying Database Records

<%@ page session="false" %>

<%@ page import="java.sql.*" %>

<%

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

System.out.println("JDBC driver loaded");

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

229

%>

<HTML>

<HEAD>

<TITLE>Display All Users</TITLE>

</HEAD>

<BODY>

<CENTER>

<BR><H2>Displaying All Users</H2>

<BR>

<BR>

<TABLE>

<TR>

<TH>First Name</TH>

<TH>Last Name</TH>

<TH>User Name</TH>

<TH>Password</TH>

</TR>

<%

String sql = "SELECT FirstName, LastName, UserName, Password" +

" FROM Users";

try {

Connection con = DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

out.println("<TR>");

out.println("<TD>" + rs.getString(1) + "</TD>");

out.println("<TD>" + rs.getString(2) + "</TD>");

out.println("<TD>" + rs.getString(3) + "</TD>");

out.println("<TD>" + rs.getString(4) + "</TD>");

out.println("</TR>");

}

rs.close();

s.close();

con.close();

}

catch (SQLException e) {

}

catch (Exception e) {

}

%>

</TABLE>

</CENTER>

</BODY>

</HTML>

The result of this JSP page in a browser is given in Figure 9.1

.

Figure 9.1. Displaying database records in a JSP page.

230

Note that you don't do any HTML encoding to the data returned by the getString method of the

ResultSet because you don't know yet how to write and use a method in a JSP page. If, for example, the data contains something like <BR>, this will ruin the display in the web browser.

When writing scriptlets, it is commonplace to interweave code with HTML tags, for writing convenience. For instance, you can modify the while statement block of the code in

Listing 9.4

to

the following: while (rs.next()) {

%>

<TR>

<TD><% out.print(rs.getString(1)); %></TD>

<TD><% out.print(rs.getString(2)); %></TD>

<TD><% out.print(rs.getString(3)); %></TD>

<TD><% out.print(rs.getString(4)); %></TD>

</TR>

<%

}

This is perfectly legal syntax.

Note

Switching from scriptlets to HTML tags and vice versa does not incur any performance penalty. The code in

Listing 9.4

can therefore be written into

Listing 9.5

.

Listing 9.5 JSP Page that Interweaves HTML Tags with Scriptlets

<%@ page session="false" %>

<%@ page import="java.sql.*" %>

<%

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

231

System.out.println("JDBC driver loaded");

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

%>

<HTML>

<HEAD>

<TITLE>Display All Users</TITLE>

</HEAD>

<BODY>

<CENTER>

<BR><H2>Displaying All Users</H2>

<BR>

<BR>

<TABLE>

<TR>

<TH>First Name</TH>

<TH>Last Name</TH>

<TH>User Name</TH>

<TH>Password</TH>

</TR>

<%

String sql = "SELECT FirstName, LastName, UserName, Password" +

" FROM Users";

try {

Connection con = DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

%>

<TR>

<TD><% out.print(rs.getString(1)); %></TD>

<TD><% out.print(rs.getString(2)); %></TD>

<TD><% out.print(rs.getString(3)); %></TD>

<TD><% out.print(rs.getString(4)); %></TD>

</TR>

<%

}

rs.close();

s.close();

con.close();

}

catch (SQLException e) {

}

catch (Exception e) {

}

%>

</TABLE>

</CENTER>

</BODY>

</HTML>

Scriptlets alone are not sufficient to write efficient and effective JSP pages. As mentioned earlier, you can't declare a method with scriptlets. Additionally, in the code in Listings

9.4

and

9.5

, the

JSP page will try to load the JDBC driver every time the page is requested. This is unnecessary because the page needs to load it only once. How do you run an initialization code as you do in servlets? The answer is explained in the following section: declarations.

232

Declarations

Declarations allow you to declare methods and variables that can be used from any point in the

JSP page. Declarations also provide a way to create initialization and clean-up code by utilizing the jspInit and jspDestroy methods.

A declaration starts with a <%! and ends with a %> and can appear anywhere throughout the page.

For example, a method declaration can appear above a page directive that imports a class, even though the class is used in the method.

The code in

Listing 9.6

shows the use of declarations to declare a method called getSystemTime

and an integer i.

Listing 9.6 Using Declarations to Declare a Method and a Variable

<%!

String getSystemTime() {

return Calendar.getInstance().getTime().toString();

}

%>

<%@ page import="java.util.Calendar" %>

<%@ page session="false" %>

<%

out.println("Current Time: " + getSystemTime());

%>

<%! int i; %>

The resulting servlet follows. For clarity, some comments have been added to the code. package org.apache.jsp; import java.util.Calendar; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import org.apache.jasper.runtime.*; public class SimplePage_jsp extends HttpJspBase {

// method declaration

String getSystemTime() {

return Calendar.getInstance().getTime().toString();

}

// variable declaration

int i;

static {

}

public SimplePage_jsp() {

}

private static boolean _jspx_inited = false;

public final void _jspx_init() throws org.apache.jasper.JasperException {

}

233

public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws java.io.IOException, ServletException {

// the content has been removed

.

.

.

}

}

See how the variable and method are added as a class-level variable and method in the servlet class?

Having the capability to declare a method, I will present the example in Listings

9.4

and

9.5

to

also apply HTML encoding to the data from the database. The modified code is presented in

Listing 9.7

.

Listing 9.7 JSP Page with a Method Declaration

<%!

String encodeHtmlTag(String tag) {

if (tag == null)

return null;

int length = tag.length();

StringBuffer encodedTag = new StringBuffer(2 * length);

for (int i=0; i<length; i++) {

char c = tag.charAt(i);

if (c == '<')

encodedTag.append("<");

else if (c == '>')

encodedTag.append(">");

else if (c == '&')

encodedTag.append("&amp;");

else if (c == '"')

encodedTag.append("&quot;");

//when trying to output text as tag's value as in

// values="???".

else if (c == ' ')

encodedTag.append("&nbsp;");

else

encodedTag.append(c);

}

return encodedTag.toString();

}

%>

<%@ page session="false" %>

<%@ page import="java.sql.*" %>

<%

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

System.out.println("JDBC driver loaded");

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

%>

<HTML>

<HEAD>

<TITLE>Display All Users</TITLE>

234

</HEAD>

<BODY>

<CENTER>

<BR><H2>Displaying All Users</H2>

<BR>

<BR>

<TABLE>

<TR>

<TH>First Name</TH>

<TH>Last Name</TH>

<TH>User Name</TH>

<TH>Password</TH>

</TR>

<%

String sql = "SELECT FirstName, LastName, UserName, Password" +

" FROM Users";

try {

Connection con = DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

%>

<TR>

<TD><% out.print(encodeHtmlTag(rs.getString(1))); %></TD>

<TD><% out.print(encodeHtmlTag(rs.getString(2))); %></TD>

<TD><% out.print(encodeHtmlTag(rs.getString(3))); %></TD>

<TD><% out.print(encodeHtmlTag(rs.getString(4))); %></TD>

</TR>

<%

}

rs.close();

s.close();

con.close();

}

catch (SQLException e) {

}

catch (Exception e) {

}

%>

</TABLE>

</CENTER>

</BODY>

</HTML>

Writing Initialization and Clean-up Code

The code in Listings

9.4

,

9.5

, and

9.7

suffer from unnecessary repetition: The JSP page tries to

load the JDBC driver every time the page is called. This is just a small example. In real life, you may have similar cases where you need to do initialization and clean-up; that is, you want a piece of code to be run only when the JSP servlet is first initialized or when it is destroyed.

In

Chapter 8 , you learned that every servlet generated from a JSP page must directly or indirectly

implement the javax.servlet.jsp.JspPage interface. This interface has two methods: jspInit and jspDestroy. The JSP container calls the jspInit the first time the JSP servlet is initialized and calls the jspDestroy when the JSP servlet is about to be removed. These two methods provide a way for initialization and clean-up code. With declarations, you can override these two methods.

235

You can now modify the code in

Listing 9.7

by moving the part that loads the JDBC driver to the

jspInit method. The code is given in

Listing 9.8

.

Listing 9.8 Utilizing the jspInit Method

<%!

public void jspInit() {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

System.out.println("JDBC driver loaded");

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

}

String encodeHtmlTag(String tag) {

if (tag == null)

return null;

int length = tag.length();

StringBuffer encodedTag = new StringBuffer(2 * length);

for (int i=0; i<length; i++) {

char c = tag.charAt(i);

if (c == '<')

encodedTag.append("<");

else if (c == '>')

encodedTag.append(">");

else if (c == '&')

encodedTag.append("&amp;");

else if (c == '"')

encodedTag.append("&quot;");

//when trying to output text as tag's value as in

// values="???".

else if (c == ' ')

encodedTag.append("&nbsp;");

else

encodedTag.append(c);

}

return encodedTag.toString();

}

%>

<%@ page session="false" %>

<%@ page import="java.sql.*" %>

<HTML>

<HEAD>

<TITLE>Display All Users</TITLE>

</HEAD>

<BODY>

<CENTER>

<BR><H2>Displaying All Users</H2>

<BR>

<BR>

<TABLE>

<TR>

<TH>First Name</TH>

<TH>Last Name</TH>

<TH>User Name</TH>

<TH>Password</TH>

236

</TR>

<%

String sql = "SELECT FirstName, LastName, UserName, Password" +

" FROM Users";

try {

Connection con = DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

%>

<TR>

<TD><% out.print(encodeHtmlTag(rs.getString(1))); %></TD>

<TD><% out.print(encodeHtmlTag(rs.getString(2))); %></TD>

<TD><% out.print(encodeHtmlTag(rs.getString(3))); %></TD>

<TD><% out.print(encodeHtmlTag(rs.getString(4))); %></TD>

</TR>

<%

}

rs.close();

s.close();

con.close();

}

catch (SQLException e) {

}

catch (Exception e) {

}

%>

</TABLE>

</CENTER>

</BODY>

</HTML>

The generated servlet is presented here. Note that some parts of the servlet code have been removed for brevity. public class SimplePage_jsp extends HttpJspBase {

public void jspInit() {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

System.out.println("JDBC driver loaded");

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

}

String encodeHtmlTag(String tag) {

.

.

.

}

static {

}

public SimplePage_jsp() {

}

237

private static boolean _jspx_inited = false;

public final void _jspx_init() throws org.apache.jasper.JasperException {

}

public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws java.io.IOException, ServletException {

.

.

.

}

}

Expressions

Expressions are the last type of JSP scripting elements. Expressions get evaluated when the JSP page is requested and their results are converted into a String and fed to the print method of the out implicit object. If the result cannot be converted into a String, an error will be raised at translation time. If this is not detected at translation time, at request-processing time, a

ClassCastException will be raised. expression.

An example of an expression is given in Listing 9.9

.

FL

Listing 9.9 Using an Expression

generated servlet: out.print( java.util.Calendar.getInstance().getTime() );

The expression in listing 9.9

is equivalent to the following scriptlet:

Current Time: <% out.print(java.util.Calendar.getInstance().getTime()); %>

As you can see, an expression is shorter because the return value is automatically fed into the out.print.

As another example, the while block shown in

Listing 9.8

can be re-written as follows using

expressions: while (rs.next()) {

%>

<TR>

<TD><%= encodeHtmlTag(rs.getString(1)) %></TD>

<TD><%= encodeHtmlTag(rs.getString(2)) %></TD>

<TD><%= encodeHtmlTag(rs.getString(3)) %></TD>

<TD><%= encodeHtmlTag(rs.getString(4)) %></TD>

</TR>

Team-Fly ®

<%

}

Standard Action Elements

Standard action elements basically are tags that can be embedded into a JSP page. At compile time, they also are replaced by Java code that corresponds to the predefined task.

The following is the list of JSP standard action elements:

• jsp:useBean jsp:setProperty jsp:getProperty jsp:param jsp:include jsp:forward jsp:plugin jsp:params jsp:fallback

The jsp:useBean, jsp:setProperty, and jsp:getProperty elements are related to Bean and are discussed in

Chapter 10 , "Developing JSP Beans." The jsp:param element is used in the

jsp:include, jsp:forward, and jsp:plugin elements to provide information in the name/value format, and therefore will be discussed with the three other elements.

jsp:include

The jsp:include action element is used to incorporate static or dynamic resources into the current page. This action element is similar to the include directive, but jsp:include provides greater flexibility because you can pass information to the included resource.

The syntax for the jsp:include action element has two forms. For the jsp:include element that does not have a parameter name/value pair, the syntax is as follows:

<jsp:include page="relativeURL" flush="true"/>

If you want to pass information to the included resource, use the second syntax:

<jsp:include page="relativeURL" flush="true">

( <jsp:param . . . /> )*

</jsp:include>

The page attribute represents the URL of the included resource in the local server. The flush attribute indicates whether the buffer is flushed. In JSP 1.2, the value of the flush attribute must be true.

In the second form, the * indicates that there can be zero or more elements in the brackets. This means that you also can use this form even though you are not passing any information to the included resource.

jsp:forward

239

The jsp:forward action element is used to terminate the execution of the current JSP page and switch control to another resource. You can forward control either to a static resource or a dynamic resource.

The syntax for the jsp:forward action element has two forms. For the jsp:forward element that does not have a parameter name/value pair, the syntax is as follows:

<jsp:forward page="relativeURL"/>

If you want to pass information to the included resource, use the second syntax:

<jsp:forward page="relativeURL">

( <jsp:param . . . /> )*

</jsp:include>

The page attribute represents the URL of the included resource in the local server.

jsp:plugin

The jsp:plugin action element is used to generate HTML <OBJECT> or <EMBED> tags containing appropriate construct to instruct the browser to download the Java Plugin software, if required, and initiates the execution of a Java applet or a JavaBeans component specified. This is beyond the scope of this book and won't be discussed further.

jsp:params

The jsp:params action element can occur only as part of the <jsp:plugin> action and will not be discussed in this book.

jsp:fallback

The jsp:fallback action element can occur only as part of the <jsp:plugin> action and will not be discussed in this book.

Comments

Commenting is part of good programming practice. You can write two types of comments inside a

JSP page:

Comments that are to be displayed in the resulting HTML page at the client browser

Comments used in the JSP page itself

For comments that are meant to be displayed in the HTML page, you use the comments tags in

HTML. This kind of comment must be sent as normal text in a JSP page. For example, the following code sends an HTML comment to the browser:

<%

out.println("<!–– Here is a comment ––>");

%>

This is equivalent to the following:

240

<!–– Here is a comment ––>

For comments in the JSP page itself, you use the <%–– … ––%> tag pair. For example, here is a

JSP comment:

<%––

Here is a comment

––%>

A JSP comment can contain anything except the closing tag. For example, this is an illegal comment:

<%––

Here is a comment ––%>

––%>

Converting into XML Syntax

XML is getting more and more important in the computing world. JSP pages can be represented using XML, and representing a JSP page as an XML document presents the following benefits:

The content of the JSP page can be validated against a set of descriptions.

The JSP page can be manipulated using an XML tool.

The JSP page can be generated from a textual representation by applying an XML transformation.

Except for the standard action elements, the other JSP programming elements have been presented using the alternative syntax throughout this chapter. This section will show you how non-XML syntax can be converted into XML syntax to share the benefits presented earlier.

Directives

The non-XML syntax for a JSP directive takes the following form:

<%@ directive (attribute="value")* %>

The XML syntax for a directive is as follows:

<jsp:directive:directiveName attribute_list />

Scripting Elements

A scripting element can be one of the following: declaration, scriptlet, or expression. The XML syntax for each of the three is given in the following sections.

Declarations

The alternative syntax for a declaration is as follows:

<%! declaration code %>

This is equivalent to the following XML syntax:

241

<jsp:declaration> declaration code </jsp:declaration>

Scriptlets

The alternative syntax for a scriptlet is as follows:

<% scriptlet code %>

This is equivalent to the following XML syntax:

<jsp:scriptlet> scriptlet code </jsp:scriptlet>

Expressions

The alternative syntax for an expression is as follows:

<%= expression %>

This is equivalent to the following XML syntax:

<jsp:expression> expression </jsp:expression>

Template Data

The <jsp:text> XML tag is used to enclose template data in JSP. The syntax is as follows:

<jsp:text> text </jsp:text>

Summary

This chapter presents the JSP syntax and semantics, the language specification that you need to master writing JSP pages. You have learned the three types of JSP elements: directives, scripting elements, and action elements. You also have learned declarations, scripting elements, and action elements, and have been shown how to use all of them. The last main section of the chapter,

" Converting into XML Syntax ," presents a discussion on the importance of XML syntax as an

alternative for the <% … %> syntax and shows you how to convert the non-XML syntax into

XML equivalents.

242

Chapter 10. Developing JSP Beans

In

Chapter 8 , "JSP Basics," and

Chapter 9 , "JSP Syntax," you learned how you can write JSP

pages by interweaving HTML tags and Java code. Although this makes writing JSP pages easy and straightforward, there are at least two disadvantages to this approach. First, the resulting spaghetti-like page seriously lacks readability. Second, there is no separation of the presentation and business rule implementation. To write a JSP page this way means a JSP author must master both Java and HTML.

Versatility is not something very common in the real world, however. Finding a Java programmer who also is good at HTML page design is as difficult as finding a graphic designer who is proficient in Java. A separation of labor would be nice to have in developing a JSP application; that is, let the graphic designer do the page design and the Java programmer author the code. In

JSP, this is possible through the use of JSP components, such as JavaBeans. In this componentcentric approach, the Java programmer writes and compiles JavaBeans that incorporate all the functionality needed in an application. While the programmer is doing this, the page designer can work with the page design at the same time. When the JavaBeans are ready, the page designer uses tags similar to HTML to call methods and properties of the beans from the JSP page.

In fact, using beans is a very common practice in JSP application development. This approach is popular because JavaBeans introduces reusability. This is to say, rather than building your own piece of code, you can simply use what other people have written. For example, you can purchase a bean for file upload and start uploading files within 30 seconds.

Warning

Note that when you are designing a JavaBean for your JSP page, reusability and modularity are of utmost importance. Therefore, it is not common to use a bean to send

HTML tags to the web browser because this makes the bean customized for that page. If you need to achieve this task, you can use custom tags instead (this is the subject of

Chapter 11 , "Using JSP Custom Tags.")

In this chapter, you learn how to use JavaBeans in JSP pages. You start with a step-by-step approach to quickly write a bean and call it from a JSP page. After you have the confidence that you can comfortably write your own bean, you will look at how to use beans optimally in your

JSP page using the three action elements briefly mentioned in Chapter 9 (jsp:useBean,

jsp:getProperty, and jsp:setProperty).

Calling Your Bean from a JSP Page

This section presents a step-by-step tutorial on how to write and deploy a simple bean called

CalculatorBean that is part of the com.brainysoftware package. After it is deployed, you then can call the bean from a JSP page. In total, there are six steps you need to follow:

1. Write a bean class whose code is given in

Listing 10.1

. Save it as CalculatorBean.java.

Listing 10.1 The CalculatorBean

package com.brainysoftware; public class CalculatorBean {

243

public int doubleIt(int number) {

return 2 * number;

}

}

The code has one public class called doubleIt that returns an integer as a result of multiplication of the argument by 2.

2. Compile the bean to obtain a class file called CalculatorBean.class.

3. Copy the bean class file to the classes directory under WEB-INF under your application directory. The deployment must take into account the package name. In this case, you need to create a directory called com under the classes directory. Under com, create a directory named brainysoftware. Copy your CalculatorBean.class file to this brainysoftware directory.

Note

In

Chapter 16 , "Application Deployment," you will examine other ways of deploying

beans in a JSP application.

The directory structure is shown in

Figure 10.1

.

Figure 10.1. The directory structure for your bean class.

4. Create a JSP page that will call the bean you just created. For this example, just use the code in

Listing 10.2

.

Listing 10.2 Calling a Bean from Your JSP Page

<jsp:useBean id="theBean" class="com.brainysoftware.CalculatorBean"/>

<HTML>

<HEAD>

</HEAD>

<BODY>

<%

int i = 4;

int j = theBean.doubleIt(i);

out.print("2*4=" + j);

%>

</BODY>

</HTML>

6. Open and direct your browser to the URL of the JSP page your wrote in Step 4.

Your browser should display something like

Figure 10.2

.

244

Figure 10.2. Result from calling the bean from a JSP page.

Note

If your JavaBean comes in the form of a .jar file, copy the .jar file into the lib directory under the WEB-INF directory of your application directory to make it available to JSP pages in your application.

Now that you can write your own bean and call it from a JSP page, let's dig deeper into it

A Brief Theory of JavaBeans

This section presents JavaBeans briefly. You'll find a concise discussion here—it's not meant to be a comprehensive tutorial on the topic. JavaBeans have been discussed in dozens of Java books and other online resources. For example, an excellent resource can be found at Sun's Java web site: http://java.sun.com/docs/books/tutorial/javabeans/index.html

.

Really, a bean is just a Java class. You don't need to extend any base class or implement any interface. To be a bean, however, a Java class must follow certain rules specified by the JavaBeans specification. In relation to JavaBeans that can be used from a JSP page, these rules are as follows:

The bean class must have a no-argument constructor. In the bean in

Listing 10.1

, the class

does not have a constructor at all. This still is legal because the Java compiler will automatically create a no-argument constructor for any Java class that does not have a constructor.

Optionally, a bean can have a public method that can be used to set the value of a property. This method is called a setter method. The method does not return any value,

245

and its name starts with "set" followed by the name of the property. A setter method has the following signature: public void setPropertyName (PropertyType value);

For example, the setter method for the property operand must be named setOperand. Note that the spelling for the property name is not exactly the same. A property name starts with a lowercase letter, but the name of the setter uses an uppercase letter after "set"; hence setOperand.

Optionally, a bean can have a public method that can be called to obtain the value of a property. This method is called a getter method, and its return type is the same as the property type. Its name must begin with "get"; followed by the name of the property. A getter method has the following signature: public PropertyType getPropertyName();

As an example, the getter method for the property named operand is getOperand. A property name starts with a lowercase letter, but the name of the getter uses an uppercase letter after "get;" hence getOperand.

Both setter and getter methods are known as access methods. In JSP, the jsp:getProperty and jsp:setProperty action elements are used to invoke a getter and a setter method, respectively. You can call these methods the same way you call an ordinary method, however.

Making a Bean Available

Before you can use a bean in your JSP page, you must make the bean available, using the jsp:useBean action element. This element has attributes that you can use to control the bean's behavior. The syntax for the jsp:useBean element has two forms. The first form is used when you don't need to write any initialization code, and the second form is used if you have Java code that needs to be run when the bean initializes. Code initialization is discussed in the next section.

The two forms of the jsp:useBean action element are as follows:

<jsp:useBean (attribute="value")

+

/> and

<jsp:useBean (attribute="value")

+

>

initialization code

</jsp:useBean>

The (attribute="value")+ part of the code means that one or more attributes must be present. The five attributes that can be used in a jsp:useBean action element are as follows:

• id class type scope beanName

246

Either the class attribute or the type attribute must be present.

The five attributes are explained in the following sections.

id

The id attribute defines a unique identifier for the bean. This identifier can be used throughout the page and can be thought of as the object reference for the bean. The value for the id attribute has the same requirements as a valid variable name in the current scripting language.

class

The class attribute specifies the fully qualified name for the JavaBean class. A fully qualified name is not required if the bean's package is imported using the page directive, however.

type

If the type attribute is present in a jsp:useBean element, it specifies the type of the JavaBean class.

The type of the bean could be the type of the class itself, the type of its superclass, or an interface the bean class implements. Normally, this attribute isn't often used.

scope

The scope attribute defines the accessibility and the life span of the bean. This attribute can take one of the following values:

• page request session application

The default value of the scope attribute is page.

The scope is a powerful feature that lets you control how long the bean will continue to exist.

Each of the attribute values is discussed in the following sections.

page

Using the page attribute value, the bean is available only in the current page after the point where the jsp:useBean action element is used. A new instance of the bean will be instantiated every time the page is requested. The bean will be automatically destroyed after the JSP page loses its scope; namely, when the control moves to another page. If you use the jsp:include or jsp:forward tags, the bean will not be accessible from the included or forwarded page.

request

With the request attribute value, the accessibility of the bean is extended to the forwarded or included page referenced by a jsp:forward or jsp:include action element. The forwarded or included page can use the bean without having a jsp:useBean action element. For example, from inside a forwarded or included page, you can use the jsp:getProperty and jsp:setProperty action elements that reference to the bean instantiated in the original page.

session

247

A bean with a session scope is placed in the user's session object. The instance of the bean will continue to exist as long as the user's session object exists. In other words, the bean's accessibility extends to other pages.

Because the bean's instance is put in the session object, you cannot use this scope if the page on which the bean is instantiated does not participate in the JSP container's session management. For example, the following code will generate an error:

<%@ page session="false" %>

<jsp:useBean id="theBean" scope="session"

class="com.brainysoftware.CalculatorBean"/>

application

A bean with an application scope lives throughout the life of the JSP container itself. It is available from any page in the application.

beanName

The beanName attribute represents a name for the bean that the instantiate method of the java.beans.Beans class expects. com.newriders.HomeLoanBean:

Alternatively, you can import the package com.newriders using a page directive and refer to the class using its name, as follows:

<%@ page import="com.newriders" %>

<jsp:useBean id="theBean" class="HomeLoanBean"/>

Note

TE

AM

The bean is available in the page after the jsp:useBean action element. It is not available before that point.

The Generated Servlet

The jsp:useBean action element causes the JSP container to generate Java code that loads the bean's class. Let's now examine the generated servlet.

Consider again the JSP page that uses a bean in

Listing 10.1

:

<jsp:useBean id="theBean" scope="page"

class="com.brainysoftware.CalculatorBean"/>

<%

int i = 4;

int j = theBean.doubleIt(i);

out.println("2*4=" + j);

%>

If you open the generated servlet class file, you will see that some code is added to the _jspService method that translates the jsp:useBean action element.

Team-Fly ®

public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;

PageContext pageContext = null;

HttpSession session = null;

ServletContext application = null;

ServletConfig config = null;

JspWriter out = null;

Object page = this;

String _value = null;

try {

if (_jspx_inited == false) {

synchronized (this) {

if (_jspx_inited == false) {

jspx_init();

_jspx_inited = true;

}

}

}

_jspxFactory = JspFactory.getDefaultFactory();

response.setContentType("text/html;charset=ISO-8859-1");

pageContext = _jspxFactory.getPageContext(

this, request, response, "", true, 8192, true);

application = pageContext.getServletContext();

config = pageContext.getServletConfig();

session = pageContext.getSession();

out = pageContext.getOut();

// an object reference to the Bean

com.brainysoftware.CalculatorBean theBean = null;

boolean _jspx_specialtheBean = false;

synchronized (pageContext) {

theBean = (com.brainysoftware.CalculatorBean)

pageContext.getAttribute("theBean",PageContext.PAGE_SCOPE);

if ( theBean == null ) {

_jspx_specialtheBean = true;

try {

theBean = (com.brainysoftware.CalculatorBean) java.beans.Beans.instantiate(this.getClass().getClassLoader(),

"com.brainysoftware.CalculatorBean");

}

catch (Exception exc) {

throw new ServletException (

" Cannot create bean of class" +

"com.brainysoftware.CalculatorBean", exc);

}

pageContext.setAttribute("theBean", theBean,

PageContext.PAGE_SCOPE);

}

}

if(_jspx_specialtheBean == true) {

}

out.write("\r\n");

int i = 4;

int j = theBean.doubleIt(i);

out.println("2*4=" + j);

249

}

catch (Throwable t) {

if (out != null && out.getBufferSize() != 0)

out.clearBuffer();

if (pageContext != null) pageContext.handlePageException(t);

}

finally {

if (_jspxFactory != null)

_jspxFactory.releasePageContext(pageContext);

}

}

The most important line of code in the generated servlet is the one that instantiates the bean and casts it to the bean's class type: theBean = (com.brainysoftware.CalculatorBean)

java.beans.Beans.instantiate(this.getClass().getClassLoader(),

"com.brainysoftware.CalculatorBean");

See how the jsp:useBean action element is translated into the instantiate method of java.beans.Beans?

Also note that the generated servlet will be slightly different if you use a different scope for the bean. To be more precise, the getAttribute and setAttribute methods of the PageContext class will be passed a scope according to the scope used for the bean. For instance, if the bean has an application scope, APPLICATION_SCOPE will be used instead of PAGE_SCOPE. If the bean has a session scope, SESSION_SCOPE will be used.

Accessing Properties Using jsp:getProperty and jsp:setProperty

In accessing a property in a bean, you can conveniently use the jsp:getProperty and jsp:setProperty action elements. The jsp:getProperty element is used to obtain the value of an internal variable, and the bean must provide a getter method. The syntax of the jsp:getProperty element is as follows:

<jsp:getProperty name="Bean Name" property="propertyName"/>

The name attribute must be assigned the name of the bean instance from which the property value will be obtained. The property attribute must be assigned the name of the property.

A jsp:getProperty element returns the property value converted into String. The return value is then automatically fed into an out.print method so it will be displayed in the current JSP page.

The jsp:setProperty action element is used to set the value of a property. Its syntax has four forms:

<jsp:setProperty name="Bean Name" property="PropertyName" value="value"/>

<jsp:setProperty name="Bean Name" property="PropertyName"/>

<jsp:setProperty name="Bean Name" property="PropertyName" param="parameterName"/>

250

<jsp:setProperty name="Bean Name" property="*"/>

In all the forms, the name attribute is assigned the name of the bean instance available in the current JSP page. In this section, however, you learn about and use only the first form. The other

three forms will be explained in the next section, " Setting a Property Value from a Request ."

In the first form of the syntax, the property attribute is assigned the name of the property whose value is to be set, and the value attribute is assigned the value of the property.

The following example demonstrates the use of the jsp:getProperty and jsp:setProperty action elements.

Consider the bean called CalculatorBean in the com.brainysoftware package in

Listing 10.3

. It has

a private integer called memory. (Note that the variable name starts with a lowercase m.) It also has a getter called getMemory and a setter named setMemory. Note that in both accessor methods, memory is spelled using an uppercase M.

Listing 10.3 The CalculatorBean with Accessors

package com.brainysoftware; public class CalculatorBean {

private int memory;

public void setMemory(int number) {

memory = number;

}

public int getMemory() {

return memory;

}

public int doubleIt(int number) {

return 2 * number;

}

}

Using the jsp:setProperty and jsp:getProperty action elements, you can set and obtain the value of memory, as demonstrated in the JSP page in

Listing 10.4

.

Listing 10.4 Accessing the Property Using jsp:setProperty and jsp:getProperty

<jsp:useBean id="theBean" class="com.brainysoftware.CalculatorBean"/>

<jsp:setProperty name="theBean" property="memory" value="169"/>

The value of memory is <jsp:getProperty name="theBean" property="memory"/>

Calling this page in a web browser, you should be able to see something similar to Figure 10.3

.

Figure 10.3. Calling the accessor in the bean.

251

As shown in

Figure 10.3

, the result of the jsp:getProperty is displayed on the current JSP page.

Note that you also can access the accessor methods in a conventional way, as described in

Listing

10.5

.

Listing 10.5 Calling Accessor Methods Like Ordinary Methods

<jsp:useBean id="theBean" class="com.brainysoftware.CalculatorBean"/>

<%

theBean.setMemory(987);

%>

The value of memory is <%= theBean.getMemory()%>

In many cases, it is also common to use an expression as the value of the value attribute. For example, the code in

Listing 10.6

feeds a JSP expression to the value attribute in a jsp:setProperty

action element.

Listing 10.6 Feeding a JSP Expression to the Value Attribute

<jsp:useBean id="theBean" class="com.brainysoftware.CalculatorBean"/>

<%

int i = 2;

%>

<jsp:setProperty name="theBean" property="memory" value="<%= 100 * i

%>"/>

The value of memory is <jsp:getProperty name="theBean" property="memory"/>

Setting a Property Value from a Request

252

You can use a more concise way of setting a property value using the jsp:setProperty action element if the value happens to come from the Request object's parameter(s). In fact, there are three forms of syntax, as discussed in the previous section. The three forms are re-written here:

<jsp:setProperty name="Bean Name" property="PropertyName" param="parameterName"/>

<jsp:setProperty name="Bean Name" property="PropertyName"/>

<jsp:setProperty name="Bean Name" property="*"/>

The first form allows you to assign a Request object parameter value to a property. The param attribute of the jsp:setProperty action element must be assigned the name of the Request object's parameter name. The following example demonstrates the use of this form. The example has two pages. The first page is a simple HTML with a form containing a Text box into which the user can enter a number. The code for this page is shown in

Listing 10.7

.

Listing 10.7 The Page Where the User Can Type a Number

<HTML>

<HEAD>

<TITLE>Passing a value</TITLE>

</HEAD>

<BODY>

<CENTER>

Please type in a number in the box

<BR>

<FORM METHOD=POST ACTION=SimplePage.jsp>

<INPUT TYPE=TEXT NAME=memory>

<INPUT TYPE=SUBMIT>

</FORM>

</CENTER>

</BODY>

</HTML>

Note that the TEXT element name is memory and the form is passed to a JSP page called

SimplePage.jsp. The SimplePage.jsp is given in Listing 10.8

.

Listing 10.8 The SimplePage.jsp Page

<jsp:useBean id="theBean" class="com.brainysoftware.CalculatorBean"/>

<jsp:setProperty name="theBean" property="memory" param="memory"/>

The value of memory is <jsp:getProperty name="theBean" property="memory"/>

If the parameter name is the same as the bean's property name, you can even omit the param attribute:

<jsp:setProperty name="theBean" property="memory"/>

This is, of course, the third form of the jsp:setProperty syntax.

The last form allows you to assign the values of Request object's parameters to multiple properties in a bean as long as the names of the properties are the same as the parameter names. The second line in

Listing 10.8

can be replaced with the following:

<jsp:setProperty name="theBean" property="*"/>

253

JavaBeans Code Initialization

The jsp:useBean action element allows you to write code that will be executed after the bean is initialized. For a bean that has a page scope, the initialization code is run every time the JSP page is requested.

Initialization code can be as simple as writing a piece of text, such as the following:

<jsp:useBean id="theBean" scope="page"

class="com.brainysoftware.CalculatorBean">

Initializing the Bean

</jsp:useBean>

Remember that any template data will be translated into an argument to an out.print method. It's not hard to guess that the initialization code will be added to the code block that instantiates the bean. Consider the following _ jspService method of the servlet generated from the previous JSP page. The method has been cleaned up for clarity: public void _jspService(HttpServletRequest request,

HttpServletResponse response)

throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;

PageContext pageContext = null;

HttpSession session = null;

ServletContext application = null;

ServletConfig config = null;

JspWriter out = null;

Object page = this;

String _value = null;

try {

.

.

.

com.brainysoftware.CalculatorBean theBean = null;

.

.

.

synchronized (pageContext) {

theBean = (com.brainysoftware.CalculatorBean)

pageContext.getAttribute("theBean",PageContext.PAGE_SCOPE);

if ( theBean == null ) {

_jspx_specialtheBean = true;

try {

theBean = (com.brainysoftware.CalculatorBean) java.beans.Beans.instantiate(this.getClass().getClassLoader(),

"com.brainysoftware.CalculatorBean");

}

catch (Exception exc) {

throw new ServletException (" Cannot create bean of class "

+"com.brainysoftware.CalculatorBean", exc);

}

pageContext.setAttribute("theBean", theBean,

PageContext.PAGE_SCOPE);

254

}

}

if(_jspx_specialtheBean == true) {

// here is the initialization code

out.write("\r\nInitializing the Bean\r\n");

}

}

catch (Throwable t) {

.

.

.

}

finally {

.

.

.

}

}

At the time of initialization, you even can use the jsp:setProperty action element to set the value of a bean's property, as demonstrated in the code in

Listing 10.9

.

Listing 10.9 Using jsp:setProperty in a Bean's Initialization Code

<jsp:useBean id="theBean" class="com.brainysoftware.CalculatorBean">

<jsp:setProperty name="theBean" property="*"/>

</jsp:useBean>

The SQLToolBean Example

I will now present an example bean that can be used as a tool to execute an SQL statement in a database server. This code is a modification of the SQLToolServlet presented in

Chapter 4 ,

"Accessing Databases with JDBC." Instead of a servlet, you now have a JavaBean.

The example consists of a bean class and two JSP pages. The first JSP page, Login.jsp, is used to obtain the user name and password for the database user authentication. It consists of an HTML form with two TEXT elements—one for the user name and one for the password.

After the form is submitted, the user name and password will be passed as properties to the bean in the second JSP page, SQLTool.jsp. The values of the user name and password will also be preserved in two hidden fields in the form in the SQLTool.jsp page. When the form is submitted, the values of the user name and password are passed back to the server. This way, a user needs to log in only once.

Figures

10.4

through

10.6

show the appearance of this small JSP application.

Figure 10.4. The Login.jsp page.

255

Figure 10.5. The SQLTool.jsp page.

Figure 10.6. The SQLTool.jSP page with some results.

256

All the business rules can be found in the JavaBean shown in

Listing 10.10

.

Listing 10.10 The SQLToolBean

package com.brainysoftware.web; import java.sql.*; import com.brainysoftware.java.StringUtil; public class SQLToolBean {

private String sql = "";

private String userName = "";

private String password = "";

private String connectionUrl;

public String getSql() {

return StringUtil.encodeHtmlTag(sql);

}

public void setSql(String sql) {

if (sql != null)

this.sql = sql;

}

public void setUserName(String userName) {

if (userName != null)

this.userName = userName;

}

public String getUserName() {

return StringUtil.encodeHtmlTag(userName);

}

public void setPassword(String password) {

if (password != null)

this.password = password;

257

}

public String getPassword() {

return StringUtil.encodeHtmlTag(password);

}

public void setConnectionUrl(String url) {

connectionUrl = url;

} public String getResult() {

if (sql == null || sql.equals(""))

return "";

StringBuffer result = new StringBuffer(1024);

try {

Connection con = DriverManager.getConnection(connectionUrl, userName, password);

Statement s = con.createStatement();

if (sql.toUpperCase().startsWith("SELECT")) {

result.append("<TABLE BORDER=1>");

ResultSet rs = s.executeQuery(sql);

ResultSetMetaData rsmd = rs.getMetaData();

// Write table headings

int columnCount = rsmd.getColumnCount();

result.append("<TR>");

for (int i=1; i<=columnCount; i++) {

"</B></TD>\n");

}

result.append("</TR>");

while (rs.next()) {

result.append("<TR>");

for (int i=1; i<=columnCount; i++) {

AM

"</TD>" );

}

FL

Y

}

rs.close();

result.append("</TABLE>");

}

else {

int i = s.executeUpdate(sql);

result.append("Record(s) affected: " + i);

}

s.close();

con.close();

result.append("</TABLE>");

}

catch (SQLException e) {

result.append("<B>Error</B>");

result.append("<BR>");

result.append(e.toString());

}

catch (Exception e) {

result.append("<B>Error</B>");

result.append("<BR>");

result.append(e.toString());

}

return result.toString();

Team-Fly ®

}

}

The SQLToolBean has four internal variables: connectionUrl, userName, password, and sql. The first three are used to obtain a Connection object to the database server, whereas sql is the SQL statement to be executed by the server. The userName, password, and sql have a getter and setter method of their own, whereas the connectionUrl only has a setter. public String getSql() {

return StringUtil.encodeHtmlTag(sql);

} public void setSql(String sql) {

if (sql != null)

this.sql = sql;

} public void setUserName(String userName) {

if (userName != null)

this.userName = userName;

} public String getUserName() {

return StringUtil.encodeHtmlTag(userName);

} public void setPassword(String password) {

if (password != null)

this.password = password;

} public String getPassword() {

return StringUtil.encodeHtmlTag(password);

} public void setConnectionUrl(String url) {

connectionUrl = url;

}

The only method the bean has is the getResult method. For an SQL statement, the return value of this method is a String containing an HTML table. For other types of SQL statements, this method returns the number of records affected by the SQL statement.

Used in various places in the SQLToolBean is the encodeHtmlTag method of the com.brainysoftware.java.StringUtil class. This method encodes a String so that characters with special meanings in HTML are converted to their equivalents. This class is included in the jar file in the CD that accompanies this book. However, you also can copy and paste the encodeHtmlTag method so that you don't have to depend on the jar file. This method is given in

Listing 10.11

.

Listing 10.11 The encodeHtmlTag Method

public static String encodeHtmlTag(String tag) {

if (tag == null)

return null;

int length = tag.length();

StringBuffer encodedTag = new StringBuffer(2 * length);

for (int i=0; i<length; i++) {

char c = tag.charAt(i);

if (c == '<')

259

encodedTag.append("<");

else if (c == '>')

encodedTag.append(">");

else if (c == '&')

encodedTag.append("&amp;");

else if (c == '"')

encodedTag.append("&quot;"); //when trying to output text as tag's

// value as in values="???".

else if (c == ' ')

encodedTag.append("&nbsp;");

else

encodedTag.append(c);

}

return encodedTag.toString();

}

As discussed in Chapter 4 , you need to load the JDBC driver from which you can get a database connection. The JDBC driver needs to be loaded only once, and the code that loads it is given as the initialization code of the bean.

The login page for this application is shown in

Listing 10.12

.

Listing 10.12 The Login.jsp Page

<HTML>

<HEAD>

<TITLE>Login Page</TITLE>

</HEAD>

<BODY>

<CENTER>

<FORM METHOD=POST ACTION=SQLTool.jsp>

<TABLE>

<TR>

<TD>User Name:</TD>

<TD><INPUT TYPE=TEXT NAME=userName></TD>

</TR>

<TR>

<TD>Password:</TD>

<TD><INPUT TYPE=PASSWORD NAME=password></TD>

</TR>

<TR>

<TD><INPUT TYPE=RESET></TD>

<TD><INPUT TYPE=SUBMIT VALUE="Login"></TD>

</TR>

</TABLE>

</FORM>

</CENTER>

</BODY>

</HTML>

This is basically a static HTML that can be safely converted into an HTML page to avoid any processing by the JSP container.

When the form in the HTML page is submitted, the request is passed to the SQLTool.jsp page.

This page is given in Listing 10.13

.

Listing 10.13 The SQLTool.jsp Page

260

<jsp:useBean id="theBean" class="com.brainysoftware.web.SQLToolBean">

<%

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

}

catch (Exception e) {

out.println(e.toString());

}

%>

</jsp:useBean>

<jsp:setProperty name="theBean" property="userName"/>

<jsp:setProperty name="theBean" property="password"/>

<jsp:setProperty name="theBean" property="connectionUrl" value="jdbc:odbc:JavaWeb"/>

<jsp:setProperty name="theBean" property="sql"/>

<HTML>

<HEAD>

<TITLE>SQL Tool</TITLE>

</HEAD>

<BODY>

<BR><H2>SQL Tool</H2>

<BR>Please type your SQL statement in the following box.

<BR>

<BR><FORM METHOD=POST>

<INPUT TYPE=HIDDEN NAME=userName VALUE="<jsp:getProperty name="theBean" property="userName"/>">

<INPUT TYPE=HIDDEN NAME=password VALUE="<jsp:getProperty name="theBean" property="password"/>">

<TEXTAREA NAME=sql COLS=80 ROWS=8>

<jsp:getProperty name="theBean" property="sql"/>

</TEXTAREA>

<BR>

<INPUT TYPE=SUBMIT>

</FORM>

<BR>

<HR>

<BR>

<%= theBean.getResult() %>

</BODY>

</HTML>

First, this code initializes the SQLToolBean using the jsp:useBean action element. Included as the bean initialization code is the code that loads the JDBC driver:

<jsp:useBean id="theBean" class="com.brainysoftware.web.SQLToolBean">

<%

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

}

catch (Exception e) {

out.println(e.toString());

}

%>

</jsp:useBean>

Next, it sets the properties of the Bean:

<jsp:setProperty name="theBean" property="userName"/>

261

<jsp:setProperty name="theBean" property="password"/>

<jsp:setProperty name="theBean" property="connectionUrl"

value="jdbc:odbc:JavaWeb"/>

<jsp:setProperty name="theBean" property="sql"/>

Note that, except for the connectionUrl property, all property values come from the request object.

The values are written as hidden values and obtained using the jsp:getProperty action elements.

Here is the form in the SQLTool.jsp page:

<FORM METHOD=POST>

<INPUT TYPE=HIDDEN NAME=userName VALUE="<jsp:getProperty name="theBean" property="userName"/>">

<INPUT TYPE=HIDDEN NAME=password VALUE="<jsp:getProperty name="theBean" property="password"/>">

<TEXTAREA NAME=sql COLS=80 ROWS=8>

<jsp:getProperty name="theBean" property="sql"/>

</TEXTAREA>

<BR>

<INPUT TYPE=SUBMIT>

</FORM>

When you view the source code of the resulting HTML page, you should be able to see that the user name and password are preserved to be submitted again to the server when the user submits the form:

<HTML>

<HEAD>

<TITLE>SQL Tool</TITLE>

</HEAD>

<BODY>

<BR><H2>SQL Tool</H2>

<BR>Please type your SQL statement in the following box.

<BR>

<BR><FORM METHOD=POST>

<INPUT TYPE=HIDDEN NAME=userName VALUE="sjones">

<INPUT TYPE=HIDDEN NAME=password VALUE="dingoblue">

<TEXTAREA NAME=sql COLS=80 ROWS=8>

</TEXTAREA>

<BR>

<INPUT TYPE=SUBMIT>

</FORM>

<BR>

<HR>

<BR>

</BODY>

</HTML>

Summary

This chapter presents the component-centric architecture of a JSP page, a preferable approach offering several advantages over JSP pages that mix template data and elements. The advantages

262

are more readability, separation of presentation and business rule implementation, and code reusability.

You have learned how to write your own bean and run it with Tomcat. You now also know the various scopes of a bean and how to set and obtain the value of a bean property using the jsp:setProperty and jsp:getProperty action elements.

263

Chapter 11. Using JSP Custom Tags

Using JavaBeans, you can separate the presentation part of a JSP page from the business rule implementation (Java code). However, only three action elements—jsp:useBean, jsp:getProperty, and jsp:setProperty—are available for accessing a bean. As such, in some situations, we have to resort to using code in a JSP page. In other words, oftentimes JavaBeans don't offer complete separation of presentation and business rule implementation.

Take

Listing 10.13

, from the previous chapter, as an example. Even though the JSP page consists

mainly of tags, we still need to write some Java code as initialization code for the bean. This part of

Listing 10.13

is reproduced here for reading convenience.

<jsp:useBean id="theBean" class="com.brainysoftware.web.SQLToolBean">

<%

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

}

catch (Exception e) {

out.println(e.toString());

}

%>

</jsp:useBean>

In other parts of Listing 10.13

, everything is represented by a tag, except when we need to call the getResult method of the bean, in which case we use a JSP expression—as in the following code fragment.

<%= theBean.getResult() %>

Also, JavaBeans are designed with reusability in mind, meaning that using a bean to output

HTML tags directly is not recommended. Outputting HTML tags from a bean makes the Bean useable only from a certain page, even though there are always exceptions to this rule.

In recognition of the imperfection of JavaBeans as a solution to separation of presentation and business rule implementation, JSP 1.1 defined a new feature: custom tags that can be used to perform custom actions.

Custom tags offer some benefits that are not present in JavaBeans. Among others, custom tags have access to all the objects available to JSP pages, and custom tags can be customized using attributes. However, custom tags are not meant to replace JavaBeans completely or make the use of JavaBeans in JSP pages obsolete. JavaBeans have their own fans, too. As you can see, sometimes it is more appropriate to use beans for their reusability, and sometimes it is better to use custom tags. In some circumstances, the choice whether to use JavaBeans or custom tags is not really clear, leaving you with a decision to make based on your experience.

In this chapter, we explore another great feature of JSP: custom tags. It will begin with writing a

JSP page that uses custom tags, deploy the small application with Tomcat, and run it in your web browser. After this experience, we start diving deep into the details of the underlying API—the classes and interfaces in the javax.servlet.jsp.tagext package. We then create more examples based on those classes and interfaces.

264

Writing Your First Custom Tag

This section demonstrates the use of custom tags in a JSP page. As usual, you are encouraged to quickly build a small application, deploy it in Tomcat, and call the page from a web browser. For this example, we build a Java component that sends the following String to the browser: "Hello from the custom tag."

This section also presents the step-by-step approach to building a JSP application that uses custom tags.

Before we start developing the application,

Figure 11.1

shows the directory structure of our JSP

application called myJSPApp. You need to complete the directory structure if you have not done so in the previous chapters.

Figure 11.1. The directory structure of the application.

Now, follow the following five easy steps.

1. Create a TLD file named taglib.tld, as shown in

Listing 11.1

, and save it in the WEB-INF

directory.

Listing 11.1 The TLD File

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag

Library 1.1//EN"

"http://java.sun.com/j2ee/dtds/webjsptaglibrary_1_1.dtd">

<taglib>

265

<tlibversion>1.0</tlibversion>

<shortname></shortname>

<tag>

<name>myTag</name>

<tagclass>com.brainysoftware.MyCustomTag</t agclass>

</tag>

</taglib>

2. Write, compile, and deploy the Java class called MyCustomTag.java given in Listing 11.2

.

Make sure that the .class file is located in the brainysoftware directory, under WEB-

INF/classes/com/ directory.

Listing 11.2 The MyCustomTag.java

package com.brainysoftware; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class MyCustomTag extends TagSupport {

public int doEndTag() throws JspException {

JspWriter out = pageContext.getOut();

try {

out.println("Hello from the custom tag.");

}

catch (Exception e) {

}

return super.doEndTag();

}

}

3. Create a JSP file from the code given in Listing 11.3

. Call it SimplePage.jsp and save it under the myJSPApp directory.

Listing 11.3 The SimplePage.jsp Page

<%@ taglib uri="/myTLD" prefix="easy"%>

<easy:myTag/>

4. Edit your deployment descriptor (web.xml) file. To use custom tags, you must specify a

<taglib> element in your web.xml file. The <taglib> element must appear after the

<servlet> and <servlet-mapping> if any. An example of the deployment descriptor is given in

Listing 11.4

.

Listing 11.4 The Deployment Descriptor for This Application

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application

2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<display-name>template</display-name>

<taglib>

<taglib-uri>/myTLD</taglib-uri>

<taglib-location>/WEB-INF/taglib.tld</taglib-location>

266

</taglib>

</web-app>

Open your web browser and type http://localhost:8080/myJSPApp/SimplePage.jsp

in the

Address box. You should see something similar to

Figure 11.2

.

Figure 11.2. A simple JSP page.

Figure 11.3

shows how all the parts work.

Figure 11.3. The relationship between the deployment descriptor, the JSP page, and the TDL file.

When the user requests the JSP page, the JSP container sees the <taglib> tag. Because of this, the

JSP container knows that it is seeing a custom tag. It then:

267

Consults the deployment descriptor (web.xml) to find the location of the taglib where the

URI is "/myTLD". The deployment descriptor returns the path to the TLD file. The JSP container will remember this path.

Continues processing the next line and encounters the custom tag myTag, prefixed by

"easy". Having found out the name and location of the TLD file, the JSP container reads the TLD file and obtains the fully qualified name of the Java class for the tag myTag. It reads: com.brainysoftware.MyCustomTag.

The JSP container can then load the class for the tag and start processing it.

The generated servlet is not that complicated, as you see here: package org.apache.jsp; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import org.apache.jasper.runtime.*; public class SimplePage_jsp extends HttpJspBase { org.apache.jasper.JasperException {

}

static {

}

public SimplePage_jsp() {

}

FL

Y

private static boolean _jspx_inited = false;

AM

TE

HttpServletResponse response)

throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;

PageContext pageContext = null;

HttpSession session = null;

ServletContext application = null;

ServletConfig config = null;

JspWriter out = null;

Object page = this;

String _value = null;

try {

if (_jspx_inited == false) {

synchronized (this) {

if (_jspx_inited == false) {

_jspx_init();

_jspx_inited = true;

}

}

}

_jspxFactory = JspFactory.getDefaultFactory();

response.setContentType("text/html;charset=ISO-8859-1");

pageContext = _jspxFactory.getPageContext(this, request,

response, "", true, 8192, true);

Team-Fly ®

application = pageContext.getServletContext();

config = pageContext.getServletConfig();

session = pageContext.getSession();

out = pageContext.getOut();

out.write("\r\n");

/* –––– easy:myTag –––– */

com.brainysoftware.MyCustomTag _jspx_th_easy_myTag_0 =

new com.brainysoftware.MyCustomTag();

_jspx_th_easy_myTag_0.setPageContext(pageContext);

_jspx_th_easy_myTag_0.setParent(null);

try {

int _jspx_eval_easy_myTag_0 =

_jspx_th_easy_myTag_0.doStartTag();

if (_jspx_eval_easy_myTag_0 == BodyTag.EVAL_BODY_BUFFERED)

throw new JspTagException("Since tag handler class" +

" com.brainysoftware.MyCustomTag does not implement

BodyTag," + " it can't return BodyTag.EVAL_BODY_TAG");

if (_jspx_eval_easy_myTag_0 != Tag.SKIP_BODY) {

do {

}

while (_jspx_th_easy_myTag_0.doAfterBody() ==

BodyTag.EVAL_BODY_AGAIN);

}

if (_jspx_th_easy_myTag_0.doEndTag() == Tag.SKIP_PAGE)

return;

}

finally {

_jspx_th_easy_myTag_0.release();

}

out.write("\r\n");

}

catch (Throwable t) {

if (out != null && out.getBufferSize() != 0)

out.clearBuffer();

if (pageContext != null)

pageContext.handlePageException(t);

}

finally {

if (_jspxFactory != null)

_jspxFactory.releasePageContext(pageContext);

}

}

}

Having seen a custom tag in action, you are now ready to dissect componenti-zation using custom tags bit by bit. Let's start with the easiest part—the deployment descriptor.

The Role of the Deployment Descriptor

The preceding example illustrates how the JSP container can find the name and location of the

TLD file by looking up the deployment descriptor.

Even though this is a common practice, you can eliminate the role of the deployment descriptor by writing the name and location of the TLD file directly on the JSP page. Therefore, the code in

Listing 11.3

can be replaced with the code in

Listing 11.5

.

269

Listing 11.5 An Alternative JSP Page for the Application

<%@ taglib uri="/WEB-INF/taglib.tld" prefix="easy"%>

<easy:myTag/>

However, directly referring to the TLD file lacks the flexibility to move and change the name of the TLD file without having to edit all the JSP pages that utilize it.

Therefore, indirect reference of the TLD file involving the deployment descriptor is preferable.

Note

Note that in all examples in this chapter, the taglib tag's URI attribute is assigned to

/myTLD. It is assumed you have edited the web.xml file accordingly.

The Tag Library Descriptor

A tag library descriptor (TLD) file is an XML document that defines a tag library and its tags. The first lines of a TLD file are the standard XML header information, as follows:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"

"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

A TLD file contains the <taglib> root element. This element can have the following subelements:

• tlibversion jspversion shortname info uri tag

Of these six elements, the tag element is the only one that can have attributes. However, the tlibversion, shortname, and tag are required in the TLD file.

The tlibversion element specifies the version number of the tag library in the following format:

([0-9])* ("." [0-9])? ("." [0-9])? ("." [0-9])?

The asterisk means that the values in the bracket can be repeated zero or more times, and the question mark means that the value in the bracket is optional. The following are some valid values for a tlibversion element: 1.1.1.1, 2, 2.3, 3.3.6, and so on.

The jspversion element specifies the JSP version. The format is the same as the tlibversion element.

([0-9])* ("." [0-9])? ("." [0-9])? ("." [0-9])?

270

The shortname element specifies a short name for the tag library. The value for this element must begin with a letter and must not contain blank space.

The info element contains the information used for documentation purposes. Its default value is an empty string.

The uri element specifies the link to an additional source of documentation for the tag library.

The tag element is the most important element in a tag library. You can specify more than one tag element in the same TLD file. Therefore, you only have one TLD file for each JSP application.

The tag element is explained in more detail in the following section.

The following is an example of a TLD file:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"

"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

<tlibversion>1.0.123.123.234</tlibversion>

<jspversion>1.2</jspversion>

<shortname></shortname>

<info>Example tags</info>

<uri></uri>

<tag>

<name>myTag</name>

<tagclass>com.brainysoftware.MyCustomTag</tagclass>

<attribute>

<name>number</name>

<required>true</required>

</attribute>

<attribute>

<name>power</name>

<required>true</required>

</attribute>

</tag>

</taglib>

The tag Element

The tag element specifies a custom tag in the library. This element can have six subelements:

• name tagclass teiclass bodycontent info attribute

Of these six tag subelements, name and tagclass are mandatory.

The name element specifies an identifier for the tag.

The tagclass element specifies the fully qualified name of the Java class that handles the processing of this tag.

271

The teiclass element specifies the helper class for this tag, if there is one. tei is short for

TagExtraInfo, the name of a class in the javax.servlet.jsp.tagext package. TagExtraInfo is explained in more detail later in this chapter when we discuss the API.

The bodycontent element specifies the type of the body content of the tag, if any. A body content is what appears between the opening and closing tags. This element can have one of the following values: empty, JSP, or tagdepen-dent. The empty value means that there is no body content supported by the tag. Assigning "JSP" as the value of the bodycontent element indicates that the body content values are one or more JSP elements. The last value, tagdepen-dent, indicates that the tag's body is to be interpreted by the tag.

The info element of the tag element contains an informational description.

The attribute element specifies zero or more attributes. The attribute element can have three subelements: name, required, and rtextprvalue. Only name is a required subelement of the attribute.

The name subelement is the identification for the attribute. The required subelement indicates whether the attribute is mandatory and can take a value of true or false, with false as the default value.

The rtexprvalue subelement indicates whether the value for this attribute can be determined at request time. If the value of this subelement is true, you can assign a request time value such as a

JSP expression.

The Custom Tag Syntax

To use a custom tag in a JSP page, you first need to use a taglib directive in your page. The taglib directive has the following syntax:

<%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>

The uri attribute specifies an absolute or relative URI that uniquely identifies the tag library descriptor associated with this prefix.

The prefix attribute defines a string that will become the prefix to distinguish a custom action.

With a taglig directive, you then can use a custom tag of the following format for a custom tag that does not have a content body:

<prefix:tagName/>

Or, you can use the following format for a custom tag that has a content body:

<prefix:tagName>body</prefix:tagName>

You can pass attributes to the tag handler by specifying the attribute(s) in the custom tag, each with the following format: attributeName="attributeValue"

272

The following example is a custom tag whose prefix is m and whose name is myTag. The tag has two attributes: number with a value of 12, and power with a value of 13.

<m:myTag number="12" power="13"/>

Note

Note that an attribute value must be quoted.

The JSP Custom Tag API

A tag handler is the Java class that is linked to a custom tag and gets invoked every time the JSP container encounters the custom tag. The tag handler is so named because it handles the processing of the tag. To be functional, a tag handler must implement an interface in the javax.servlet.jsp.tagext package or extend one of the classes in the same package.

In JSP 1.2, the javax.servlet.jsp.tagext has four interfaces and twelve classes, four more members than the same package in the JSP 1.1 specification. Some of the members of the javax.servlet.jsp.tagext package are explained here. For a complete reference of this package, see

Appendix E , "The javax.servlet.jsp.tagext Package Reference."

The two most important interfaces are Tag and BodyTag. These two interfaces also set the life cycle of a tag handler. Either Tag or BodyTag must be implemented by a tag handler, either directly or indirectly.

The Tag Interface

Tag handlers that implement the Tag interface must provide implementations for all the interface's methods. These methods are as follows:

• doStartTag doEndTag getParent setParent setPageContext release

You can write a tag handler by simply implementing the Tag interface and providing blank implementations of all its six methods. For example, the code in

Listing 11.6

is a tag handler

called BasicTagHandler that does not do anything.

Listing 11.6 A Simple Tag Handler that Does Not Do Anything

package com.brainysoftware; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class BasicTagHandler implements Tag {

public void setParent(Tag t) {

}

273

public void setPageContext(PageContext p) {

}

public void release() {

}

public Tag getParent() {

return null;

}

public int doStartTag() {

return EVAL_BODY_INCLUDE;

}

public int doEndTag() {

return EVAL_PAGE;

}

}

Note that both doStartTag and doEndTag return an integer. Their return values are one of the four static final integers defined in the Tag interface: SKIP_BODY, EVAL_BODY_INCLUDE,

SKIP_PAGE, and EVAL_PAGE. Tag.SKIP_BODY and Tag.EVAL_BODY_INCLUDE are valid return values of the doStartTag method, whereas Tag.SKIP_PAGE and Tag.EVAL_PAGE are valid return values of the doEndTag method.

The Life Cycle of a Tag Handler

The life cycle of a tag handler that implements the Tag interface is controlled by the JSP container by calling the methods in the following order:

1. The JSP container obtains an instance of the tag handler from the pool or creates a new one. It then calls the setPageContext, passing a PageContext object representing the JSP page where the custom tag is found. If you want to access the JSP page, you need to assign this PageContext object to an object reference that has class scope. The setPageContext method has the following signature: public void setPageContext(PageContext pageContext)

2. The JSP container then calls the setParent method. This method passes a tag object, which represents the closest tag enclosing the current tag handler. If there is no enclosing tag, a null object reference is passed.

The signature of the setParent method is as follows: public void setParent(Tag parent)

3. The JSP container then sets all the attributes in the custom tag, if any. Attributes are handled like properties in a JavaBean, namely by using the getter and setter methods. For example, if the custom tag has an attribute named temperature, the getter is called getTemperature and the setter is called setTemperature. The JSP container calls all the available setter methods to set attribute values.

4. Next, the JSP container calls the doStartTag, whose signature is as follows:

274

public int doStartTag() throws javax.servlet.jsp.JspException

The doStartTag method can return either Tag.SKIP_BODY and

Tag.EVAL_BODY_INCLUDE. If Tag.SKIP_BODY is returned, the JSP container will not process the tag's body contents, if any. If the doStartTag method returns

Tag.EVAL_BODY_INCLUDE, the body contents, if any, will be processed normally.

5. Regardless of the return value of the doStartTag method, the JSP container next calls the doEndTag method. This method has the following signature: public int doEndTag() throws javax.servlet.jsp.JspException

The doEndTag method returns either Tag.SKIP_PAGE or Tag.EVAL_PAGE. If

Tag.SKIP_PAGE is returned, the JSP container will not process the remaining of the JSP page. If Tag.EVAL_PAGE is returned, the JSP container processes the rest of the JSP page as normal.

6. The release method is the last method that the JSP container calls. This method has the following signature: public void release()

You should write any clean-up code in this method implementation. For example, you might want to close a file that was opened in the other method or destroy a database connection.

7. The JSP container returns the instance of the tag handler to a pool for future use.

A Content Substitution Tag Handler

The following example illustrates a tag handler that provides implementations for the setPageContext and doStartTag methods. The setPageContext assigns the PageContext object passed in by the JSP container to an object reference.

The doStartTag then obtains the JspWriter object through the getOut method of the PageContext and writes something to it. Because the tag handler writes directly to the JspWriter object of the current JSP page, whatever it writes is sent to the web browser. The tag handler is called

MyCustomTag and is shown in

Listing 11.7

.

Listing 11.7 The Content Substitution Tag Handler

package com.brainysoftware; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class MyCustomTag implements Tag {

PageContext pageContext;

public void setParent(Tag t) {

}

public void setPageContext(PageContext p) {

pageContext = p;

}

275

public void release() {

}

public Tag getParent() {

return null;

}

public int doStartTag() {

try {

JspWriter out = pageContext.getOut();

out.println("Hello from the tag handler.");

}

catch(Exception e) {

}

return EVAL_BODY_INCLUDE;

}

public int doEndTag() throws JspException {

return EVAL_PAGE;

}

}

To test the tag handler, you need a JSP page as given in Listing 11.8

and a TLD file as given in

Listing 11.9

.

Listing 11.8 The JSP Page that Contains a Custom Tag that Uses the Content

Substitution Tag Handler

<%@ taglib uri="/myTLD" prefix="easy"%>

<easy:myTag/>

Listing 11.9 The TLD File for This Example

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN"

"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

<tlibversion>1.0</tlibversion>

<shortname></shortname>

<tag>

<name>myTag</name>

<tagclass>com.brainysoftware.MyCustomTag</tagclass>

</tag>

</taglib>

An Example: Using Attributes in a custom Tag

The following example presents a tag handler named DoublerTag that doubles an integer and outputs the result to the web browser. It demonstrates the use of an attribute called number. The tag handler has a setter called setNumber that is called by the JSP container to set the attribute value. The code for the tag handler is given in

Listing 11.10

.

Listing 11.10 The DoublerTag

package com.brainysoftware; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*;

276

public class DoublerTag implements Tag {

private int number;

public void setNumber(int number) {

this.number = number;

}

PageContext pageContext;

public void setParent(Tag t) {

}

public void setPageContext(PageContext p) {

pageContext = p;

}

public void release() {

}

public Tag getParent() {

return null;

}

public int doStartTag() {

try {

JspWriter out = pageContext.getOut();

out.println("Double of " + number + " is " + (2 * number));

}

catch(Exception e) {

}

return EVAL_BODY_INCLUDE;

}

public int doEndTag() throws JspException {

return EVAL_PAGE;

}

}

For the code to run, you need a JSP page, as shown in Listing 11.11

, and a TLD file given in

Listing 11.12

.

Listing 11.11 The JSP Page that Calls the DoublerTag

<%@ taglib uri="/myTLD" prefix="easy"%>

<easy:myTag number="12"/>

Listing 11.12 The TLD File for the Example

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library

1.1//EN"

"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

<tlibversion>1.0</tlibversion>

<shortname></shortname>

<tag>

<name>myTag</name>

<tagclass>com.brainysoftware.DoublerTag</tagclass>

277

<attribute>

<name>number</name>

<required>true</required>

</attribute>

</tag>

</taglib>

The IterationTag Interface

The IterationTag interface extends the Tag interface by adding a new method called doAfterBody and a static final integer EVAL_BODY_AGAIN. This method is invoked after the doStartTag method and can return either the Tag.SKIP_BODY or IterationTag.EVAL_BODY_AGAIN. If the latter is returned, the doAfterBody is called again. If the return value is Tag.SKIP_BODY, the body will be skipped and the JSP container will call the doEndTag method.

An Example: A PowerTag

The following example demonstrates a tag handler that implements the IterationTag interface and illustrates the use of the doAfterBody method.

The tag handler, called PowerTag, calculates a base number raised to the power of another number.

It then writes to the Web browser the following: number^power=result

String to the browser:

FL

Y

For instance, if you pass 2 for number and 3 for power, the tag handler returns the following

2^3=8

The code of the tag handler is given in Listing 11.13

.

TE package com.brainysoftware;

AM

import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class PowerTag implements IterationTag {

PageContext pageContext;

private int number;

private int power;

private int counter;

private int result = 1;

// the setter for number

public void setNumber(int number) {

this.number = number;

}

// the setter for power

public void setPower(int power) {

this.power = power;

}

Team-Fly ®

public void setParent(Tag t) {

}

public void setPageContext(PageContext p) {

pageContext = p;

}

public void release() {

}

public Tag getParent() {

return null;

}

public int doStartTag() {

return EVAL_BODY_INCLUDE;

}

public int doAfterBody() {

counter++;

result *= number;

if (counter == power)

return SKIP_BODY;

else

return EVAL_BODY_AGAIN;

}

public int doEndTag() throws JspException {

System.out.println("doEndTag");

try {

JspWriter out = pageContext.getOut();

out.println(number + "^" + power + "=" + result);

}

catch(Exception e) {

}

return EVAL_PAGE;

}

}

To test the code, you need a JSP page, such as the one in Listing 11.14

, and a TLD file given in

Listing 11.15

.

Listing 11.14 The JSP Page that Calls PowerTag

<%@ taglib uri="/myTLD" prefix="easy"%>

<easy:myTag number="2" power="3"/>

Listing 11.15 The TLD File that Is Used in the Example

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library

1.1//EN"

"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

<tlibversion>1.0</tlibversion>

<shortname></shortname>

<tag>

<name>myTag</name>

<tagclass>com.brainysoftware.PowerTag</tagclass>

279

<attribute>

<name>number</name>

<required>true</required>

</attribute>

<attribute>

<name>power</name>

<required>true</required>

</attribute>

</tag>

</taglib>

Manipulating Body Contents with BodyTag and BodyContent

A JSP custom tag can have a body content, such as the following tag:

<%@ taglib uri="/myTLD" prefix="x"%>

<x:theTag>This is the body content</x:theTag>

When you use the Tag and IterationTag interfaces, you cannot manipulate the body content. You don't even have access to it.

If you want to manipulate the body content of the custom tag, you have to use the BodyTag interface and the BodyContent class in the javax.servlet.jsp.tagext package. This section introduces you to these two elements and builds an example of a tag handler that manipulates the body content.

The BodyTag Interface

The BodyTag interface extends the IterationTag interface by adding two methods, doInitBody and setBodyContent, and two static final integers, EVAL_BODY_BUFFERED and

EVAL_BODY_TAG. As of JSP 1.2, however, EVAL_BODY_TAG is deprecated.

A tag handler that implements the BodyTag interface has a life cycle similar to the ones implementing the IterationTag interface. The difference is that the doStartTag method of the tag handler implementing BodyTag can return

SKIP_BODY, EVAL_BODY_INCLUDE, or EVAL_BODY_BUFFERED. If the method returns

EVAL_BODY_INCLUDE, the body is evaluated as it is in IterationTag. If the method returns

EVAL_BODY_BUFFERED, a BodyContent object is created that represents the custom tag's body content. You learn more about the BodyContent class later in this section.

Two extra methods are called by the JSP container in tag handlers implementing the BodyTag interface: setBodyContent and doInitBody. The two methods have the following signatures: public void setBodyContent(BodyContent bodyContent) public void doInitBody() throws javax.servlet.jsp.JspException

The setBodyContent method is called after the doStartTag, followed by the doInitBody method.

The setBodyContent will not be invoked, however, if one or both of the following is true:

The custom tag does not have a body content.

The custom tag has a body content but the doStartTag method returns SKIP_BODY or

EVAL_BODY_INCLUDE.

280

The doInitBody method can be used to prepare for evaluation of the body. Normally, this method is called by the JSP container after the setBody Content method. This method will not be called, however, if one of the following is true:

The custom tag does not have a body content.

The custom tag has a body content, but the doStartTag method returns SKIP_BODY or

EVAL_BODY_INCLUDE.

The BodyContent Class

The BodyContent class is an abstract class that extends the javax.servlet.jsp.JspWriter class. The

BodyContent class represents the body content of the custom tag, if any. You obtain the body content from the setBodyContent method in the BodyTag interface.

An Example: Manipulating the Body Content

The following example shows a tag handler that manipulates the body content of a JSP custom tag.

The tag handler does two things: HTML encode the body content and print the encoded version of the body content to the browser. The tag handler is called EncoderTag and incorporates the htmlEncodeTag method from the com.brainysoftware.java.StringUtil class. The tag handler is given in

Listing 11.16

.

Listing 11.16 The EncoderTag

package com.brainysoftware; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class EncoderTag implements BodyTag {

PageContext pageContext;

BodyContent bodyContent;

/**

* Encode an HTML tag so it will be displayed

* as it is on the browser.

* Particularly, this method searches the

* passed in String and replace every occurrence

* of the following characters:

* '<' with "<"

* '>' with ">"

* '&' with "&amp;"

* //'"' with "&quot;"

* ' ' with "&nbsp;"

*/

private String encodeHtmlTag(String tag) {

if (tag == null)

return null;

int length = tag.length();

StringBuffer encodedTag = new StringBuffer(2 * length);

for (int i=0; i<length; i++) {

char c = tag.charAt(i);

if (c == '<')

encodedTag.append("<");

else if (c == '>')

encodedTag.append(">");

else if (c == '&')

281

encodedTag.append("&amp;");

else if (c == '"')

encodedTag.append("&quot;");

//when trying to output text as tag's value as in

// values="???".

else if (c == ' ')

encodedTag.append("&nbsp;");

else

encodedTag.append(c);

}

return encodedTag.toString();

}

public void setParent(Tag t) {

}

public void setPageContext(PageContext p) {

pageContext = p;

}

public void release() {

}

public Tag getParent() {

return null;

}

public int doStartTag() {

return EVAL_BODY_BUFFERED;

}

public void setBodyContent(BodyContent bodyContent) {

this.bodyContent = bodyContent;

}

public void doInitBody() {

}

public int doAfterBody() {

String content = bodyContent.getString();

try{

JspWriter out = bodyContent.getEnclosingWriter();

out.print(encodeHtmlTag(content));

}

catch(Exception e) {}

return SKIP_BODY;

}

public int doEndTag() throws JspException {

return EVAL_PAGE;

}

}

The important methods are the setBodyContent and the doAfterBody. The setBodyContent method passes the BodyContent objects from the JSP container to the bodyContent object reference that has class-scope, as shown here:

282

public void setBodyContent(BodyContent bodyContent) {

this.bodyContent = bodyContent;

}

You cannot manipulate the body content in the setBodyContent method. You must wait until the doInitBody is called. You write the following manipulation code in the doAfterBody method to take care of this:

String content = bodyContent.getString(); try{

JspWriter out = bodyContent.getEnclosingWriter();

out.print(encodeHtmlTag(content));

} catch(Exception e) {} return SKIP_BODY;

First, you obtain the String representation of the body content using the getString method of the

BodyContent class. Next, to write to the browser, you first need to use the getEnclosingWriter method to obtain the implicit object out of the current JSP page. Finally, to output a String to the browser, you call the print method of JspWriter.

To use the tag handler, you need the JSP page like the one given in Listing 11.17

and a TLD file,

as shown in

Listing 11.18

.

Listing 11.17 The JSP Page that Uses the EncoderTag Tag Handler

<%@ taglib uri="/myTLD" prefix="easy"%>

<easy:myTag><BR> means change line</easy:myTag>

Listing 11.18 The TLD File for this Example

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library

1.1//EN"

"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

<tlibversion>1.0</tlibversion>

<shortname></shortname>

<tag>

<name>myTag</name>

<tagclass>com.brainysoftware.EncoderTag</tagclass>

<bodycontent>tagdependent</bodycontent>

</tag>

</taglib>

The Support Classes

Although the three interfaces—Tag, IterationTag, and BodyTag—provide a great way to write tag handlers, one apparent drawback is inherent to all interfaces: You must provide implementations for all the methods, including those you don't use. This, of course, makes the code look more complex than necessary, and the class takes longer to write and debug.

To solve this problem, the javax.servlet.jsp.tagext package provides support classes that implement those interfaces. These classes are TagSupport and BodyTagSupport. Now, instead of implementing an interface, you can extend one of these classes, as this section explains.

283

The TagSupport Class

The TagSupport class implements the IterationTag interface. Its signature is as follows: public class TagSupport implements IterationTag, java.io.Serializable

The TagSupport class is intended to be used as the base class for tag handlers.

The BodyTagSupport Class

The BodyTagSupport class implements the BodyTag interface and has the following signature: public class BodyTagSupport extends TagSupport implements BodyTag

This class is meant to be subclassed by tag handlers that need to implement the BodyTag interface.

To illustrate the usefulness of these support classes, the following example shows a tag handler called CapitalizerTag that converts a body content to its uppercase version and outputs it to the browser.The code is given in

Listing 11.19

.

Listing 11.19 The CapitalizerTag

package com.brainysoftware; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class CapitalizerTag extends BodyTagSupport {

public int doAfterBody() {

String content = bodyContent.getString();

try{

JspWriter out = bodyContent.getEnclosingWriter();

out.print(content.toUpperCase());

}

catch(Exception e) {}

return SKIP_BODY;

}

}

See how simple the tag handler has become? You don't need to provide implementations of methods you don't use.

To complete the example, here is the JSP page that uses the CapitalizerTag tag handler (in

Listing

11.20

) and the TLD file ( Listing 11.21

).

Listing 11.20 The JSP Page that Uses the CapitalizerTag

<%@ taglib uri="/myTLD" prefix="easy"%>

<easy:myTag>See the big picture?</easy:myTag>

Listing 11.21 The TLD File for this Example

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib

284

PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library

1.1//EN"

"http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd">

<taglib>

<tlibversion>1.0</tlibversion>

<shortname></shortname>

<tag>

<name>myTag</name>

<tagclass>com.brainysoftware.CapitalizerTag</tagclass>

<bodycontent>tagdependent</bodycontent>

</tag>

</taglib>

Summary

You have seen in this chapter that custom tags are an alternative to JavaBeans that enable you to make JSP pages contain only the presentation part of an application. A JSP custom tag is used to invoke an associated tag handler, a Java class that handles the processing of the tag.

Tag handlers implement the Tag, IterationTag, or BodyTag interface, or they extend one of the two support classes: TagSupport and BodyTagSupport.

285

Chapter 12. Programmable File Download

To Internet surfers, downloading files is a day-to-day activity that can be done without effort.

Writing a web program that allows only authorized users to download certain files is a totally different story. Normally, the operating system or web container authentication system lets you password protect files so that file download is allowed only if the user enters the correct user name and password. However, at least two problems exist with this approach:

If you have more than one user, the password must be shared. However, a password is supposed to be private and confidential. The more people who know the password, the less secure it is. Furthermore, if many users know the password, it is not easy to record who downloads a particular file. Also, in some cases, using the operating system or web container authentication system is not as flexible as matching a user's credential against a database table.

Depending on the type of downloaded file, the browser tries to open it with the correct application—if the browser knows the file type. Sometimes, this is not what you want.

You need the browser to display the File Download dialog box, shown in

Figure 12.1

.

Figure 12.1. The File Download dialog box in Internet Explorer.

This chapter discusses a technique that allows you to programmatically send a file to a browser. I call it programmable file download. Using this technique, you have full control over the downloaded file. This chapter offers an example of how to perform programmable file downloads from a JSP page.

Alternatively, you can use the file download bean (com.brainysoftware.web.FileDownload), which can be found in the software/FileDownload directory on the accompanying CD. Just copy the FileDownload.jar file onto the WEB-INF/lib directory of your application directory and restart

Tomcat.

Warning

File Download is commercially available from the Brainysoftware.com

web site at http://www.brainysoftware.com

. Brainysoftware.com

grants the first purchaser of this book a license to deploy the File Download bean, but only on one server. This license does not include technical support and is void if the book is re-sold.

286

Keys to Programmable File Download

Some issues that you need to consider when writing an application that will send a file to a browser are the following:

Unauthorized users should not be able to download a file by typing its URL. This means, the file should be stored in a directory outside of the virtual directory. For example, if your virtual directory is C:\Tomcat\webapps\MyVir, storing the file in this directory or in a subdirectory under this one makes your file visible by anyone on the Internet.

Regardless of the type of file, the browser must display a File Download dialog box (like

the one shown in Figure 12.1

). It should not automatically fire up the application to run

the file if the browser recognizes the file extension. (For example, if the downloaded file is a Microsoft Word document, the browser should not load Microsoft Word in the browser.)

Programmable file download has a number of applications, such as document management applications, for securing a file, and so on. A few things that you need to do to create an application for programmable file download are outlined in the following list:

1. Set the response's content type to APPLICATION/OCTET-STREAM. This value is not case sensitive.

2. Add an HTTP response header named Content-Disposition and give it the following value: attachment; filename=theFileName where theFileName is the default name for the file that appears in the File Download dialog box. This is normally the same name as the file, but not necessarily.

3. Do not send any characters other than the actual file content. This could happen without you realizing it. For example, if you need to write some page directives in your file download JSP page, you might write the directives in a normal way, such as the following:

<%@ page import="java.io.FileInputStream"%>

<jsp:useBean id="DBBeanId" scope="page" class="docman.DBBean"

/>

Without you realizing it, the carriage return at the end of the first page directive will be sent to the browser. Instead, write those directives like the following:

<%@ page import="java.io.FileInputStream" %>

<jsp:useBean id="DBBeanId" scope="page" class="docman.DBBean" />

This looks unusual, but it is safe.

Writing programmable file download code in JSP requires you to use the setContentType method to set the response content type to APPLICATION/OCTET-STREAM. It also requires that you use the setHeader method to add the required header. Afterward, reading the file one character at a time is easy using a java.io.FileInputStream class. The code in

Listing 12.1

allows the user to

programmatically download the C:\access.log file in a Windows operating system. If you use a different operating system, change the value of the filename and filepath variables accordingly.

Listing 12.1 Programmable File Download in JSP

287

<%

// fetch the file

String filename = "access.log";

String filepath = "C:\\";

response.setContentType(

"APPLICATION/OCTET-STREAM");

response.setHeader("Content-Disposition",

"attachment; filename=\"" + filename + "\"");

java.io.FileInputStream fileInputStream =

new java.io.FileInputStream(filepath + filename);

int i;

while ((i=fileInputStream.read()) != -1) {

out.write(i);

}

fileInputStream.close();

out.close();

%>

Using the Brainysoftware.com File Download Bean

An easier way to programmatically download a file is by using the bean found in the authentication prior to sending a file to the browser. Only if the userName and password

FL usual.

Y

Listing 12.2

offers a user

Listing 12.2 Authenticating the User Before Sending a File

TE

<%

AM

String userName = request.getParameter("userName");

String password = request.getParameter("password");

// only allow download if the user supplied the

// correct user name and passwrd

if (userName != null && password != null &&

userName.equals("james") &&

password.equals("cook")) {

String filepath = "C:\\TV.bmp";

theBean.download(response, filepath);

}

else

out.print("Login incorrect");

%>

Summary

Team-Fly ®

Programmable file download is an important function that can be useful in a number of applications. This chapter showed you the things you need to do to send a file to the browser, and how to force the browser to display the File Download dialog box. Knowing the key points enables you to write a programmable file download application in any technology. For more application of programmable file download, see

Chapter 20 , "Web-Based Document

Management."

289

Chapter 13. File Upload

File upload plays a significant role—beyond email applications—in java development. Uploading files to the server is an important function that is offered in more and more types of applications, including web-based document management systems and the likes of "Secure File Transfer via

HTTP."

This chapter discusses all you need to know about file upload. But first thing first. Before you jump excitedly into coding, you need to understand the underlying theory: the HTTP request.

Understanding the HTTP request is critical because when you process an uploaded file, you work with raw data not obtainable by simply querying the HTTP Request object.

The last section of the chapter talks about the File Upload bean from Brainysoftware.com

, included on the accompanying CD. Purchasing this book grants you the right to use it only for learning purposes. To use it in deployment, commercial or non-commercial, you must obtain a separate license. For more information on the license agreement, see the terms and conditions of the software that can be found in the software/fileUpload directory of the CD.

Let's now start by examining the HTTP request.

The HTTP Request

Each HTTP request from the web browser or other web client applications consists of three parts.

These are as follows:

The part containing the HTTP request method, the Uniform Resource Identifier (URI), and the protocol and the protocol version

HTTP request headers

The entity body

These three parts are explained in the following sections.

The request Method, URI, and Protocol

The first part of an HTTP request consists of the request method, the URI, and the protocol. The

HTTP request method indicates the method used in the HTTP request. In HTTP 1.0, the method could be one of the following three methods: GET, HEAD, or POST. In HTTP 1.1, four more methods are added to the initial three: DELETE, PUT, TRACE, and OPTIONS.

Among these seven methods, the two methods that you use most frequently are GET and POST.

GET is the default method. You use it, for example, when you type a URL, such as http://www.brainysoftware.com

, in the Location or Address box of your browser to request a page.

The POST method is also common. You normally use this as the value of the <FORM> tag's

METHOD attribute. When you upload a file, you must use the POST method.

The second subpart of the HTTP request, the URI, specifies an Internet resource. A URI is normally interpreted as relative to the web server's root directory. Thus, it starts with a forward slash (/), as follows:

290

/virtualRoot/pageName

For example, in a typical JavaServer pages application, the URI could be the following:

/eshop/login.jsp

Note

You can find more information on URI at http://rfc.net/rfc2396.html

.

The third subpart of the first part is the protocol and the protocol version understood by the requester (the browser). The protocol must be HTTP, and the version could be 1.0 or 1.1. Most web servers nowadays understand both versions 1.0 and 1.1 of HTTP; therefore, this kind of web server can serve HTTP requests in both versions as well. If you are still using an old HTTP 1.0 web server, you could be in trouble if your users use modern browsers that send requests using

HTTP 1.1 protocol.

Combining the three subparts, the first part of the HTTP request looks like the following:

POST /virtualRoot/pageName HTTP/version

For instance, the following is a typical first part of an HTTP request:

POST /eshop/login.jsp HTTP/1.1

The HTTP Request Headers

The second component of an HTTP request consists of a number of HTTP headers. The four types of HTTP headers are general, entity, request, and response. These headers are summarized in

Table 13.1

, Table 13.2

, and

Table 13.3

. The response headers are HTTP response-specific and as a

result are not relevant to this discussion.

Table 13.1. HTTP General Headers

Header Description

Pragma The Pragma general header is used to include implementation-specific directives that may apply to any recipient along the request/response chain. In other words, pragmas tell the servers used to send this request to behave in a certain way. The Pragma header may contain multiple values. For example, the following line of code tells all proxy servers that relay this request not to use a cached version of the object, but instead to download the object from the specified location:

Pragma: no-cache

Date The Date general header represents the date and time at which the message originated.

Table 13.2. HTTP Entity Headers

Header Description

Allow The Allow header lists the set of methods supported by the resource identified by the requested URL. This field informs the recipient of valid methods associated with the resource. The Allow header is not permitted in a request using the POST method and thus should be ignored if it is received as part of a POST entity. For instance, the following Allow header specifies that GET and HEAD are allowed methods:

Allow: GET, HEAD

Content-

Encoding

The Content-Encoding header is used to describe the type of encoding used on the entity. When present, its value indicates the decoding mechanism that must be applied

291

to obtain the media type referenced by the Content-Type header. For example, the following header specifies that x-gzip is the decoding mechanism that needs to be applied to obtain the media type referenced by the Content-Type header:

Content-Encoding: x-gzip

Content-

Length

The Content-Length header indicates the size (in decimal number of octets) of the entity body sent to the recipient or, in the case of the HEAD method, the size of the entity body that would have been sent had the request been a GET. Applications should use this field to indicate the size of the entity body to be transferred, regardless of the media type of the entity. A valid Content-Length field value is required on all

HTTP/1.0 request messages containing an entity body. Any Content-Length header greater than or equal to 0 is a valid value. For example, the following header specifies that the content length is 123,452 bytes:

Content-Length: 123452

Content-

Type

The Content-Type header indicates the media type of the entity body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET. For example, the following header specifies that text/html is the media type of the HTTP response's entity body:

Content-Type: text/html

Expires The Expires header gives the date and time after which the entity should be considered invalid. This allows information providers to suggest the volatility of the resource or a date after which the information may no longer be accurate. Applications must not cache this entity beyond the date given. The presence of an Expires header does not imply that the original resource will change or cease to exist at, before, or after that time. However, information providers should include an Expires header with that date.

For example, the following header specifies that the content should expire at 13:13:13 on August 6, 2002:

Expires: Tue, 6 Aug 2002 13:13:13 GMT

Last-

Modified

The Last-Modified header indicates the date and time at which the sender believes the resource was last modified. The exact semantics of this field are defined in terms of how the recipient should interpret it: If the recipient has a copy of this resource that is older than the date given by the Last-Modified field, that copy should be considered stale. For example, this header specifies that the resource was last updated at 12:12:12 on Aug 6, 2002:

Last-Modified: Tue, 6 Aug 2002 12:12:12 GMT

Table 13.3. HTTP Request Headers

Header Description

From The From header specifies who is taking responsibility for the request. This field contains the email address of the user submitting the request. For example, the following header indicates that the user's email is [email protected]

:

From: [email protected]

Accept The Accept header contains a semicolon-separated list of MIME representation schemes that are accepted by the client. The server uses this information to determine which data types are safe to send to the client in the HTTP response.

Although the Accept field can contain multiple values, the Accept line itself also can be used more than once to specify additional accept types. (This has the same effect as specifying multiple accept types on a single line.) If the Accept field is not used in the request header, the default accept types of text/plain and text/html are assumed. For example, the following header specifies a few MIME schemes accepted by the client:

Accept: text/plain;

292

text/htmlAccept; image/gif; image/jpeg

Accept-

Encoding

The Accept-Encoding header is similar in syntax to the Accept header; however, it specifies the content-encoding schemes that are acceptable in the response. For instance, the following header indicates that x-compress and x-zip are the contentencoding schemes that the response can accept:

Accept-Encoding: x-compress; x-zip

Accept-

Language

The Accept-Language header also is similar to the Accept header. This header specifies the preferred response language. The following example specifies English as the accepted language:

Accept-Language: en

User-Agent The User-Agent header, if present, specifies the name of the client browser. The first word should be the name of the software, followed by a slash and an optional version number. Any other product names that are part of the complete software package also may be included. Each name/version pair should be separated by a space. This field is used mostly for statistical purposes and allows servers to track software usage and protocol violation. For example, the following header specifies that the client is using Internet Explorer 4.01 on Windows 98 operating system:

User-Agent: Mozilla/4.0

Referer

(compatible; MSIE 4.01; Windows 98)

The Referer header specifies the URI that contained the URI in the request header.

In HTML, this would be the address of the page that contained the link to the requested object. Like the User-Agent header, this header is not required but is mostly for the server's statistical and tracking purpose. For example, the following header specifies that the current request is sent as the result of the user clicking the link http://localhost:8080/MyApp/Page1.jsp

.

Referer: http://localhost:8080/MyApp/Page1.jsp

Authorization The Authorization header contains authorization information. The first word contained in this header specifies the type of authorization system to be used. Then, separated by a space, it should be followed by authorization information such as a user name, password, and so forth. For example, here is a typical Authorization header:

Authorization: user

If-Modified-

Since ken:dragonlancer

The If-Modified-Since header is used with the GET method to make it conditional.

Basically, if the object hasn't changed since the date and time specified by this header, the object is not sent. A local cached copy of the object is used instead. For example, the following is such a header:

If-Modified-Since: Thu, 6 Aug 2002

11:12:29 GMT

The Entity Body

The entity body is the content of the HTTP request itself. The following section illustrates this in the best way—with an example.

HTTP Request Example

293

The following is an example of an HTTP header:

Accept: application/vnd.ms-excel, application/msword, */*

Accept-Language: en-au

Connection: Keep-Alive

Host: localhost

Referer: http://localhost/examples/jsp/num/demo.jsp

User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98)

Content-Length: 32

Content-Type: application/x-www-form-urlencoded

Accept-Encoding: gzip, deflate

LastName=truman&FirstName=daniel

The preceding HTTP header reveals a lot. The first line tells you that the browser sending this request can accept a number of file formats, including Microsoft Excel and Microsoft Word. This information is followed by the language used (in this case, Australian English), the type of connection (keep-alive), and the name of the host (localhost). The header also tells the server that the request is sent from the demo.jsp, which is located in http://localhost/examples/jsp/num/ directory

. Then in the User-Agent entry, the request shows that the user is using Microsoft Internet Explorer version 4.01, which is compatible with Netscape Navigator 4.0. The user's operating system is also recorded as Windows 98. The meaning of the information can be retrieved from

Table 13.1

, Table 13.2

, and Table 13.3

.

Following the header are two pairs of carriage-return line-feed characters. The length of this separator is 4 bytes because each carriage-return line-feed character pair consists of the ASCII character numbers 13 and 10. From the previous HTTP header, you can see that the body consists of the following code:

LastName=truman&FirstName=daniel

The HTTP header clearly comes from a form with two input elements: one called LastName with the value truman and the other called FirstName with the value daniel.

Note that the length of LastName=truman&FirstName=daniel is 32, as indicated by the Content-

Length header.

Now that you have finished dissecting an HTTP request, you are ready to take this information to the coding stage. To program a complete file-upload application, you need to know both the server side and the client side. The next section takes a look at the client side.

Client-Side HTML

Prior to the RFC 1867 standard, eight values were possible for the TYPE attribute of an INPUT element: CHECKBOX, HIDDEN, IMAGE, PASS-WORD, RADIO, RESET, SUBMIT, and

TEXT. Although these form elements have proven useful in a wide variety of applications in which input from the user needs to be transferred to the server, none of these is useful for sending either a text or binary file. For this reason, the TYPE attribute of an Input element was given another possible value: FILE. In addition, the RFC defines a new MIME media type, multipart/form-data, and specifies the behavior of HTML user agents when interpreting a form with ENC-TYPE="multipart/form-data" and/or <INPUT type="file"> tags.

For example, an HTML form author who wants to request one or more files from a user would write this:

294

<FORM ACTION=Jsp1.jsp ENCTYPE="MULTIPART/FORM-DATA" METHOD=POST>

File to Upload: <INPUT NAME=filename TYPE=FILE>

<BR>

<INPUT TYPE=SUBMIT VALUE="Upload">

</FORM>

When an INPUT tag of type FILE is encountered, the browser might show a display of previously selected filenames and a Browse button or selection method. Clicking the Browse button would cause the browser to enter into a file-selection mode appropriate for the platform. Window-based browsers might display a file-selection window, for example. In such a file-selection dialog box, the user would have the option of replacing a current selection, adding a new file selection, and so on.

HTTP Request of an Uploaded File

Before you process a file upload, you should first familiarize yourself with the HTTP request of an uploaded file. The following small application is not for processing an uploaded file; however, it demonstrates how to prepare an HTML page to upload a file and write the HTTP request into a file for further study. Viewing the produced file with a text editor reveals the format of the request, which in turn enables you to extract the filename, the file content, and other useful information.

This small application consists of an HTML file called main.html, a JSP file called Jsp1.jsp, and a

JavaBean called SimpleBean.

The main.html file is the one that the client can use to select a file to upload to the server.

Listing

13.1

presents the code for it.

Listing 13.1 The main.html File

<HTML>

<HEAD>

<TITLE>File Upload</TITLE>

</HEAD>

<BODY>

<FORM ACTION=Jsp1.jsp ENCTYPE="MULTIPART/FORM-DATA" METHOD=POST>

Author: <INPUT TYPE=TEXT Name=Author>

<BR>

Company: <INPUT TYPE=TEXT Name=Company>

<BR>

Select file to upload <INPUT TYPE=FILE Name=Filename>

<BR>

<INPUT TYPE=SUBMIT VALUE="Upload">

</FORM>

</BODY>

</HTML>

You can see that the ENCTYPE attribute is used in the <FORM> tag and its value is

MULTIPART/FORM-DATA. There are four input elements, including the Submit button. The first two are normal TEXT elements called Author and Company. The third one is an element of type FILE, the input element that is used to select a file.

The ACTION attribute of the form has the value of Jsp1.jsp, meaning that the request (and also the file uploaded) is sent to the Jsp1.jsp file.

295

The Jsp1.jsp file simply calls a bean called SimpleBean, as presented in

Listing 13.2

.

Listing 13.2 The Jsp1.jsp File

<jsp:useBean id="TheBean" scope="page" class="SimpleBean " />

<%

TheBean.doUpload(request);

%>

Listing 13.3

presents the code for the SimpleBean bean.

Listing 13.3 The SimpleBean Bean

import java.io.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletInputStream; public class FileUploadBean {

public void doUpload(HttpServletRequest request) throws

IOException {

PrintWriter pw = new PrintWriter(

new BufferedWriter(new FileWriter("Demo.out")));

ServletInputStream in = request.getInputStream();

int i = in.read();

while (i != -1) {

pw.print((char) i);

i = in.read();

}

pw.close();

}

}

The user interface is given by the main.html file and is shown in Figure 13.1

. For this example, I enter some input values for the Author and Company input elements and select a file called abisco.html with the following content. I select an HTML file to upload because I would like to show the content of the file. Because an HTML file is basically a text file, the content is easy to display.

Figure 13.1. The example's user interface.

296

The content of the abisco.html file is as follows:

<HTML>

<HEAD>

<TITLE>Abisco</TITLE>

</HEAD>

</HTML>

After the form in the main.html file is submitted to the Jsp1.jsp page, the Jsp1.jsp page calls the

SimpleBean bean to write everything on the HttpServletRequest object to a file named Demo.out.

When you open the Demo.out file, you will see something similar to the following:

–––––––––––––––––––––––––––––7d15340138

Content-Disposition: form-data; name="Author"

A. Christie

–––––––––––––––––––––––––––––7d15340138

Content-Disposition: form-data; name="Company"

Abisco

–––––––––––––––––––––––––––––7d15340138

Content-Disposition: form-data; name="Filename"; filename="C:\123data\abisco.html"

Content-Type: text/html

<HTML>

<HEAD>

<TITLE>Abisco</TITLE>

</HEAD>

</HTML>

–––––––––––––––––––––––––––––7d15340138––

In brief, the entity body of the HTTP request contains all the form input, including the uploaded file. Those input values are separated from each other by a delimiter. Sometimes called a

297

boundary, this delimiter consists of a few dozen dash characters followed by a random number. In

the previous example, the delimiter is the following line:

–––––––––––––––––––––––––––––7d15340138

And the same delimiter acts as a separator between two form elements' values. The last delimiter ends the entity body with two more dashes:

–––––––––––––––––––––––––––––7d15340138––

For an input value that comes from a nonfile element, the delimiter is followed by the following line:

Content-Disposition: form-data; name=inputName

In the previous line, inputName is the name of the form element. For example:

Content-Disposition: form-data; name="Author"

The line is followed by two sequences of carriage-return line-feed characters and the element value. element and the complete path of the file in the user's computer. From the previous HTTP request, this line is as follows: filename="C:\123data\abisco.html"

C:\123data\abisco.html.

AM

For this example, the value is text/html:

Content-Type: text/html

Like the non-File input element, the content starts after two sequences of carriage-return line-feed characters.

Warnning

The value of the file separator will differ according to the client's operating system. The preceding code illustrates the output from a Windows machine. Linux/Unix will have a forward slash (/) as a file separator and Macintosh a colon (:).

Uploading a File

Based on the explanation in the previous sections, you can now write a JSP page to handle file upload. This JSP page is given in

Listing 13.4

.

Team-Fly ®

Listing 13.4 File Upload JSP Page

<%@ page import="java.io.*" %>

<%

// the directory where the uploaded file will be saved.

String savePath = "C:\\123data\\";

String filename = "";

ServletInputStream in = request.getInputStream();

byte[] line = new byte[128];

int i = in.readLine(line, 0, 128);

int boundaryLength = i - 2;

String boundary = new String(line, 0, boundaryLength); //-2 discards the newline character

while (i != -1) {

String newLine = new String(line, 0, i);

if (newLine.startsWith("Content-Disposition: form-data; name=\""))

{

String s = new String(line, 0, i-2);

int pos = s.indexOf("filename=\"");

if (pos != -1) {

String filepath = s.substring(pos+10, s.length()-1);

// Windows browsers include the full path on the client

// But Linux/Unix and Mac browsers only send the filename

// test if this is from a Windows browser

pos = filepath.lastIndexOf("\\");

if (pos != -1)

filename = filepath.substring(pos + 1);

else

filename = filepath;

}

//this is the file content

i = in.readLine(line, 0, 128);

i = in.readLine(line, 0, 128);

// blank line

i = in.readLine(line, 0, 128);

ByteArrayOutputStream buffer = new ByteArrayOutputStream();

newLine = new String(line, 0, i);

while (i != -1 && !newLine.startsWith(boundary)) {

// the problem is the last line of the file content

// contains the new line character.

// So, we need to check if the current line is

// the last line.

buffer.write(line, 0, i);

i = in.readLine(line, 0, 128);

newLine = new String(line, 0, i);

}

try {

// save the uploaded file

RandomAccessFile f = new RandomAccessFile(

savePath + filename, "rw");

byte[] bytes = buffer.toByteArray();

f.write(bytes, 0, bytes.length - 2);

f.close();

}

299

catch (Exception e) {}

}

i = in.readLine(line, 0, 128);

} // end while

%>

The code in Listing 13.4

begins by obtaining a reference to the ServletInputStream object from the

HTTP request. The ServletInputStream contains the content of the uploaded file as you see here:

ServletInputStream in = request.getInputStream();

The beginning of the uploaded file is separated by the boundary and a sequence of carriage-return line-feed characters. Therefore, you can read the content of the HttpServletRequest object line by line. The following line of code defines a byte array called line: byte[] line = new byte[128];

You then use the readLine method of ServletInputStream to read the first line of the

HttpServletRequest object's content: int i = in.readLine(line, 0, 128);

The first line gives the boundary and its length. The boundary and the length of the boundary are important values, as you will see later. The boundary is terminated by a sequence of carriagereturn line-feed characters; therefore, the actual length is 2 less than the number of bytes returned by the readLine method: int boundaryLength = i - 2;

The boundary is retrieved from the byte array line by discarding the last two carriage-return linefeed characters, as follows:

String boundary = new String(line, 0, boundaryLength);

Having retrieved the boundary, you then can start extracting the form element value by reading the

HttpServletRequest object's content line by line using the while loop, until it reaches the end when the readLine method returns -1. The following code gives an example of this: while (i != -1) {

String newLine = new String(line, 0, i);

.

.

.

}

With browsers on Windows operating systems, the uploaded filename is sent along with the file path. In other operating systems, no file path information is sent.

Now, you can obtain the filename from the read string by using the following code:

String s = new String(line, 0, i-2); int pos = s.indexOf("filename=\""); if (pos != -1) {

String filepath = s.substring(pos+10, s.length()-1);

300

// Windows browsers include the full path on the client

// But Linux/Unix and Mac browsers only send the filename

// test if this is from a Windows browser

pos = filepath.lastIndexOf("\\");

if (pos != -1)

filename = filepath.substring(pos + 1);

else

filename = filepath;

}

After you obtain the filename, you will notice two pairs of carriage-return linefeed characters before the beginning of the uploaded file content. Therefore, you call the readLine method twice: i = in.readLine(line, 0, 128); i = in.readLine(line, 0, 128);

Then begins the actual file content. The content of the file is buffered into a

ByteArrayOutputStream; thus you instantiate one with the following:

ByteArrayOutputStream buffer = new ByteArrayOutputStream();

Then, you keep reading the line until you find another boundary, as shown here: newLine = new String(line, 0, i); while (i != -1 && !newLine.startsWith(boundary)) {

// the problem is the last line of the file content

// contains the new line character.

// So, we need to check if the current line is

// the last line.

buffer.write(line, 0, i);

i = in.readLine(line, 0, 128);

newLine = new String(line, 0, i);

}

The boundary signals the end of the uploaded file. The last step is to save the buffer into a file, as shown in the following code: try {

// save the uploaded file

RandomAccessFile f = new RandomAccessFile(

savePath + filename, "rw");

byte[] bytes = buffer.toByteArray();

f.write(bytes, 0, bytes.length - 2);

f.close();

} catch (Exception e) {}

To use the FileUpload.jsp file in Listing 13.4

, you need another page where the upload form is displayed. An example is given in

Listing 13.5

.

Listing 13.5 The Form to Select a File to Be Uploaded

<HTML>

<HEAD>

<TITLE>File Upload</TITLE>

</HEAD>

<BODY>

301

<FORM ACTION=http://localhost:8080/myApp/servlet/FileUpload.jsp

ENCTYPE="MULTIPART/

FORM-DATA" METHOD=POST>

Select file to upload <INPUT TYPE=FILE Name=Filename>

<BR>

<INPUT TYPE=SUBMIT VALUE="Upload">

</FORM>

</BODY>

</HTML>

FileUpload Bean

The code in

Listing 13.4

allows you to upload a file and save it in the specified directory on the

server. Oftentimes, however, you also want to send other pieces of information along with the file.

The File Upload bean, on the accompanying CD, lets you upload a file and an unlimited number of field values. This component takes the form of a class called com.brainysoftware.web.FileUpload and can be found in the software/FileUpload/ directory of the

CD.

The following is the list of methods in the FileUploadBean class: public String getFilepath()

This method returns the file path where the uploaded file is saved. public String getFilename()

Returns the name of the uploaded file. public String getContentType()

Returns the value of the content type of the uploaded file. public String getFieldValue(String fieldName)

Returns the value of the HTML form element whose name is specified by fieldName. public void setSavePath(String savePath)

Specifies the name of the directory where the uploaded file should be saved on the server. public void doUpload(HttpServletRequest request) throws IOException

The most important method in the FileUploadBean class, this method extracts the field names and values from the HTML form and processes and saves the uploaded file.

Using the File Upload Bean

To use the file, copy the BrainySoftwareFileUpload.jar file in the software/FileUpload directory on the accompanying CD to the WEB-INF/lib directory under your application directory and restart Tomcat.

302

The following listings provide an HTML file and a JSP file that illustrate the use of the bean. The

HTML file contains a form with a few elements. The HTML file is given in Listing 13.6

, and the

JSP file is given in Listing 13.7

.

Listing 13.6 The HTML File to Upload a File

<HTML>

<HEAD>

<TITLE>File Upload</TITLE>

</HEAD>

<BODY>

<FORM ACTION=Jsp1.jsp ENCTYPE="MULTIPART/FORM-DATA" METHOD=POST>

Author: <INPUT TYPE=TEXT Name=Author>

<BR>

Company: <INPUT TYPE=TEXT Name=Company>

<BR>

Comment: <TEXTAREA NAME=Comment></TEXTAREA>

<BR>

Select file to upload <INPUT TYPE=FILE Name=Filename>

<BR>

Description: <INPUT TYPE=TEXT Name=Description>

<BR>

<INPUT TYPE=SUBMIT VALUE="Upload">

</FORM>

</BODY>

</HTML>

When the user submits the form, the HTTP request will be handed to Jsp1.jsp, which uses the

FileUpload bean to process the request. The Jsp1.jsp is given in

Listing 13.7

.

Listing 13.7 The Jsp1.jsp File

<jsp:useBean id="theBean" scope="page" class="com.brainysoftware.web.FileUploadBean" />

<%

//in Windows

theBean.setSavePath("C:\\123data\\");

//in Linux/Unix, you might have something like

//theBean.setSavePath("/home/budi/");

theBean.doUpload(request);

theBean.save();

out.println("Filename:" + theBean.getFilename());

out.println("<BR>Content Type:" + theBean.getContentType());

out.println("<BR>Author:" + theBean.getFieldValue("Author"));

out.println("<BR>Company:" + theBean.getFieldValue("Company"));

out.println("<BR>Comment:" + theBean.getFieldValue("Comment"));

%>

Multiple File Upload

Multiple file upload is possible using the Pro version of the Brainysoftware.com File Upload bean

( http://www.brainysoftware.com

)

303

Summary

File upload is an important function that is used in many different applications. Such applications include the web-based email (for uploading attachments), document management, and FTP by

HTTP.

In this chapter, you learned how to upload a file by first presenting the HTTP request header. You also learned how to process an uploaded file on the server and use the Upload bean from

BrainySoftware.com

.

304

Chapter 14. Security Configuration

In the previous chapters, you learned how to implement a Login page using both servlets and JSP to restrict access to a certain resource.The common practice is to write code that takes a user's name and password and matches them against those stored in a database.

Although this practice is great, there is another approach to securing your application that does not require you to write a single line of code. Instead, you configure the deployment descriptor of the web application you want to secure.

This chapter discusses the security configuration in the deployment descriptor and introduces you to various methods of authentications. This chapter also shows you how to use the securityconstraint and login-config elements to configure security for your applications.

Imposing Security Constraints

By configuring the deployment descriptor, you can restrict access to some resources in an application in many different ways. For example, you can require the user to log in to view one resource, but not another resource. You also can restrict access to a resource if the request is sent using a particular HTTP method. For instance, you can mandate that a resource is viewable as long as the user requests it using the POST method.

Normally, if access to a resource is restricted, you will require the user to log in—that is, enter a user name and password. If the user provides the correct user name and password, access to the page is given. Of course, you can restrict a resource without even allowing the user to enter credentials. If you intend to make a resource unreachable, however, why put it there in the first place?

You can display a Login page automatically. In this case, the browser will display its own Login dialog box. Alternatively, you can use your own Login dialog box if you want.

When imposing security constraints, you need to choose what resources to protect by drafting a

URL pattern. If the HTTP request's URL matches that pattern, access to the resource is restricted; that is, the user will be required to log in. For instance, if the URL pattern you give is

/servlet/FirstServlet, the web container will restrict any request whose URL contains that pattern, such as http://domain/myApp/servlet/FirstServlet

. You can use the wild card * in a

URL pattern to represent any set of characters. For instance, the URL pattern /servlet/* will restrict access to any URL that contains "/servlet/", such as http://domain/myApp/servlet/Testing

or http://domain/myApp/servlet/Filter

.

After you determine what resource(s) to protect, you also need to consider who can have access to that resource. Programmatically, as in the examples in previous chapters, you can hard-code a set of user names and passwords or match a user name and password against a table in a database.

With the deployment descriptor, however, the concept is slightly different. In addition to user names and passwords, you need to be familiar with principals and roles. These items are explained in the next section.

Principals and Roles

305

The concept of the principal is simple. You can think of principals as users. Basically, a principal is an entity. It could be an individual, a corporate, or another type of entity. "Principal" and "user" are used interchangeably to refer to an identity.

A role is an abstract grouping of users. It refers more to a position rather than an individual. You can think of a role as a group. As such, a user can fill one or more roles.

How do you specify the list of users and roles? Tomcat includes a file called tomcat-users.xml in the conf directory under %CATALINA_HOME%. By default, it declares three users, as follows:

<tomcat-users>

<user name="tomcat" password="tomcat" roles="tomcat" />

<user name="role1" password="tomcat" roles="role1" />

<user name="both" password="tomcat" roles="tomcat,role1" />

</tomcat-users>

The file says the following about the users:

The first user is called "tomcat". It can fill the "tomcat" role.

The second user has the name of "role1" and can fill the "role1" role.

The third one is "both" and can play both "tomcat" and "role1" roles.

This is probably not a good example to explain users and roles, so let's use the following example:

<tomcat-users>

<user name="Joe" password="pwd" roles="marketingManager" />

<user name="Peter" password="0192" roles="HRManager" />

<user name="MrDirector" password="humblepine"

roles="marketingManager,HRManager" />

</tomcat-users>

This example also works with three users; their user names are Joe, Peter, and MrDirector. Joe is the Marketing Manager in the organization; therefore, he can fill the marketingManager role. Peter is the HR Manager and he fills the HRManager role. MrDirector is the Director of the company.

He is the highest in the organization rank. He can play both marketingManager and HRManager roles.

Each restricted resource is associated with a role that can have access to it. A servlet that displays the salary list, for example, is likely to be associated with the HRManager role. In this case, Peter can use his user name and password to access it. Joe has a valid user name and password as well.

Joe is not in the position to access the salary list, however. If he ever tries to log in and access the servlet by using his user name and password, he will be refused access.

On the other hand, MrDirector can play both roles. If one day Peter is not in because he is ill (or having another job interview), MrDirector can use his user name and password to access the servlet that displays the salary list.

You can add as many users as you want to the tomcat-users.xml file.

Using the Security-Constraint Element

As previously mentioned, you can restrict access to a resource without entering a single line of code by configuring the deployment descriptor. You can use several elements to assist in doing this. The elements most frequently used are security-constraint and login-config.

306

You use the security-constraint element to restrict access to one or more resources. The securityconstraint element can appear multiple times in a deployment descriptor.

Note

You can find out more about the elements that can be used in the deployment descriptor in

Chapter 16 , "Application Deployment."

The security-constraint element can contain the following elements:

display-name. An optional element that contains a descriptive name to be displayed by an XML manipulation tool.

web-resource-collection. This element identifies a subset of resources to which access needs to be restricted. In the web-resource-collection, you can define the URL pattern(s) and the HTTP method. If no HTTP method is present, the security constraint applies to all methods.

auth-constraint. This element specifies the user roles that should have access to this resource collection. If no auth-constraint element is specified, the security constraint applies to all roles.

user-data-constraint. This element is used to indicate how the data that is sent to the client and web container (and vice versa) must be protected.

The web-resource-collection element can have the following required and optional subelements:

web-resource-name. A name identifying a resource. This is a required element.

description. An optional element containing a description of the resource collection.

url-pattern. An optional element specifying a URL pattern to which the restriction must be applied. There could be zero or more url-pattern elements in a web-resource-collection element.

http-method. An optional element specifying the restricted method. There could be zero or more http-method elements in a web-resource-collection element.

The auth-constraint element can have the following subelements:

description. An optional element describing the auth-constraint element.

role-name. The roles that have access to the restricted resource. This element is required.

The user-data-constraint element can contain the following elements:

description. An optional element describing the user-data-constraint element.

transport-guarantee. This element must have one of the following values: NONE,

INTEGRAL, or CONFIDENTIAL. NONE means that the application does not require any transport guarantees. INTEGRAL means that the data between the server and the client should be sent in such a way that it can't be changed in transit. CONFIDENTIAL means that the data transmitted must be encrypted. In most cases, SSL is used for either

INTEGRAL or CONFIDENTIAL. This element is required.

Let's start with an example of a deployment descriptor, given in Listing 14.1

.

Listing 14.1 The Deployment Descriptor

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

307

"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>

<security-constraint>

<web-resource-collection>

<web-resource-name>

Restricted Area

</web-resource-name>

<url-pattern>/servlet/*</url-pattern>

</web-resource-collection>

<auth-constraint>

<role-name>manager</role-name>

</auth-constraint>

</security-constraint>

</web-app>

Having a deployment descriptor, such as the one in Listing 14.1

, causes the web container to block any request that matches the URL pattern that does not come from a user in the manager role. The auth-constraint element inside the security-constraint element says that the resource can be accessed only by users in the manager role.

Figure 14.1

shows the result when a non-manager tries

to access the resource.

Figure 14.1. Unauthorized user trying to access a restricted area.

TE

AM

FL

Y

Using the login-config Element

The preceding section discussed the security-constraint element. Now, let's have a look at the second element for security configuration—login-config.

Team-Fly ®

Firstly, let's add another user to the tomcat-users.xml file. This user has a user name of "GM", a password of "lontong", and a role of "manager". The tomcat-users.xml file is given in

Listing 14.2

.

Listing 14.2 Adding a New User to the tomcat-users.xml File

<tomcat-users>

<user name="GM" password="lontong" roles="manager" />

<user name="tomcat" password="tomcat" roles="tomcat" />

<user name="role1" password="tomcat" roles="role1" />

<user name="both" password="tomcat" roles="tomcat,role1" />

</tomcat-users>

How does a user access a resource using a specified role? Each user needs to log in using the user name and password assigned to the role.

How do you allow them to log in? By using the login-config element.

Note

When you ask a user to enter credentials (user name and password), you are

authenticating the user. See the sidebar later in this section for more about authentication

methods.

The login-config element can contain the following optional elements:

auth-method. This element contains the authentication methods and can have one of the following values: BASIC, DIGEST, FORM, or CLIENT-CERT. The following sidebar,

"

Authentication Methods ," explains more about these methods.

realm-name. This is the descriptive name that will be displayed in the standard Login dialog box if BASIC is specified as the value of the auth-method element.

form-login-config. This element specifies the Login and error pages that will be used if the value of the auth-method element is FORM. This is explained in more detail in the following section.

Authentication Methods

When you are securing a Java-based web application, you can choose from the following four authentication methods:

Basic authentication

Form-based authentication

Digest authentication

Secure Socket Layer (SSL) and client certificate authentication

Using the Basic authentication, when a user tries to access a restricted resource, the web container asks the browser to display a standard Login dialog box containing two boxes: one for entering a user name, and one for the password. If the user enters the correct user name and password, the server displays the requested resource. Otherwise, the Login dialog box is redisplayed, asking the user to try again. The server will let the user try to log in three times, after which an error message is sent. The drawback of this method is that the user name and password are transmitted to the server using the base64 encoding, which is a very weak encryption scheme.

Form-based authentication is similar to Basic authentication; however, instead of sending an instruction to the browser to display a standard Login page, the server uses a

309

custom Login page that must be prepared by the developer. This authentication method will also display a custom Error page written by the developer on a failed attempt to login.

The authentication methods take care only of displaying the login form. Without SSL, the password is sent as plain text and is insecure. With SSL, the password is sent encrypted.

Even though both basic authentication and form-based authentication send the login information in almost plain text, you can use SSL to encrypt the data.

Digest authentication works like Basic authentication; however, the login information is not transmitted. Instead, the hash of the passwords are sent. This protects the information from malicious sniffers.

Basic and digest authentication methods are specified in RFC2617, which you can find at ftp://ftp.isi.edu/in-notes/rfc2617.txt

.

When the transmitted data is sensitive, you need to use SSL to encrypt it. For more information about SSL, see http://home.netscape.com/eng/ssl3/3-SPEC.HTM

.

As an example of requiring the user to log in, consider the deployment descriptor in Listing 14.3

.

Listing 14.3 Deployment Descriptor that Requires the User to Log In

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>

<security-constraint>

<web-resource-collection>

<web-resource-name>

Restricted Area

</web-resource-name>

<url-pattern>/servlet/*</url-pattern>

</web-resource-collection>

<auth-constraint>

<role-name>manager</role-name>

</auth-constraint>

</security-constraint>

<login-config>

<auth-method>BASIC</auth-method>

<realm-name>User Basic Authentication</realm-name>

</login-config>

</web-app>

See how you use the login-config element? The authentication method used is BASIC. Now every time a user accesses a resource using a URL matching the pattern, the web browser will display a dialog box as shown in

Figure 14.2

.

Figure 14.2. The Login dialog box.

310

The user can then type the user name and password for the manager role. The user name must be

"GM" and the password is "lontong".

If the user does not login successfully, the dialog box reappears. If the user fails to login three

times, the browser will display Figure 14.3

:

Figure 14.3. HTTP Status 401.

If the login is successful, the resource is displayed and an authentication token is sent in the response. After the user logs in successfully, requests for another resource matching the pattern will not require login because the user already has the authentication token.

311

If the user logs in correctly using the user name and password of another role, the browser will display a different page, as you see in

Figure 14.4

. For example, the user might type "tomcat" as

the user name and "tomcat" as the password (using the role tomcat in the tomcat-users.xml file).

Figure 14.4. Using the wrong role.

Allowing Multiple Roles

You can specify more than one role to have access to a resource. For example,

Listing 14.4

gives

the deployment descriptor that allows two roles to access a certain resource.

Listing 14.4 Allowing Multiple Roles to Access a Resource

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>

<security-constraint>

<web-resource-collection>

<web-resource-name>

Restricted Area

</web-resource-name>

<url-pattern>/servlet/*</url-pattern>

</web-resource-collection>

<auth-constraint>

<role-name>manager</role-name>

<role-name>tomcat</role-name>

312

</auth-constraint>

</security-constraint>

<login-config>

<auth-method>BASIC</auth-method>

<realm-name>User Basic Authentication</realm-name>

</login-config>

</web-app>

You also need the tomcat-users.xml file in Listing 14.5

.

Listing 14.5 The tomcat-users.xml File for the Example

<tomcat-users>

<user name="GM" password="lontong" roles="manager" />

<user name="tomcat" password="tomcat" roles="tomcat" />

<user name="role1" password="tomcat" roles="role1" />

<user name="both" password="tomcat" roles="tomcat,role1" />

</tomcat-users>

Now you can use both the manager role and the tomcat role to access the single resource. Note that the tomcat role appears both in the second and fourth user elements. This means that you also can use the user name "both" and password "tomcat" to access the resource.

Form-Based Authentication

The auth-method element in the login-config element allows you to specify FORM as its value.

Assigning FORM as the value of auth-method means that you don't want to use the browser's standard Login page. Instead, you are telling the web container that you want to use your own custom page. This is called form-based authentication.

You need to prepare two pages if you decide to use form-based authentication: a Login page and an Error page. The Login page, which can be a static file or a dynamic resource, is a page that is displayed when a user tries to access a restricted resource. Basically, the Login page can be as simple or as complex as you like. The requirements are that the Login page needs to contain an

HTML form with the following requisites:

The method of the form must be POST.

The value of the ACTION attribute must be "j_security_check".

The form must have two input elements called j_username and j_password. Into these elements the user enters the user name and password.

In addition, you need an Error page that can also be a static page or a dynamic resource. This page is displayed when the user does not log in successfully. Note that the web container will display the Error page on the first failed attempt to login.

The following is an example of form-based authentication. The deployment descriptor is given in

Listing 14.6

.

Listing 14.6 The Deployment Descriptor for Form-Based Authentication

<?xml version="1.0" encoding="ISO-8859-1"?>

313

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>

<security-constraint>

<web-resource-collection>

<web-resource-name>

Restricted Area

</web-resource-name>

<url-pattern>/servlet/*</url-pattern>

</web-resource-collection>

<auth-constraint>

<role-name>manager</role-name>

<role-name>tomcat</role-name>

</auth-constraint>

</security-constraint>

<login-config>

<auth-method>FORM</auth-method>

<form-login-config>

<form-login-page>/Login.html</form-login-page>

<form-error-page>/Error.html</form-error-page>

</form-login-config>

</login-config>

</web-app>

The form-login-config element specifies the URL of the Login page and the Error page. The deployment descriptor mandates that the Login page is called Login.html and is to be found under the application directory. The descriptor also tells the web container that the Error page for this form-based authentication is named Error.html and is also found under the application directory.

Listings

14.7

and

14.8

list the Login page and the Error page, respectively.

Listing 14.7 Login.html

<HTML>

<HEAD>

<TITLE>Login Page</TITLE>

</HEAD>

<BODY>

<CENTER>

<H2>Please enter your user name and password</H2>

<FORM ACTION="j_security_check" METHOD="POST">

<TABLE>

<TR>

<TD>User name:</TD>

<TD><INPUT TYPE=TEXT NAME="j_username"></TD>

</TR>

<TR>

<TD>Password:</TD>

<TD><INPUT TYPE=PASSWORD NAME="j_password"></TD>

</TR>

<TR>

<TD><INPUT TYPE=RESET></TD>

<TD><INPUT TYPE=SUBMIT VALUE="Login"></TD>

</TR>

</TABLE>

</FORM>

314

</BODY>

</HTML>

Listing 14.8 Error.html

<HTML>

<HEAD>

<TITLE>Error Page</TITLE>

</HEAD>

<BODY>

Login failed. Click <A HREF="Login.html">here</A> to try again.

</BODY>

</HTML>

When a user tries to access the resource whose URL matches the pattern specified in the deployment descriptor, the browser displays the Login page shown in

Figure 14.5

.

Figure 14.5. Login page.

If the login fails, the Error page is displayed, as shown in

Figure 14.6

.

Figure 14.6. Error page.

315

A successful login will display the requested page.

Digest Authentication

Using digest authentication does not require you to change too much in the deployment descriptor.

The main difference between Basic and form-based authentication and digest authentication is that you don't specify a realm if the authentication method used is DIGEST.

The following example demonstrates the use of digest authentication. The deployment descriptor

is given in Listing 14.9

.

Listing 14.9 The Deployment Descriptor that Uses the Digest Authentication

Method

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>

<security-constraint>

<web-resource-collection>

<web-resource-name>

Restricted Area

</web-resource-name>

<url-pattern>/servlet/*</url-pattern>

</web-resource-collection>

<auth-constraint>

<role-name>manager</role-name>

316

<role-name>tomcat</role-name>

</auth-constraint>

</security-constraint>

<login-config>

<auth-method>DIGEST</auth-method>

</login-config>

</web-app>

When the user tries to access the restricted resource, a dialog box, such as the one shown in Figure

14.7

, is displayed.

Figure 14.7. Digest Authentication Method dialog box.

Note that this dialog box is very similar to the one used in the Basic authentication method.

Methods Related to Security

Even though configuring the deployment descriptor and specifying roles in the tomcat-users.xml file means that you don't need to do any programming in your code, sometimes some coding is inevitable. For example, you might want to record all users that log in. The javax.servlet.http.HttpServletRequest interface provides a few methods that enable you to have access to portions of the user's login information. These methods are getAuthType, isUserInRole, getPrincipal, and getRemoteUser. The methods are explained here: public String getAuthType()

This method returns the name of the authentication scheme used to protect the servlet. The return value is one of the following values: BASIC_AUTH, FORM_AUTH, CLIENT_CERT_AUTH, and DIGEST_AUTH. It returns null if the request was not authenticated. public boolean isUserInRole(String role)

This method indicates whether the authenticated user is included in the specified logical "role". If the user has not been authenticated, the method returns false.

317

public java.security.Principal getUserPrincipal()

This method returns a java.security.Principal object containing the name of the current authenticated user. If the user has not been authenticated, the method returns null. public String getRemoteUser()

Returns the login of the user making this request, if the user has been authenticated, or null if the user has not been authenticated. Whether the user name is sent with each subsequent request depends on the browser and type of authentication.

For example, the JSP code in

Listing 14.10

demonstrates the use of the different methods.

Listing 14.10 Using HttpServletRequest Methods to Obtain the User Name Login

Information

<%

out.println("Auth Type:" + request.getAuthType());

out.println("<BR>User Principal:" + request.getUserPrincipal());

out.println("<BR>Remote User:" + request.getRemoteUser());

if (request.isUserInRole("tomcat"))

out.println("<BR>User in role");

else

out.println("<BR>User not in role");

%>

If you run this code, you should see something similar to

FL

Y

.

Figure 14.8. Finding out who the user is.

TE

AM

Team-Fly ®

Restricting Certain Methods

The previous examples restrict access to a resource regardless of the HTTP method used to request the resource. You also can selectively choose HTTP methods that you need to restrict. For example, you may want to restrict access to a request that is submitted using the GET method, but yet allows access if the user is using the POST method.

The deployment descriptor in

Listing 14.11

restricts the GET method. If the page is requested

using the GET method, the user needs to log in. If the page is requested using the other methods, such as POST, no authentication is required.

Listing 14.11 Restricting a Certain Method

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/j2ee/dtds/web-app_2_3.dtd">

<web-app>

<security-constraint>

<web-resource-collection>

<web-resource-name>

Restricted Area

</web-resource-name>

<url-pattern>/*</url-pattern>

<http-method>GET</http-method>

</web-resource-collection>

<auth-constraint>

<role-name>manager</role-name>

<role-name>tomcat</role-name>

</auth-constraint>

</security-constraint>

<login-config>

<auth-method>DIGEST</auth-method>

</login-config>

</web-app>

Summary

In this chapter, you have learned how to configure your deployment descriptor so that the web container restricts access to some or all of the resources. The configuration means that you need only to modify your deployment descriptor file—no programming is necessary.

If you need to access the user login's information, you can use the following methods of the javax.servlet.http.HttpServletRequest interface: getRemoteUser, getPrincipal, getAuthType, and isUserInRole.

319

Chapter 15. Caching

You normally store data in a relational database. Connecting to the database, however, is one of the most resource-consumptive operations that you commonly perform in a web application.

Therefore, if you can reduce the number of times your application needs to access the database, your application will generally be faster and more scalable. Many people avoid databases entirely by storing their data in text files or XML files, but this solution is not suitable for every application. In addition, if you have an existing database-based application, using XML will require a change to your data structure and eventually to your application architecture.

This chapter presents two solutions to the database-access problem: caching data in a text file and caching data in memory.

The first solution writes frequently accessed, but hardly changed data, into text files. Hard disk space is very cheap today and having an easily read copy of data will not hurt at all. When your application needs the data from the database, instead of hitting the database server, the application can just include a text file. Unless the database server caches the data in its memory, embedding a text file is an operation that is probably a thousand times faster than opening a connection to a database.

When you include a text file, you can use a server-side include feature of the web server, which is normally achieved by using a .shtml or .shtm file. This technique is, of course, much faster than processing a similar JSP file because with JSP files, you need at least one extra step—the process hand-over from the web server to the JSP container.

This technique presents its own problem, however: maintenance. When the data in the database changes, its copy in the text file must also change.

The second technique, caching data in memory, is even faster. Because a server normally has limited amount of RAM, however, you normally cache only selected data in memory.

This chapter shows you how to use these two techniques to improve your application performance.

Caching Data into a Text File

What sort of data can be cached into a text file? Almost anything—as long as the data meets the following criteria:

Frequently accessed

Not sensitive data, such as user names and passwords

Does not change very often

A large amount of data should qualify. These data items could include the product categories in an online shop, the details of each product, the items in an online auction, and so on.

Consider the example of an online shop. The product categories are seldom changed—maybe not even once a year. These product categories, however, are accessed from the database every time a user visits your online shop because you need to list all categories in the Search In select box. (I'm assuming that your site has search capability because all proper online shops allow the user to

320

search for a specific product.) How many times has your application accessed the database for exactly the same piece of data?

The code in

Listing 15.1

is a typical HTML code fragment used for a search feature in a computer

book online bookstore.

Listing 15.1 HTML Code for a Search Feature in an Online Bookstore

<FORM METHOD=POST ACTION=Search.jsp>

Keyword: <INPUT TYPE=TEXT Name=Keyword><BR>Search In:

<SELECT Name=Category>

<OPTION VALUE=1>Programming</OPTION>

<OPTION VALUE=2>Operating System</OPTION>

<OPTION VALUE=3>Database</OPTION>

<OPTION VALUE=4>Certification</OPTION>

</SELECT>

<INPUT TYPE=SUBMIT VALUE=Search>

</FORM>

When viewed in a web browser, the code in Listing 15.1

. will look similar to Figure 15.1

.

Figure 15.1. The search feature in an online store.

Using JSP, on the server side, you would have the code presented in

Listing 15.2

.

Listing 15.2 Extracting Categories Without Caching

<%@ page import="java.sql.*" %>

<%!

public void jspInit() {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

}

321

catch (ClassNotFoundException e) {

}

}

%>

<FORM METHOD=POST ACTION=Search.jsp>

Keyword: <INPUT TYPE=TEXT Name=Keyword><BR>

Search In: <SELECT Name=Category>

<%

//Open the Categories table

try {

String sql = "SELECT * FROM Categories";

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

out.print("<OPTION VALUE=");

out.print(rs.getString(1));

out.print(">");

out.print(rs.getString(2));

out.print("</OPTION>\n");

}

s.close();

con.close();

}

catch (SQLException e) {

out.println(e.toString());

}

catch (Exception e) {

out.println(e.toString());

}

%>

</SELECT>

<INPUT TYPE=SUBMIT VALUE=Search>

</FORM>

Now if you put the categories in a text file called Categories.txt that contains the text in Listing

15.3

, you don't need to access the database to display the categories in the Search In select box.

Listing 15.3 The Categories.txt File

<OPTION VALUE=1>Programming</OPTION>

<OPTION VALUE=2>Operating System</OPTION>

<OPTION VALUE=3>Database</OPTION>

<OPTION VALUE=4>Certification</OPTION>

The JSP code is much simpler, as you see in Listing 15.4

.

Listing 15.4 The JSP Code when a Text File Is Used

<FORM METHOD=POST ACTION=Search.jsp>

Keyword: <INPUT TYPE=TEXT Name=Keyword><BR>

Search In: <SELECT Name=Category>

<%@ include file="Categories.txt" %>

</SELECT>

<INPUT TYPE=SUBMIT VALUE=Search>

</FORM>

322

Better still, you might not need a JSP page at all. You can use an .shtml extension for that page if your web server supports it. This capability, however, relies on the web server itself and you should consult the documentation that comes with your web server to find out more.

In the case of caching product details into text files, a reasonable approach is to copy the details of each product to a text file and name the text file using the product's ID. What if you have one thousand or one million products? The quantity does not matter here because if your clients have a million products to sell, it is very likely they can afford to buy a high-speed hard disk.

The drawback of this technique is that there appears to be an inevitable maintenance problem. The data items cached into text files are seldom changed, but they do change. When they change, you need to have a way of updating the copy in the text file. Additionally, when a cached item is deleted, you must also remove its copy in the text file.

The solution to this maintenance problem is to modify your administration pages so that when something changes on the database, the copy in the text file also changes. For example, if you cache the product category into a file, whenever you add a new product category to the database, the categories.txt file must be updated.

The code in

Listing 15.5

shows an example of the Category Admin page, which changes the copy

of the product categories in the text file. At first, the page looks similar the one shown in

Figure

15.2

.

Figure 15.2. The administration page to add, update, and delete categories.

Listing 15.5 The Categories Admin Page

<%@ page import="java.sql.*" %>

<%@ page import="java.io.*" %>

<%!

public void jspInit() {

try {

323

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

}

catch (ClassNotFoundException e) {

}

}

%>

<HTML>

<HEAD>

<TITLE>Product Category Admin Page</TITLE>

</HEAD>

<BODY>

<H1>Add, Update, Delete Categories</H1>

<BR><BR>

<B>Add New Category</B>

<BR>

<FORM METHOD=POST>

<INPUT TYPE=HIDDEN NAME=action VALUE=add>

<INPUT TYPE=TEXT NAME=category SIZE=14>

<INPUT TYPE=SUBMIT VALUE=Add>

</FORM>

<HR>

<BR>

<%

String id = request.getParameter("id");

String category = request.getParameter("category");

String action = request.getParameter("action");

String sql;

StringBuffer categories = new StringBuffer(2048);

//Open the Categories table

try {

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

ResultSet rs;

if (action != null && action.equals("add")) {

sql = "SELECT CategoryName FROM Categories WHERE

CategoryName='" + category + "'"; rs = s.executeQuery(sql);

if (!rs.next()) {

sql = "INSERT INTO Categories (CategoryName) VALUES ('" + category + "')";

s.executeUpdate(sql);

}

else

out.println(category + " is already in the database");

}

else if (action != null && action.equals("delete")) {

sql = "DELETE FROM Categories WHERE CategoryID=" + id;

s.executeUpdate(sql);

}

else if (action != null && action.equals("update")) {

sql = "UPDATE Categories SET CategoryName='" + category + "'" +

" WHERE CategoryId=" + id;

s.executeUpdate(sql);

}

sql = "SELECT CategoryID, CategoryName FROM Categories ORDER BY

CategoryName ASC";

rs = s.executeQuery(sql);

// Now list all categories plus the DELETE and UPDATE buttons

out.println("<TABLE>");

324

while (rs.next()) {

id = rs.getString(1);

category = rs.getString(2);

%>

<TR>

<TD>

<FORM METHOD=POST>

<INPUT TYPE=HIDDEN NAME=id VALUE="<%=id%>">

<INPUT TYPE=HIDDEN NAME=action VALUE="update">

<INPUT TYPE=TEXT NAME=category VALUE="<%=category%>">

<INPUT TYPE=SUBMIT VALUE=Update>

</FORM>

</TD>

<TD>

<FORM METHOD=POST>

<INPUT TYPE=HIDDEN NAME=id VALUE="<%=id%>">

<INPUT TYPE=HIDDEN NAME=action VALUE="delete">

<INPUT TYPE=SUBMIT VALUE=Delete>

</FORM>

</TD>

</TR>

<%

categories.append("<OPTION VALUE=").append(id).append(">");

categories.append(category).append("</OPTION>\n");

}

out.println("</TABLE>");

s.close();

con.close();

//Create a text file called Categories.txt in the specified folder

String path = "C:\\123data\\";

FileWriter fw = new FileWriter(path + "categories.txt");

fw.write(categories.toString());

fw.close();

}

catch (SQLException e) {

out.println(e.toString());

}

catch (Exception e) {

out.println(e.toString());

}

%>

</BODY>

</HTML>

In the code in Listing 15.5

, categories.txt is updated every time the administrator adds, deletes, or updates a category, which solves the maintenance problem of caching data in a text file.

Note

The path variable should be assigned the actual location of the category.txt file.

Caching in Memory

325

Caching selected data in memory is preferable if you know which data is requested most often.

This data is dumped into memory at the initialization time of a servlet and is only done once.

Subsequent requests for the cached data will result in faster responses.

The code in

Listing 15.6

demonstrates caching product details from the Products table in memory.

All products marked as "hot" products are retrieved from the database at initialization time and stored in a java.util.HashMap object.

Listing 15.6 Caching Data in Memory

<%@ page import="java.sql.*" %>

<%@ page import="java.util.HashMap" %>

<%!

HashMap products = new HashMap(50);

public void jspInit() {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

String sql = "SELECT ProductId, ProductName, Description,

Price" + " FROM Products" + " WHERE Hot=True";

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

Product product = new Product();

String productId = rs.getString("ProductId");

product.productId = productId;

product.productName = rs.getString("ProductName");

product.description = rs.getString("Description");

product.price = rs.getFloat("Price");

products.put(productId, product);

}

con.close();

}

catch (ClassNotFoundException e) {

}

catch (Exception e) {

}

}

class Product {

String productId;

String productName;

String description;

float price;

}

%>

<%

long t1 = System.currentTimeMillis();

%>

<HTML>

<HEAD>

<TITLE>Product Details</TITLE>

</HEAD>

<BODY>

<%

String productId = request.getParameter("id");

//productId="2";

if (productId == null) {

out.println("The request did not carry a product identifier");

326

return;

}

String productName = null;

String description = null;

float price = 0;

Product product = (Product) products.get(productId);

if (product != null) {

productName = product.productName;

description = product.description;

price = product.price;

}

else {

// not found in the cache, grab from the database

try {

Connection con =

DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

String sql = "SELECT ProductName, Description, Price" +

" FROM Products" +

" WHERE ProductId=" + productId;

ResultSet rs = s.executeQuery(sql);

if (rs.next()) {

productName = rs.getString("ProductName");

description = rs.getString("Description");

price = rs.getFloat("Price");

}

rs.close();

s.close();

con.close();

}

catch (SQLException e) {

out.println(e.toString());

}

catch (Exception e) {

out.println(e.toString());

}

}

%>

<BR>Product Id: <%=productId%>

<BR>Product Name: <%=productName%>

<BR>Description: <%=description%>

<BR>Price: <%=price%>

<BR>

<%

long t2 = System.currentTimeMillis();

out.println("Processing time: " + (t2 - t1));

%>

</BODY>

</HTML>

Each product that needs to be cached is represented by the Product class, whose definition is as follows: class Product {

String productId;

String productName;

String description;

float price;

327

}

The initialization code is written in the jspInit method of the JSP page. This code is executed only once when the JSP servlet is loaded into memory.

The jspInit() method first loads the JDBC driver, opens a connection object, and retrieves all products marked as "hot" products from the Products table, as you see here public void jspInit() {

try {

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection con = DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

String sql = "SELECT ProductId, ProductName, Description, Price"

+

" FROM Products" +

" WHERE Hot=True";

ResultSet rs = s.executeQuery(sql);

.

.

.

con.close();

}

}

catch (ClassNotFoundException e) {

}

catch (Exception e) {

}

After you get the ResultSet object from the Statement's executeQuery method, you instantiate a

Product object, assign values to each field in the Product object, and add the Product object into the HashMap object, as follows: while (rs.next()) {

TE

AM

String productId = rs.getString("ProductId");

product.productId = productId;

FL

Y

product.productName = rs.getString("ProductName");

product.description = rs.getString("Description");

product.price = rs.getFloat("Price");

products.put(productId, product);

}

The product identifier is used as the key for each product added to the HashMap.

When a product is requested, the JSP page first checks to see whether it is available in the

HashMap. If it is, the product is obtained from the HastMap, as you see here:

Product product = (Product) products.get(productId); if (product != null) {

productName = product.productName;

description = product.description;

price = product.price;

}

If the requested product is not available, you have to connect to the database and retrieve the product from the Products table, like this:

Team-Fly ®

// not found in the cache, grab from the database

try {

Connection con = DriverManager.getConnection("jdbc:odbc:JavaWeb");

Statement s = con.createStatement();

String sql = "SELECT ProductName, Description, Price" +

" FROM Products" +

" WHERE ProductId=" + productId;

ResultSet rs = s.executeQuery(sql);

if (rs.next()) {

productName = rs.getString("ProductName");

description = rs.getString("Description");

price = rs.getFloat("Price");

}

rs.close();

s.close();

con.close();

}

catch (SQLException e) {

out.println(e.toString());

}

catch (Exception e) {

out.println(e.toString());

}

}

The JSP page is displayed in Figure 15.3

.

Figure 15.3. Caching data in memory.

The JSP page also defines two variables—t1 and t2—to help measure the time taken to process the

JSP page. t1 is written at the beginning of the page, and t2 is written toward the end of the page.

You want to know the result, don't you?

329

Good news. It works!

My example shows a significant improvement. For a request for a cached product, t2 - t1 equals 0.

This, of course, only means that the processing time is too fast to measure.

For requests for products not in the cache, t2 - t1 results in between 110 and 250 milliseconds.

Conclusion: Caching data in memory really speeds up response time.

Summary

Data caching is a popular technique used on busy web sites. Caching improves scalability of the web application because it reduces the number of times database-related resource-consumptive operations are performed. This chapter demonstrated how you can cache data in text files as well as in memory.

330

Chapter 16. Application Deployment

This chapter discusses the process of deploying your servlet and JSP application. To understand how to properly display your web application, you first need to understand the directory structure of an application. For that reason, this chapter starts with a review of the directory structure. The next topic, which is the primary focus of the chapter, covers the deployment descriptor where you can configure each application. Finally, this chapter helps you learn how to create an alias for your servlet and your JSP page and then map them to a new URL. By creating an alias, you can call your application using a shorter or more preferable URL.

Application Directory Structure

When you first install Tomcat, several directories are created under the directory in which you install Tomcat.

Figure 16.1

shows an example.

Figure 16.1. Tomcat's directory structure.

In this case, Tomcat is installed in a directory called tomcat4. This directory is also known as

%CATALINA_HOME%. See

Appendix A , "Tomcat Installation and Configuration," to find

information on the function of each subdirectory.

In this chapter, you are interested in one of the subdirectories that Tomcat installation creates:

webapps. The webapps directory is the parent directory of every web application that will be run

under this Tomcat installation. When you first install Tomcat, a number of sample applications are also created. One such application is the examples application.

Figure 16.2

illustrates a webapps

directory that includes a number of applications.

Figure 16.2. The myWebApp application.

331

Let's look at the application myWebApp, which represents a typical web application. This myWebApp directory is called the application directory.

Right under an application directory is a directory called WEB-INF, which has special

significance in a web application. Figure 16.2

shows two other directories under the myWebApp

directory: images and jsp. These two directories are optional. The jsp directory is where you store all your JSP pages. You could place them directly under the application directories if you choose; however, organizing all your JSP pages in separate directories is a good practice. The image directory is used to store all the image files. Again, this image directory does not play a significant role except to make your application more organized.

If your web application uses some static files, such as HTML files, you put them under the application directory as well. Alternatively, again for the sake of being organized, you can create a subdirectory under the application directory to group similar files. In a real-world application, having a directory called html for all your HTML files is not uncommon.

As mentioned, the WEB-INF directory has a special meaning. This directory is not visible from a client web browser, and everything you put under it is also hidden from the client. First, the WEB-

INF is where you put your deployment descriptor (web.xml file). Including this deployment descriptor is optional, but you can do a lot of things with it, as you'll see in the following section,

" Deployment Descriptor ."

If you use any servlet, you must have a directory called classes under WEB-INF. Servlets that don't belong to a package must be copied to the classes directory. For servlets with a package, you must create a valid directory structure that reflects the Java package. In

Figure 16.2

, you saw a

directory structure under class for servlets that belong to the com.newriders package.

The lib directory under WEB-INF is useful if you use a library files, such as .jar files. Library files copied here will be available to all resources in the application. If you have a library that needs to be available to more than one application, you can put it under the lib directory under

%CATALINA_HOME%.

If you use custom tag libraries for your JSP pages, the TLD file(s) must also go under WEB-INF or in a subdirectory beneath it. In

Figure 16.2

, a directory called tld is created to hold all TLD files.

JavaBeans and custom tag component class files are stored in the classes directory under WEB-

INF.

332

Deployment Descriptor

A deployment descriptor is an XML document that contains information describing a specific servlet or JSP application. Some of the elements in a deployment descriptor are related to servlets, and some are related to JSP applications.

A typical deployment descriptor starts with the following header:

<?xml version="1.0" encoding="ISO-8859-1"?>

This header specifies the version of XML and the encoding used. The header is followed by the following DOCTYPE declaration:

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

This code specifies the document type definition (DTD) against which you can check the validity of the XML document. The previous <!DOCTYPE> element has several attributes that tell us a lot about the DTD.

The following list describes the information you can learn from the <!DOCTYPE> element:

• web-app defines the root element of this document (deployment descriptor, not DTD file).

PUBLIC means that the DTD file is intended for public use.

"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" means that the DTD is maintained by Sun Microsystems, Inc. This information also tells us that the type of the document it describes is DTD Web Application 2.3, and the DTD is written in English.

The URL " http://java.sun.com/dtd/web-app_2_3.dtd

"> represents the location of the

DTD file.

Warning

Note that the DTD file location shown in the preceding list is a new address: The DTD file location used to be http://java.sun.com/j2ee/dtds/web-app_2_3.dtd

.

The root element of a deployment descriptor is web-app. This element can have up to 23 kinds of subelements, all of which are optional. Some subelements can appear only once, and others can appear more than once. Additionally, some of these subelements can have subelements.

Note

For those of you who are not XML experts, here are some notes that can be useful in understanding the following discussion about DTDs: x+ : one or more occurrences of x. x* : zero or more occurrences of x. x? : optional x.

333

x, y : x followed by y. x | y : x or y

PCDATA = parsed character data. Parsed character data is text that does not contain markup, but rather simple character data.

According to the DTD file, the syntax of the web-app element's subelements is briefly described as follows:

<!ELEMENT web-app (icon?, display-name?, description?, distributable?, context-param*, filter*, filter-mapping*, listener*, servlet*, servlet-mapping*, session-config?, mime-mapping*, welcome-file-list?, error-page*, taglib*, resourceenv-ref*, resource-ref*,

security-constraint*, login-config?, security-role*,env-entry ejbref*, ejb-local-ref*)>

The question mark (?) character indicates that a subelement is optional and can appear only once.

The asterisks (

*

) are used to specify subelements that can appear more than once in the deployment descriptor. The description of the subelements indicates that all subelements are optional.

Following this web-app element declaration comes the declarations of each subelement. This chapter discusses each element based on its functionality.

Note

Subelements must appear in the order specified previously. For example, if the web-app element in a deployment descriptor has both servlet and servlet-mapping subelements, the servlet subelement must appear before the servlet-mapping subelement.

A deployment descriptor generally looks like the following:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/j2ee/dtds/web-app_2.3.dtd">

<web-app>

<element-1>

<subelement-1>value of subelement-1 of element-1</subelement-1>

<subelement-2>value of subelement-2 of element-1</subelement-2>

.

.

.

</element-1>

<element-2>

<subelement-1>value of subelement-1 of element-2</subelement-1>

<subelement-2>value of subelement-2 of element-2</subelement-2>

.

.

.

</element-2>

.

334

.

.

<element-n>

<subelement-1>value of subelement-1 of element-n</subelement-1>

<subelement-2>value of subelement-2 of element-n</subelement-2>

.

.

.

</element-n>

</web-app>

The following example shows the deployment descriptor of a servlet application:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/j2ee/dtds/web-app_2.3.dtd">

<web-app>

<servlet>

<servlet-name>HttpRequestDemo</servlet-name>

<servlet-class>HttpRequestDemoServlet</servlet-class>

</servlet>

<servlet>

<servlet-name>Primitive</servlet-name>

<servlet-class>PrimitiveServlet</servlet-class>

</servlet>

<servlet>

<servlet-name>ConfigDemo</servlet-name>

<servlet-class>ConfigDemoServlet</servlet-class>

<init-param>

<param-name>adminEmail</param-name>

<param-value>[email protected]</param-value>

</init-param>

<init-param>

<param-name>adminContactNumber</param-name>

<param-value>0414371237</param-value>

</init-param>

</servlet>

</web-app>

Note

A deployment descriptor, like other XML documents, can also contain comments. A comment in XML is anything between the <!-- tag and the --> tag.

The subelements are explained in the following sections. An example is given for each subelement.

icon

The icon element contains an optional small-icon subelement and an optional large-icon subelement. Its element description is as follows:

<!ELEMENT icon (small-icon?, large-icon?)>

<!ELEMENT small-icon (#PCDATA)>

<!ELEMENT large-icon (#PCDATA)>

335

The icon element is used to specify the filenames for a small (16 x 16) and or a large (32 x 32) icon in either GIF or JPEG format. The filename is a path relative to the root of the web application archive (WAR).

The icon can be used by an XML tool if you happen to use a tool to edit your deployment descriptor. The web container does not use this element.

For example, the following is a deployment descriptor that uses an icon element. The icon element has both a small icon and a large icon:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<icon>

<small-icon>/CompanyLogo.jpg</small-icon>

<large-icon>/CompanyBigLogo.jpg</large-icon>

</icon>

</web-app>

display-name

The display-name element contains a name to be displayed by an XML tool if you use a tool to edit your deployment descriptor. The element descriptor for display-name is as follows:<!ELEMENT display-name (#PCDATA)>. The following example is a deployment descriptor that has both icon and display-name elements:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<icon>

<small-icon>/CompanyLogo.jpg</small-icon>

<large-icon>/CompanyBigLogo.jpg</large-icon>

</icon>

<display-name>Superposition Marketing</display-name>

</web-app>

description

You use the description element to provide information about the deployment descriptor. The value of the description element can be used by an XML tool.

The description element has the following element descriptor:

<!ELEMENT description (#PCDATA)>

The following is an example of a deployment descriptor that uses a description element:

<?xml version="1.0" encoding="ISO-8859-1"?>

336

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<display-name>Superposition Marketing</display-name>

<description>This application tracks statistical changes</description>

</web-app>

distributable

If present in a deployment descriptor, the distributable element indicates that the application is written to be deployed into a distributed web container. The syntax for this element is as follows:

<!ELEMENT distributable EMPTY>

For example, the following is a deployment descriptor that contains a distributable element:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<display-name>Superposition Marketing</display-name>

<distributable/>

</web-app>

context-param

The context-param element contains a pair of parameter names and values used as the application's servlet context initialization parameter. The parameter name must be unique throughout the web application. The syntax for the context-param element and its subelements is as follows:

<!ELEMENT context-param (param-name, param-value, description?)>

<!ELEMENT param-name (#PCDATA)>

<!ELEMENT param-value (#PCDATA)>

<!ELEMENT description (#PCDATA)>

The param-name subelement contains the parameter name, and the param-value subelement contains the parameter value. Optionally, a description subelement also can be present to describe the parameter.

The following is a valid deployment descriptor with a few context-param elements:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<context-param>

<param-name>adminName</param-name>

337

<param-value>Tommy Matena</param-value>

</context-param>

<context-param>

<param-name>initValue</param-name>

<param-value>8060</param-value>

<description>the port number used</description>

</context-param>

</web-app>

filter

This element specifies a filter in the web application. The filter is mapped either to a servlet or a

URL pattern using the filter-mapping element described in the next section. The filter element and the filter-mapping element that does the mapping for this filter must have the same name. Filters are discussed in

Chapter 7 , "Servlet Filtering."

The element descriptor for filter is as follows:

<!ELEMENT filter (icon?, filter-name, display-name?, description?, filter-class, init-param*)>

<!ELEMENT filter-name (#PCDATA)>

<!ELEMENT filter-class (#PCDATA)> param has the same element descriptor as context-param. application. The filter-class element specifies the fully qualified name for the filter class.

UpperCaseFilter and Double Filter:

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<filter>

<filter-name>

UpperCase Filter

</filter-name>

<filter-class>

UpperCaseFilter

</filter-class>

</filter>

<filter>

<filter-name>

Double Filter

</filter-name>

<filter-class>

DoubleFilter

</filter-class>

<init-param>

<param-name>frequency</param-name>

<param-value>1909</param-value>

</init-param>

Team-Fly ®

</filter>

</web-app>

filter-mapping

The filter-mapping element declares the filter mappings in the web application. A filter can be mapped either to a servlet or a URL pattern. Mapping a filter to a servlet causes the filter to work on the servlet. Mapping a filter to a URL pattern makes filtering occur to any resource whose URL matches the URL pattern. Filtering is performed in the same order as the appearance of filtermapping elements in the deployment descriptor.

The element descriptor for filter-mapping is as follows:

<!ELEMENT filter-mapping (filter-name, (url-pattern | servlet-name))>

<!ELEMENT filter-name (#PCDATA)>

<!ELEMENT url-pattern (#PCDATA)>

<!ELEMENT servlet-name (#PCDATA)>

The filter-name value must match one of the filter names declared in the filter elements.

The following is a deployment descriptor that contains two filter-mapping elements:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<!–– Define servlet-mapped and path-mapped filters ––>

<filter>

<filter-name>

Basic Filter

</filter-name>

<filter-class>

BasicFilter

</filter-class>

</filter>

<filter>

<filter-name>

Advanced Filter

</filter-name>

<filter-class>

AdvancedFilter

</filter-class>

</filter>

<!–– Define filter mappings for the defined filters ––>

<filter-mapping>

<filter-name>

Basic Filter

</filter-name>

<servlet-name>

FilteredServlet

</servlet-name>

</filter-mapping>

<filter-mapping>

<filter-name>

Advanced Filter

</filter-name>

339

<url-pattern>

/*

</url-pattern>

</filter-mapping>

</web-app>

listener

The listener element is used to register a listener class that you include in a web application. The listener element has the following element descriptor:

<!ELEMENT listener (listener-class)>

<!ELEMENT listener-class (#PCDATA)>

The following is a valid deployment descriptor containing a listener element:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<listener>

<listener-class>

AppLifeCycleEvent

</listener-class>

</listener>

</web-app>

servlet

The servlet element is used to declare a servlet. It has the following element descriptor:

<!ELEMENT servlet (icon?, servlet-name, display-name?, description?,

(servlet-class|jsp-file), init-param*, load-on-startup?, run-as?, security-role-ref*)>

<!ELEMENT servlet-name (#PCDATA)>

<!ELEMENT servlet-class (#PCDATA)>

<!ELEMENT jsp-file (#PCDATA)>

<!ELEMENT init-param (param-name, param-value, description?)>

<!ELEMENT load-on-startup (#PCDATA)>

<!ELEMENT run-as (description?, role-name)>

<!ELEMENT role-name (#PCDATA)>

The icon, display-name, and description elements are described in the previous sections. The initparam element descriptor is the same as context-param.

A servlet element must contain a servlet-name element and a servlet-class element, or a servletname element and a jsp-file element. The servlet-name element defines the name for that servlet and must be unique thoroughout the application.

The servlet-class element specifies the fully qualified class name of the servlet.

The jsp-file element specifies the full path to a JSP file within the application. The full path must begin with a /.

340

You use the init-param subelement to pass an initial parameter name and value to the servlet.

The load-on-startup element is used to load the servlet automatically into memory when the web container starts up. Loading a servlet means instantiating the servlet and calling its init method.

You use this element to avoid delay in the response for the first request to the servlet, caused by the servlet loading to memory. If this element is present and a jsp-file element is specified, the JSP file is precompiled into a servlet and the resulting servlet is loaded.

The content of a load-on-startup value is either empty or an integer number. The value indicates the order of loading into memory by the web container. For example, if there are two servlet elements and both contain load-on-startup subelements, the servlet with a lower number in the load-on-startup subelement is loaded first. If the value of the load-on-startup is empty or a negative number, it is up to the web container to decide when to load the servlet. If two servlets have the same value for their load-on-startup subelements, the web container is free to choose which servlet to load first.

If a run-as element is defined, it overrides the security identity used to call an Enterprise Java

Bean by that servlet in this web application. The role-name is one of the security roles defined for the current web application.

The security-role-ref element defines a mapping between the name of the role called from a servlet using isUserInRole(String name) and the name of a security role defined for the web application.

The security-role-ref element is described as follows:

<!ELEMENT security-role-ref (description?, role-name, role-link)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT role-name (#PCDATA)>

<!ELEMENT role-link (#PCDATA)>

The role-link element is used to link a security role reference to a defined security role. The rolelink element must contain the name of one of the security roles defined in the security-role elements.

For example, to map the security role reference "MG" to the security role with role-name

"manager," the syntax would be as follows:

<security-role-ref>

<role-name>MG</role-name>

<role-link>manager</manager>

</security-role-ref>

In this case, if the servlet called by a user belonging to the "manager" security role made the API call isUserInRole("MG"), the result would be true. The role-name "

*

" is not permitted because it has a special meaning for authorization constraints.

The following is a deployment descriptor containing several servlet elements:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>

First

341

</servlet-name>

<servlet-class>

FirstServlet

</servlet-class>

<load-on-startup>

1

</load-on-startup>

</servlet>

<servlet>

<servlet-name>

JDBCServlet

</servlet-name>

<servlet-class>

com.newriders.db.JDBCServlet

</servlet-class>

<load-on-startup>

2

</load-on-startup>

</servlet>

</web-app>

servlet-mapping

The servlet-mapping element maps a URL pattern to a servlet. The element descriptor for servletmapping is as follows:

<!ELEMENT servlet-mapping (servlet-name, url-pattern)>

<!ELEMENT servlet-name (#PCDATA)>

<!ELEMENT url-pattern (#PCDATA)>

The following is a deployment descriptor that maps a servlet with a URL pattern. For more details,

see the section " Servlet Alias and Mapping ," later in this chapter.

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>AnAlias</servlet-name>

<servlet-class>com.newriders.OtherServlet</servlet-class>

</servlet>

<!–– servlet mapping ––>

<servlet-mapping>

<servlet-name>AnAlias</servlet-name>

<url-pattern>/newURL</url-pattern>

</servlet-mapping>

</web-app>

session-config

The session-config element defines the parameters for the javax.servlet.http.HttpSession objects in the web application. The element descriptor is as follows:

<!ELEMENT session-config (session-timeout?)>

<!ELEMENT session-timeout (#PCDATA)>

342

The session-timeout element specifies the default session timeout interval in minutes. This value must be an integer. If the value of the session-timeout element is zero or a negative number, the session will never time out.

The following is a deployment descriptor that makes the default HttpSession object invalid 10 minutes after the last access from the user:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<session-config>

<session-timeout>

10

</session-timeout>

</session-config>

</web-app>

mime-mapping

The mime-mapping element maps a mime type to an extension. Its element decriptor is as follows:

<!ELEMENT mime-mapping (extension, mime-type)>

<!ELEMENT extension (#PCDATA)>

<!ELEMENT mime-type (#PCDATA)>

The extension element describes the extension, and mime-type is the MIME type. For example, the following deployment descriptor maps the extension "txt" to "text/plain":

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<mime-mapping>

<extension>

txt

</extension>

<mime-type>

text/plain

</mime-type>

</mime-mapping>

</web-app>

welcome-file-list

The welcome-file-list element specifies the default file that is displayed when the URL entered by the user in the browser does not contain a servlet name or a JSP page. For example, assume the user types in something like the following: http://www.yourdomain.com/appName/

343

If no welcome-file-list element is specified in the deployment descriptor for a web application, the user sees a permission error message or the list of files and directories in the application directory.

The welcome-file-list is described as follows:

<!ELEMENT welcome-file-list (welcome-file+)>

<!ELEMENT welcome-file (#PCDATA)>

The welcome-file subelement contains the default filename. A welcome-file-list element can contain one or more welcome-file subelements. If the file specified in the first welcome-file element cannot be found, the web container will try to display the second one, and so on.

The following is a deployment descriptor that contains a welcome-file-list element. The element contains two welcome-file elements. The first welcome-file specifies a file in the application directory called index.html; the second defines the welcome.html file under the src directory, which is under the application directory:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<welcome-file-list>

<welcome-file>

index.html

</welcome-file>

<welcome-file>

src/welcome.html

</welcome-file>

</welcome-file-list>

</web-app>

If the index.html file is not found in the application directory when a user types a URL that does not contain a servlet name or a JSP page or other resource, the welcome.html file in the src directory will be displayed.

error-page

The error-page element maps an error code or an exception type to a resource path in the web application, so that if a particular HTTP error or a specified Java exception occurs, the resource will be displayed instead. Its element descriptor is as follows:

<!ELEMENT error-page ((error-code | exception-type), location)>

<!ELEMENT error-code (#PCDATA)>

<!ELEMENT exception-type (#PCDATA)>

<!ELEMENT location (#PCDATA)>

The error-code element contains an HTTP error code, exception type is the fully qualified name of a Java exception type, and location is the path to the resource in the web application relative to the application directory. The value of location must start with a /.

For example, the following deployment descriptor causes the web container to display the error.html page in the application directory every time the HTTP 404 error code occurs:

<?xml version="1.0" encoding="ISO-8859-1"?>

344

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<error-page>

<error-code>

404

</error-code>

<location>

/error.html

</location>

</error-page>

</web-app>

taglib

The taglib element describes a JSP custom tag library. The taglib element is described as follows:

<!ELEMENT taglib (taglib-uri, taglib-location)>

<!ELEMENT taglib-uri (#PCDATA)>

<!ELEMENT taglib-location (#PCDATA)>

The taglib-uri element is the URI of the tag library used in the web application. The value for taglib-uri is relative to the location of the deployment descriptor.

The taglib-location contains the location where the TLD file for the tag library can be found.

The following is a deployment descriptor that contains taglib elements:

<?xml version="1.0" encoding="ISO-8859-1" ?>

<!DOCTYPE taglib

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<taglib>

<taglib-uri>

http://java.apache.org/tomcat/examples-taglib

</taglib-uri>

<taglib-location>

/WEB-INF/jsp/example-taglib.tld

</taglib-location>

</taglib>

</web-app>

resource-env-ref

You use the resource-env-ref element to specify a declaration of a servlet's reference to an administered object associated with a resource in the servlet's environment. The element descriptor of resource-env-ref is as follows:

<!ELEMENT resource-env-ref (description?, resource-env-ref-name, resource-env-ref-type)>

<!ELEMENT resource-env-ref-name (#PCDATA)>

<!ELEMENT resource-env-ref-type (#PCDATA)>

345

The resource-env-ref-name is the name of a resource environment reference whose value is the entry name of the environment used in servlet code. The name is a Java Naming and Directory

Interface (JNDI) name relative to the java:comp/env context and must be unique throughout the web application. resource-env-ref-type defines the type of a resource environment reference. Its value must be the fully qualified name of a Java class or interface.

As an example, the following deployment descriptor contains a resource-env-ref element:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<resource-env-ref>

<resource-env-ref-name>jms/XQueue</resource-env-ref-name>

<resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>

</resource-env-ref>

</web-app>

resource-ref

The resource-ref element specifies a declaration of a servlet's reference to an external resource. Its element descriptor is as follows:

<!ELEMENT resource-ref (description?, res-ref-name, res-type, resauth, res-sharing-scope?)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT res-ref-name (#PCDATA)>

<!ELEMENT res-type (#PCDATA)>

<!ELEMENT res-auth (#PCDATA)>

<!ELEMENT res-sharing-scope (#PCDATA)>

The subelements of resource-ref are described as follows:

• res-ref-name is the name of the resource factory reference name. The name is a JNDI name relative to the java:comp/env context. The name must be unique throughout the web application. res-auth indicates whether the servlet code signs on programmatically to the resource manager or whether the Container will sign on to the resource manager on the servlet's behalf. The value of this element must be either Application or Container. res-sharing-scope indicates whether connections obtained through the given resource manager connection factory reference can be shared. The value of this element must be either Shareable (default) or Unshareable.

The following is a deployment descriptor that contains a resource-ref element:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

346

<web-app>

<resource-ref>

<description>JDBC Data Source</description>

<res-ref-name>db/JDBCDatabase</res-ref-name>

<res-type>javax.sql.DataSource</res-type>

<res-auth>Application</res-auth>

<res-sharing-scope>Unshareable</res-sharing-scope>

</resource-ref>

</web-app>

security-constraint

The security-constraint in the deployment descriptor allows you to restrict access to certain resources without programming. To use this element, you should understand some security terms discussed in

Chapter 14 , "Security Configuration."

The security-constraint element is described as follows:

<!ELEMENT security-constraint (display-name?, web-resourcecollection+, auth-constraint?, user-data-constraint?)>

<!ELEMENT display-name (#PCDATA)>

<!ELEMENT web-resource-collection (web-resource-name, description?, url-pattern*, http-method*)>

<!ELEMENT auth-constraint (description?, role-name*)>

<!ELEMENT user-data-constraint (description?, transport-guarantee)>

The web-resource-collection element identifies a subset of resources to which access needs to be restricted. In the web-resource-collection, you can define the URL pattern(s) and the HTTP method. If no HTTP method is present, the security constraint applies to all methods.

The auth-constraint element specifies the user roles that should have access to this resource collection. If no auth-constraint element is specified, the security constraint applies to all roles.

The user-data-constraint element is used to indicate how data transmitted between the client and web container must be protected.

The description of the web-resource-collection element is shown as follows:

<!ELEMENT web-resource-collection (web-resource-name, description?, url-pattern*, http-method*)>

<!ELEMENT web-resource-name (#PCDATA)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT url-pattern (#PCDATA)>

<!ELEMENT http-method (#PCDATA)>

The web-resource-name is a name associated with the protected resource.

The http-method element can be assigned one of the HTTP methods, such as GET and POST.

The description of the auth-constraint element is shown here:

<!ELEMENT auth-constraint (description?, role-name*)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT role-name (#PCDATA)>

347

The role-name element contains the name of a security role.

The description of the user-data-constraint element is given here:

<!ELEMENT user-data-constraint (description?, transport-guarantee)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT transport-guarantee (#PCDATA)>

The transport-guarantee element must have one of the following values: NONE, INTEGRAL, or

CONFIDENTIAL. NONE means that the application does not require transport guarantees.

INTEGRAL means that the data between the server and the client should be sent in such a way that it can't be changed in transit. CONFIDENTIAL means that the data transmitted must be encrypted. In most cases, Secure Sockets Layer (SSL) is used for either INTEGRAL or

CONFIDENTIAL.

The following is a deployment descriptor that restricts access to any resource with a URL matching the pattern /servlet/

*

. Only a user in a manager role will be allowed access. The loginconfig element will require a user to log in and the Basic authentication method is used. The user must then enter the user name and password of the manager role to successfully log in:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<security-constraint>

<web-resource-collection>

FL

<web-resource-name>

Restricted Area

</web-resource-name>

<url-pattern>/servlet/*</url-pattern>

<auth-constraint>

TE

<role-name>manager</role-name>

</auth-constraint>

AM

</security-constraint>

<login-config>

<auth-method>BASIC</auth-method>

<realm-name>User Basic Authentication</realm-name>

</login-config>

</web-app>

login-config

The login-config element is used to specify the authentication method used, the realm name, and the attributes needed by the form login mechanism. Its element descriptor is as follows:

<!ELEMENT login-config (auth-method?, realm-name?, form-loginconfig?)>

<!ELEMENT auth-method (#PCDATA)>

<!ELEMENT realm-name (#PCDATA)>

<!ELEMENT form-login-config (form-login-page, form-error-page)>

The auth-method specifies the authentication method. Its value is one of the following: BASIC,

DIGEST, FORM, or CLIENT-CERT.

Team-Fly ®

The realm name element specifies the realm name to use in HTTP Basic authorization.

The form-login-config element specifies the login and error pages that should be used in formbased login. If form-based authentication is not used, these elements are ignored.

The form-login-config element is further elaborated as follows:

<!ELEMENT form-login-config (form-login-page, form-error-page)>

<!ELEMENT form-login-page (#PCDATA)>

<!ELEMENT form-error-page (#PCDATA)>

The form-login-page element specifies a path to a resource that displays a Login page. The path must start with a / and is relative to the application directory.

The form-error-page element specifies a path to a resource that displays an error page when user login fails. The path must begin with a / and is relative to the application directory.

security-role

The security-role element specifies the declaration of a security role used in the securityconstraints. It is described as follows:

<!ELEMENT security-role (description?, role-name)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT role-name (#PCDATA)>

The following deployment descriptor illustrates the use of the security-role element:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<security-role>

<role-name>manager</role-name>

</security-role>

</web-app>

env-entry

The env-entry element specifies an application environment entry. This element is described using the following descriptor:

<!ELEMENT env-entry (description?, env-entry-name, env-entry-value?, env-entry-type)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT env-entry-name (#PCDATA)>

<!ELEMENT env-entry-value (#PCDATA)>

<!ELEMENT env-entry-type (#PCDATA)>

The env-entry-name element contains the name of a web application's environment entry. The name is a JNDI name relative to the java:comp/env context. The name must be unique throughout the application.

349

The env-entry-value element contains the value of a web application's environment entry. The value must be a String that is valid for the constructor of the specified type that takes a single

String parameter—or for java.lang.Character, a single character.

The env-entry-type element contains the fully qualified Java type of the environment entry value that is expected by the web application's code. This element must have one of the following values: java.lang.Boolean java.lang.Byte java.lang.Character java.lang.String java.lang.Short java.lang.Integer java.lang.Long java.lang.Float java.lang.Double

The ejb-ref element specifies a reference to an Enterprise JavaBean's home. Its descriptor is as follows:

<!ELEMENT ejb-ref (description?, ejb-ref-name, ejb-ref-type, home, remote, ejb-link?)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT ejb-ref-name (#PCDATA)>

<!ELEMENT ejb-ref-type (#PCDATA)>

<!ELEMENT home (#PCDATA)>

<!ELEMENT remote (#PCDATA)>

<!ELEMENT ejb-link (#PCDATA)>

The ejb-ref-name element contains the name of an EJB reference. The EJB reference is an entry in the servlet's environment and is relative to the java:comp/env context. The name must be unique within the web application. Its name is recommended to begin with "ejb/".

The ejb-ref-type element contains the expected type of the referenced enterprise bean. The value of the ejb-ref-type element must be either Entity or Session.

The home element contains the fully qualified name of the enterprise bean's home interface.

The remote element contains the fully qualified name of the enterprise bean's remote interface.

The ejb-link element is used in the ejb-ref or ejb-local-ref elements to specify that an EJB reference is linked to another enterprise bean.

The value of the ejb-link element must be the ejb-name of an enterprise bean in the same J2EE application unit.

The name in the ejb-link element may be composed of a path name specifying the ejb-jar containing the referenced enterprise bean. The ejb-name of the target bean has been appended and separated from the path name by using #. The path name is relative to the WAR containing the web application that is referencing the enterprise bean. This allows multiple enterprise beans with the same ejb-name to be identified uniquely.

The ejb-local-ref element is used for the declaration of a reference to an enterprise bean's local home. It is described as follows:

350

<!ELEMENT ejb-local-ref (description?, ejb-ref-name, ejb-ref-type, local-home, local, ejb-link?)>

<!ELEMENT description (#PCDATA)>

<!ELEMENT ejb-ref-name (#PCDATA)>

<!ELEMENT ejb-ref-type (#PCDATA)>

<!ELEMENT local-home (#PCDATA)>

<!ELEMENT local (#PCDATA)>

<!ELEMENT ejb-link (#PCDATA)>

The local element contains the fully qualified name of the enterprise bean's local interface.

The local-home element contains the fully qualified name of the enterprise bean's local home interface.

Servlet Alias and Mapping

With Tomcat, you actually don't need a deployment descriptor for a servlet. Consider the following directory structure given in

Figure 16.3

. This is the structure for a web application

called myApp.

Figure 16.3. The directory structure for myApp.

As long as you put your servlet class file under the classes directory under myApp, your servlet should be accessible from the following URL: http://domain/myApp/servlet/ServletClassName

.

For instance, if your servlet is called TestingServlet and your domain name is www.blahblahblah.com

, the URL to the servlet is the following: http://www.blahblahblah.com/myApp/servlet/TestingServlet

Note

Note that the servlet is accessed through the default port 8080.

Appendix A provides

information on how to make your servlet work on a non-default port.

The previous URL assumes that the servlet is not contained in a package. If the servlet is part of a package, you must store your class file under a directory structure that reflects the Java package.

For example, the following servlet called OtherServlet is part of the package com.newriders.

First, you need the directory structure given in Figure 16.4

. The OtherServlet class file must be

stored in the newriders directory.

351

Figure 16.4. The directory structure for a servlet in a package.

The servlet then can be accessed using the following URL: http://domain/myApp/servlet/com.newriders.OtherServlet

You can see that the package name is reflected in the URL; however, the deployment descriptor allows you to call your servlet by another name. This simply means you can make your servlet available with a non-standard URL.

For example, the deployment descriptor in

Listing 16.1

creates an alias called AnAlias for

com.newriders.OtherServlet.

Listing 16.1 The Deployment Descriptor that Provides an Alias

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>AnAlias</servlet-name>

<servlet-class>com.newriders.OtherServlet</servlet-class>

</servlet>

</web-app>

In the deployment descriptor, first you define a name (AnAlias) for the servlet com.newriders.OtherServlet. Then your servlet is available from both of the following URLs: http://domain/myApp/servlet/com.newriders.OtherServlet http://domain/myApp/servlet/AnAlias

In the preceding example, the URL still must contain the word "servlet," even though you can choose your own name. With servlet-mapping, you can remove the word "servlet" from the URL.

The next example shows you how to create a different URL for the previous servlet

(com.newriders.OtherServlet) using the deployment descriptor in

Listing 16.2

.

Listing 16.2 The Deployment Descriptor that Provides Mapping

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

352

<web-app>

<servlet>

<servlet-name>AnAlias</servlet-name>

<servlet-class>com.newriders.OtherServlet</servlet-class>

</servlet>

<!–– mapping ––>

<servlet-mapping>

<servlet-name>AnAlias</servlet-name>

<url-pattern>/newURL</url-pattern>

</servlet-mapping>

</web-app>

Now, you can access your servlet using the following three URLs: http://localhost:8080/myApp/servlet/com.newriders.OtherServlet http://localhost:8080/myApp/servlet/AnAlias http://localhost:8080/myApp/newURL

Note that the word "servlet" disappears in the third URL.

The URL pattern can go beyond a simple word. For example, to give the impression that the class file is in a subdirectory, consider the deployment descriptor in

Listing 16.3

.

Listing 16.3 The Deployment Descriptor that Uses a More Complex Map

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>AnAlias</servlet-name>

<servlet-class>com.newriders.OtherServlet</servlet-class>

</servlet>

<!–– mapping ––>

<servlet-mapping>

<servlet-name>AnAlias</servlet-name>

<url-pattern>/newURL/level-1/level-2</url-pattern>

</servlet-mapping>

</web-app>

Now you can use the following URL to access your servlet: http://domain/myApp/newURL/level-1/level-2

Note also that you can use the wild-card character

*

to indicate that you accept anything. For example, the URL pattern /whatever/

*

will make your servlet accessible with any URL that ends with /whatever/, such as: http://domain/myApp/whatever/noname http://domain/myApp/whatever/favorite

JSP Alias and Mapping

353

With a JSP application, you have a similar directory structure as that of a servlet application.

Consider a JSP application named myJSPApp. This application has the directory structure given in

Figure 16.5

.

Figure 16.5. The directory structure for a JSP application called myJSPApp.

You store your JSP files in the myJSPApp directory and additional class files under the WEB-

INF/classes directory. The JSP page then is callable using the following URL: http://domain/appName/pageName

This means that if your domain and domain name is www.blahblahblah.com

, your application name is myJSPApp, and the page is called SimplePage.jsp, once you register your application in the server.xml file (see

Appendix A ), the URL to access the page is as follows:

http://www.blahblahblah.com/myJSPApp/SimplePage.jsp

If you don't have a JavaBean and tag library, you don't even need the WEB-INF file. If you are happy with the URL to access your JSP page, you don't need a deployment descriptor, either.

Using a deployment descriptor, however, you can configure your application. Among other things, you can create an alias so that you can access your JSP page with another name.

For example, the following is a deployment descriptor that provides an alias for a JSP page called

SimplePage.jsp:

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<servlet>

<servlet-name>

AnAlias

</servlet-name>

<jsp-file>

/SimplePage.jsp

</jsp-file>

<load-on-startup>1</load-on-startup>

</servlet>

</web-app>

Note

Having a web application that consists of both servlets and JSP pages as well as other resources is very common. In this case, servlet classes and JSP pages can be stored in their own directories without affecting each other.

354

Packaging and Deploying a Web Application

You can deploy an application with the directory structure explained in the previous section.

There is a more elegant way for deploying your application, however; you can first package your application into a web archive (WAR) file. A web archive file has a .war extension.

Basically, a WAR file is a .jar file you create using the jar program. Into a WAR file, you package every file in an application. The name of the WAR file normally is the same as the application name; however, you can use any name you like.

After you have a WAR file, you deploy it under the webapps directory. You then can access your application just as you would an unpackaged application. The name used for your packaged application is the .war filename. For example, if you package an application called myApp into a

WAR file called dontcare.war, when deployed, the application name is dontcare, not myApp. This is the result because when you archive your application, the application name is not included in the WAR file.

Summary

This chapter explained to you how you can configure and deploy your web application. The chapter started by introducing the directory structure of a typical application and then moved to an explanation of the deployment descriptor.

After the application is ready for deployment, you can deploy it by retaining the files and directory structure of your application. Alternatively, you can package the application into a WAR file and deploy the whole application using a single file.

355

Chapter 17. Architecting Java Web Applications

Now that you know the techniques, tips, and tricks for working with servlets and JSP, it is time to look at the architectural designs of a Java web application. Two models are commonly used and this chapter explains them and shows why JSP does not make servlets obsolete. In fact, in complex applications, JSP pages and servlets go hand in hand.

The terms for the two architectural designs first appeared in the early drafts of the JSP specifications: Model 1 and Model 2. These two terms are not mentioned in the more current JSP specification documents. However, the designs are still widely in use today. The models are explained in the next two sections. Similar applications are given in both Model 1 and Model 2 to illustrate the models' differences.

Note

A project based on Model 2 application is presented in

Chapter 18 , "Developing E-

Commerce Applications."

Model 1 Architecture

In Model 1 architecture, the application is page-centric. The client browser navigates through a series of JSP pages in which any JSP page can employ a JavaBean that performs business operations. However, the highlight of this architecture is that each JSP page processes its own input. Applications implementing this architecture normally have a series of JSP pages where the user is expected to proceed from the first page to the next. If needed, a servlet or an HTML page can be substituted for the JSP page in the series.

The Model 1 architecture is depicted in

Figure 17.1

.

Figure 17.1. Model 1 architecture.

Example of Model 1 Architecture: A Login Application

The following example is a Login application that uses the Model 1 architecture. It consists of three JSP pages and a JavaBean. As the name implies, this application is for users to log in. The sequence of this series of JSP applications starts from the Login.jsp page that is given in

Listing

17.1

Listing 17.1 Login.jsp

<%@ page session="false" %>

<HTML>

<HEAD>

<TITLE>Login</TITLE>

</HEAD>

356

<BODY>

<FORM METHOD="POST" ACTION="ProcessLogin.jsp">

<%

if (request.getParameter("error") != null) {

%>

Login failed. Please try again

<BR><HR>

<%

}

%>

<TABLE>

<TR>

<TD>User Name</TD>

<TD><INPUT TYPE=TEXT NAME="userName"></TD>

</TR>

<TR>

<TD>Password</TD>

<TD><INPUT TYPE=PASSWORD NAME="password"></TD>

</TR>

<TR>

<TD COLSPAN="2"><INPUT TYPE=SUBMIT VALUE="Login"></TD>

</TR>

</TABLE>

</FORM>

</BODY>

</HTML>

The Login.jsp page is nothing more than an HTML page with a form. The only code present is the scriplet after the <FORM> tag that checks to see if the request object contains a parameter called

"error". If so, a message is displayed.

<%

if (request.getParameter("error") != null) {

%>

Login failed. Please try again

<BR><HR>

<%

}

%>

The form in the Login page is submitted to the second JSP page—ProcessLogin.jsp, which is illustrated in

Listing 17.2

.

Listing 17.2 ProcessLogin.jsp

<%@ page session="false" %>

<jsp:useBean id="loginBean" scope="page" class="model1.LoginBean" />

<%

if (loginBean.login(request.getParameter("userName"),

request.getParameter("password")))

request.getRequestDispatcher("Welcome.jsp").forward(request, response);

else

//we have to use sendRedirect because we want to send the ?error part

//to the Login.jsp page.

//with RequestDispatcher.forward(), the URL will still be

//the current URL

response.sendRedirect("Login.jsp?error=yes");

%>

357

This page employs a JavaBean called model1.LoginBean. The ProcessLogin.jsp page calls the login method of the bean, passing the userName parameter and the password parameter of the request object. The login method returns true if the user is an authorized user. It returns false otherwise.

In a successful login the ProcessLogin.jsp page displays the Welcome page. if (loginBean.login(request.getParameter("userName"),

request.getParameter("password")))

request.getRequestDispatcher("Welcome.jsp").forward(request, response);

.

.

.

Note that rather than using the sendRedirect method of the javax.servlet.http.HttpServletResponse interface, use a request dispatcher obtained from the getRequestDispatcher method of the request object. Then, the RequestDispatcher object's forward method transfers processing to the

Welcome.jsp page. The forward method is faster than the sendRedirect method because there is no round trip to the client, such as with the sendRedirect method.

If the login failed, however, the user is sent back to the Login.jsp page. response.sendRedirect("Login.jsp?error=yes");

Y

In this example, the sendRedirect method of the javax.servlet.http.HttpServletResponse interface

FL

Model 2 Architecture ,"

later in this chapter.

The Welcome.jsp page is given in

Listing 17.3

.

AM

Listing 17.3 Welcome.jsp

TE

<%@ page session="false" %>

<HTML>

<HEAD>

<TITLE>Welcome</TITLE>

</HEAD>

<BODY>

Welcome. You have successfully logged in.

</BODY>

</HTML>

The JavaBean used in the ProcessLogin.jsp page is given in Listing 17.4

.

Listing 17.4 LoginBean.java

package model1; public class LoginBean {

public boolean login(String userName, String password) {

if (userName == null || password == null ||

!(userName.equals("aibo") && password.equals("kitada")))

return false;

else

return true;

Team-Fly ®

}

}

In the login method in the JavaBean, a successful login occurs if the userName equals "aibo" and the password is the same as "kitada". The login method is purposely very simple. In a real-life application, these two values are normally matched against a database table.

To test the application, complete the following steps:

1. Use the myJSPApp application.

2. Copy all the .jsp pages in the myJSPApp directory under webapps.

3. Compile the LoginBean.java and copy the .class file into the WEB-INF/classes/model1/ directory.

4. Restart Tomcat and load the Login page using the following URL: http://localhost:8080/myJSPApp/Login.jsp

.

This application is illustrated in Figures

17.2

to

17.4

.

Figure 17.2. The Login page.

Figure 17.3. The Welcome page.

359

Figure 17.4. The Login page after a failed login.

The Advantages and Disadvantages of Model 1 Architecture

The advantage of this model is its ease of development. This architectural design, therefore, is suitable for small projects, or when you want to quickly finish something.

Two disadvantages of this model are as follows:

360

It is hard to achieve division of labor between the page designer and the web developer because normally the web developer needs to be involved in the development of the page and the business objects.

Model 1 architecture is hard to maintain and it is not flexible. This is especially true for large projects.

Due to the drawbacks of this architectural design, Model 2 architecture was introduced.

Model 2 Architecture

The Model 2 architecture is basically a Model-View-Controller (MVC) architecture that separates content generation and content presentation. A Model 2 architecture is indicated by the presence of a controller servlet between the client browser and the JSP pages (or the servlets that present the content). The controller servlet dispatches HTTP requests to the corresponding presentation

JSP pages—based on the request URL, input parameters, and application state. In this model, presentation parts (JSP pages or servlets) are isolated from each other.

Model 2 applications are more flexible and easier to maintain, and to extend, because views do not reference each other directly. The Model 2 controller servlet provides a single point of control for security and logging, and often encapsulates incoming data into a form usable by the back-end

MVC model.

Warning

Unless you are sure that your small application will remain small, always elect Model 2 as the architectural design of your application. It is true that Model 2 architecture adds some complexity to the application. However, an MVC application framework can greatly simplify the implementation of a Model 2 application.

Figure 17.5

depicts the Model 2 architecture.

Figure 17.5. Model 2 architecture.

Example of Model 2 Application

To illustrate the use of Model 2 architecture, the following example is the rewrite of the previous

Login application described in the section "

Model 1 Architecture ."

At the center is the controller servlet, which is the single entry point of the application. The servlet is named Model2Servlet and is given in

Listing 17.5

.

Listing 17.5 The Model2Servlet

361

import javax.servlet.*; public class Model2Servlet extends GenericServlet {

public void service(ServletRequest request, ServletResponse response)

throws ServletException, java.io.IOException {

String userName = request.getParameter("userName");

String password = request.getParameter("password");

if (userName == null) {

RequestDispatcher rd = request.getRequestDispatcher("/Login.jsp");

rd.forward(request, response);

}

else {

if (password != null && userName.equals("aibo")

&& password.equals("kitada")) {

// login successful

RequestDispatcher rd = request.getRequestDispatcher("/Welcome.jsp");

rd.forward(request, response);

}

else {

// login failed

request.setAttribute("error", "yes");

RequestDispatcher rd = request.getRequestDispatcher("/Login.jsp");

rd.forward(request, response);

}

}

}

}

The application is very simple because there are only two JSP pages for presentation: the Login page and the Welcome page. The Login page is used for the user to log in, and the Welcome page is displayed after a successful login. Therefore, the servlet dispatches the request either to the

Login page or to the Welcome page.

However, how does the servlet know what JSP page to dispatch to? The answer lies in the logic inside the service method of the servlet.

The service method checks for a parameter called userName in the ServletRequest object.

Absence of this parameter results in the servlet dispatching the request to the Login page. if (userName == null) {

RequestDispatcher rd = request.getRequestDispatcher("/Login.jsp");

rd.forward(request, response);

}

Therefore, the first time the user requests a page from the application, the Login page displays because there is no userName parameter in the request.

If the userName parameter is present, the controller servlet knows that the user is trying to log in.

The servlet then checks to see if the username is "aibo" and the password is "kitada". If so, the servlet dispatches the request to the Welcome.jsp page. if (password != null && userName.equals("aibo") &&

362

password.equals("kitada")) {

// login successful

RequestDispatcher rd = request.getRequestDispatcher("/Welcome.jsp");

rd.forward(request, response);

}

Otherwise, it returns the user to the Login page after setting an attribute called error in the

ServletRequest object. The presence of this attribute makes the Login.jsp page display an error message.

The Login.jsp and Welcome.jsp are given in Listings

17.6

and 17.7

respectively.

Listing 17.6 Login Page

<%@ page session="false" %>

<HTML>

<HEAD>

<TITLE>Login</TITLE>

</HEAD>

<BODY>

<FORM METHOD="POST">

<%

if (request.getAttribute("error") != null) {

%>

Login failed. Please try again

<BR><HR>

<%

}

%>

<TABLE>

<TR>

<TD>User Name</TD>

<TD><INPUT TYPE=TEXT NAME="userName"></TD>

</TR>

<TR>

<TD>Password</TD>

<TD><INPUT TYPE=PASSWORD NAME="password"></TD>

</TR>

<TR>

<TD COLSPAN="2"><INPUT TYPE=SUBMIT VALUE="Login"></TD>

</TR>

</TABLE>

</FORM>

</BODY>

</HTML>

Listing 17.7 Welcome Page

<%@ page session="false" %>

<HTML>

<HEAD>

<TITLE>Welcome</TITLE>

</HEAD>

<BODY>

Welcome. You have successfully logged in.

</BODY>

</HTML>

To test this application, complete the following steps:

363

1. Copy Login.jsp and Welcome.jsp to the myJSPApp directory.

2. Compile the servlet and copy the .class file into the WEB-INF/classes directory.

3. Restart Tomcat and type the following in the browser: http://localhost:8080/myJSPApp/servlet/Model2Servlet

Summary

This chapter briefly explains the two models of Java web application design: Model 1 and Model

2. Model 1 architecture provides rapid development for small projects, and is suitable for small projects that will remain small or for building prototypes. Model 2 is the recommended architecture for any medium-sized to large projects. Model 2 is harder to build, but it provides more maintainability and extensibility.

Chapter 18 presents an e-commerce application that is built based on Model 2 architectural design.

364

Chapter 18. Developing E-Commerce Applications

In

Chapter 17 , "Architecting Java Web Applications," you learned that there are two design

models you can adopt to build Java web applications with servlets and JSP. The first model, simply called Model 1, is a page-centric model in which an application consists of a series of JSP pages. In this model, a JSP page calls another JSP page. Developing applications based on this model is very easy; however, for complex applications, this model presents maintenance nightmares. Therefore, this model is suitable only for small applications that will never grow in complexity.

The second model, Model 2, is a Model-View-Controller (MVC) architecture that separates content generation and content presentation. A Model 2 architecture is indicated by the presence of a controller servlet between the client browser and the JSP pages or servlet content that presents the content. The controller servlet dispatches HTTP requests to the corresponding presentation

JSP pages based on the request URL, input parameters, and application state. In this model, presentation parts (JSP pages or servlets) are isolated from each other.

Model 2 applications are more flexible and easier to maintain and extend because views do not reference each other directly. The Model 2 controller servlet provides a single point of control for security and logging, and often encapsulates incoming data into a form usable by the back-end

MVC model.

Model 2 architecture is recommended for complex applications. Building an application using this model is not as simple as using Model 1; however, this model offers many advantages over the first model. In this chapter, you see how this model is used in an e-commerce application that implements an online store.

The project is called Burnaby (named after the city east of Vancouver, British Columbia), and it is an online store that sells foods in many different categories. Here you can find chocolate, biscuits, milk, cheese, and other things you normally might find in a superstore. The project's sole purpose is to demonstrate how Model 2 applications can be designed and developed. For brevity and clarity, little or no error handling has been included and no optimization is used. The graphic design also is kept simple. A Microsoft Access database accompanies this project and is ready to use if you happen to be using Windows. Otherwise, you can build your own database based on the database structure given in the section, "

The Database Structure ," with any favorite database

server, as long as there is a JDBC driver for that database server.

Project Specification

If you have shopped online or browsed an electronic store such as Amazon.com

, you will easily understand the specification for this project.

Loosely defined, the application you will be building is an online store users can visit and do the following things:

Search for certain products based on product names or descriptions

Browse the list of products by category

View a product's details

Place a product in the shopping cart

View and edit the shopping cart

365

Check out and place an order

The Database Structure

For simplicity, a Microsoft Access database is used as the example in this chapter. For deployment, however, you are encouraged to port it in a more scalable and powerful database. The Access database file is located in the \db directory under the application's WEB-INF directory. You use four tables for this project: Categories, Products, Orders, and OrderDetails. The structure of each table is given next.

The Categories Table

The Categories table is used to store product categories. It is a simple table whose design is given in

Table 18.1

.

Table 18.1. The Structure of the Categories Table

Column Name Data Type

CategoryId AutoNumber

Category Text

The Products Table

The Products table is used to store the details of every product sold. Its structure is presented in

Table 18.2

. Note that the table uses a CategoryId column to categorize the products.

Table 18.2. The Structure of the Products Table

Column Name Data Type

ProductId AutoNumber

CategoryId Number

Name Text

Description Text

Price Number

The Orders Table

The Orders table holds order information, including the delivery address, the credit card details, and the contact name. A unique identifier is used for each order, which is used to link to all shopping items in the OrderDetails table.

The structure of the Orders table is given in Table 18.3

.

Table 18.3. The Structure of the Orders Table

Column Name Data Type

OrderId Number

ContactName Text

DeliveryAddress Text

366

CCName Text

CCNumber Text

CCExpiryDate Text

The OrderDetails Table

The OrderDetails table is used to store all shopping items for each order. Its structure is given in

Table 18.4

.

Table 18.4. The Structure of the OrderDetails Table

Column Name Data Type

Id AutoNumber

OrderId Number

ProductId Number

Quantity Number

Price Number

Page Design

For consistency in the look and feel of the application, every JSP page uses the same design.

There is a header on top of each page and a menu on the left. Every page has the following structure:

<HTML>

<BODY>

<TABLE>

<TR>

<!–– header ––>

</TR>

<TR>

<TD VALIGN="TOP">

<!–– menu ––>

</TD>

<TD VALIGN="TOP">

<!–– page content––>

</TD>

</TR>

</TABLE>

</BODY>

</HTML>

Preparation

Before you start coding, you need to do these steps in preparation:

367

1. Copy the directory Burnaby and its content from the software/burnaby directory on the

CD to %CATALINA_HOME%/webapps/. The directory structure of the application is shown in

Figure 18.1

.

Figure 18.1. The application directory structure.

2. Create a DSN name called Burnaby for the Microsoft Access database. Or, if you are using a different database, make sure that the JDBC driver for the database can be found and loaded by the JVM.

3. Edit the server.xml file, which is the server configuration file located in the conf directory under %CATALINA_HOME%. Open the file with your text editor and look for something like the following:

reloadable="true">

.

.

.

FL

</Context> reloadable="true">

</Context>

Application Design

The application consists of a controller servlet that receives all the requests and forwards each request to one of the JSP pages. The architecture is shown in

Figure 18.2

.

Figure 18.2. The application architecture.

Figures

18.3

to

18.8

show the user interface of the Burnaby project.

Team-Fly ®

Figure 18.3. The Default page.

Figure 18.4. The SearchResults page.

Figure 18.5. The BrowseCatalog page.

369

Figure 18.6. The ProductDetails page.

Figure 18.7. The Shopping Cart page.

370

Figure 18.8. The Checkout page.

Building the Project

371

The following section discusses the files that make up the application, starting with the deployment descriptor and continuing with the controller servlet. The section then discusses each of the JSP pages and other classes in detail.

The Deployment Descriptor

One of the files included in the Burnaby directory is the deployment descriptor (web.xml). This file can be found in the WEB-INF directory. In this web.xml file, you specify several initial parameters that will become global variables in the servlet/JSP pages. These global variables are loaded into the ServletContext object when the servlet is initialized. The deployment descriptor is given in

Listing 18.1

.

Listing 18.1 Web.xml File

<?xml version="1.0" encoding="ISO-8859-1"?>

<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>

<!–– Define the controller servlet ––>

<servlet>

<servlet-name>ControllerServlet</servlet-name>

<servlet-class>ControllerServlet</servlet-class>

<!–– Define initial parameters that will be loaded into

the ServletContext object in the controller servlet —>

<init-param>

<param-name>base</param-name>

<paramvalue>http://localhost:8080/burnaby/servlet/ControllerServlet</paramvalue>

</init-param>

<init-param>

<param-name>jdbcDriver</param-name>

<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>

</init-param>

<init-param>

<param-name>imageUrl</param-name>

<param-value>http://localhost:8080/burnaby/images/</paramvalue>

</init-param>

<init-param>

<param-name>dbUrl</param-name>

<param-value>jdbc:odbc:Burnaby</param-value>

</init-param>

<init-param>

<param-name>dbUserName</param-name>

<param-value></param-value>

</init-param>

<init-param>

<param-name>dbPassword</param-name>

<param-value></param-value>

</init-param>

</servlet>

</web-app>

The following list describes each initial parameter:

372

base. The URL of the controller servlet that will be used in the HREF attribute of a hyperlink or the ACTION attribute of an HTML form in the JSP pages. For example, base will have the following value if you are using Tomcat on the local machine on port 8080: http://localhost:8080/burnaby/servlet/ControllerServlet

When deploying the application, replace "localhost:8080" with your domain name.

jdbcDriver. The JDBC driver used to access the database.

imageUrl. The URL where images are located.

dbUrl. The database URL used when opening a java.sql.Connection object.

dbUserName. The username used when opening a java.sql.Connection object.

dbPassword. The password used when opening a java.sql.Connection object.

The Controller Servlet

The controller servlet is contained in the ControllerServlet.java file in the burnaby/src directory

and is given in Listing 18.2

.

Listing 18.2 ControllerServlet

import java.sql.*; import javax.servlet.*; import javax.servlet.http.*; import java.io.*; import java.util.*; import com.brainysoftware.burnaby.DbBean; public class ControllerServlet extends HttpServlet {

/**Initialize global variables*/

public void init(ServletConfig config) throws ServletException {

System.out.println("initializing controller servlet.");

ServletContext context = config.getServletContext();

context.setAttribute("base", config.getInitParameter("base"));

context.setAttribute("imageUrl", config.getInitParameter("imageUrl"));

// instantiating the DbBean

DbBean dbBean = new DbBean();

// initialize the DbBean's fields

dbBean.setDbUrl(config.getInitParameter("dbUrl"));

dbBean.setDbUserName(config.getInitParameter("dbUserName"));

dbBean.setDbPassword(config.getInitParameter("dbPassword"));

// put the bean in the servlet context

// the bean will be accessed from JSP pages

context.setAttribute("dbBean", dbBean);

try {

// loading the database JDBC driver

Class.forName(config.getInitParameter("jdbcDriver"));

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

373

super.init(config);

}

/**Process the HTTP Get request*/

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

doPost(request, response);

}

/**Process the HTTP Post request*/

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String base = "/jsp/";

String url = base + "Default.jsp";

String action = request.getParameter("action");

if (action != null) {

if (action.equals("search"))

url = base + "SearchResults.jsp";

else if (action.equals("browseCatalog"))

url = base + "BrowseCatalog.jsp";

else if (action.equals("productDetails"))

url = base + "ProductDetails.jsp";

else if (action.equals("productDetails"))

url = base + "ProductDetails.jsp";

else if (action.equals("addShoppingItem") ||

action.equals("updateShoppingItem") ||

action.equals("deleteShoppingItem") ||

action.equals("displayShoppingCart"))

url = base + "ShoppingCart.jsp";

else if (action.equals("checkOut"))

url = base + "CheckOut.jsp";

else if (action.equals("order"))

url = base + "Order.jsp";

}

RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(url);

requestDispatcher.forward(request, response);

}

}

As you can see from Listing 18.2

, the two important methods are init and doPost. The init method does the following things:

Reads initial parameters from the deployment descriptor and initializes global variables for the whole application, as follows:

ServletContext context = config.getServletContext(); context.setAttribute("base", config.getInitParameter("base")); context.setAttribute("imageUrl", config.getInitParameter("imageUrl"));

Instantiates the DbBean JavaBean and puts it in the servlet context object:

// instantiating the DbBean

DbBean dbBean = new DbBean();

// initialize the DbBean's fields

dbBean.setDbUrl(config.getInitParameter("dbUrl"));

374

• dbBean.setDbUserName(config.getInitParameter("dbUserName")); dbBean.setDbPassword(config.getInitParameter("dbPassword"));

// put the bean in the servlet context

// the bean will be accessed from JSP pages

context.setAttribute("dbBean", dbBean);

This bean can be accessed from the JSP pages using the following useBean tag.

<jsp:useBean id="dbBean" scope="application" class="com.brainysoftware.burnaby.DbBean"/>

Loads the JDBC driver for the database, as follows: try {

// loading the database JDBC driver

Class.forName(config.getInitParameter("jdbcDriver"));

}

catch (ClassNotFoundException e) {

System.out.println(e.toString());

}

The doPost method controls the application by forwarding requests to corresponding JSP pages based on the value of the action parameter. Requests are forwarded to JSP pages using the forward method of the RequestDispatcher object, as follows:

RequestDispatcher requestDispatcher =

getServletContext().getRequestDispatcher(url); requestDispatcher.forward(request, response);

Supporting Classes

Two supporting classes are used for this project. The first one is the Product class that represents a product in the shopping application. The second one, the ShoppingItem class, represents a shopping item. Both classes are similar except that the Product class does not have a quantity field.

The Product class and the ShoppingItem class are given in Listings 18.3

and 18.4

, respectively.

Listing 18.3 Product.java

package com.brainysoftware.burnaby; public class Product {

public int id;

public String name;

public String description;

public double price;

}

Listing 18.4 ShoppingItem.java

package com.brainysoftware.burnaby; public class ShoppingItem {

public int productId;

375

public String name;

public String description;

public double price;

public int quantity;

}

Included Files

Every JSP page has the same design—the header and the menu on the left of the page. The header is represented by the Header.jsp file, and the menu by the Menu.jsp file. These files are given in

Listings

18.5

and 18.6

, respectively.

Listing 18.5 Header.jsp

<%

String base = (String) application.getAttribute("base");

String imageUrl = (String) application.getAttribute("imageUrl");

%>

<TABLE WIDTH="740" CELLPADDING="0"

HEIGHT="75" CELLSPACING="0" BORDER="0">

<TR>

<TD ALIGN="left" BGCOLOR="F6F6F6">

<FONT FACE="Verdana" SIZE="4">Burnaby e-Mall</FONT>

</TD>

<TD ALIGN="RIGHT" BGCOLOR="F6F6F6">

<A HREF="<%=base%>?action=displayShoppingCart"><IMG

BORDER="0" SRC="<%=(imageUrl + "cart.gif")%>"></A>

&nbsp;&nbsp;&nbsp;

</TD>

</TR>

</TABLE>

The first four lines of the code obtain the base and imageUrl attributes from the ServletContext object, which in a JSP page is represented by the application implicit, as you see here:

<%

String base = (String) application.getAttribute("base");

String imageUrl = (String) application.getAttribute("imageUrl");

%>

The base and imageUrl variables are used to compose the link to the shopping cart, as follows:

<A HREF="<%=base%>?action=displayShoppingCart"><IMG

BORDER="0" SRC="<%=(imageUrl + "cart.gif")%>"></A>

Listing 18.6 Menu.jsp

<%@ page import="java.util.*" %>

<jsp:useBean id="dbBean" scope="application" class="com.brainysoftware.burnaby.DbBean"/>

<%

String base = (String) application.getAttribute("base");

%>

<TABLE CELLSPACING="0" CELLPADDING="5" WIDTH="150" BORDER="0">

<TR>

<TD BGCOLOR="F6F6F6">

<FONT FACE="Verdana">Search</FONT>

376

<FORM>

<INPUT TYPE="HIDDEN" NAME="action" VALUE="search">

<INPUT TYPE="TEXT" NAME="keyword" SIZE="10">

<INPUT type="SUBMIT" VALUE="Go">

</FORM>

</TD>

</TR>

<TR>

<TD BGCOLOR="F6F6F6"><FONT FACE="Verdana">Categories:</FONT></TD>

</TR>

<TR VALIGN="TOP">

<TD BGCOLOR="F6F6F6">

<%

Hashtable categories = dbBean.getCategories();

Enumeration categoryIds = categories.keys();

while (categoryIds.hasMoreElements()) {

Object categoryId = categoryIds.nextElement();

out.println("<A HREF=" + base +

"?action=browseCatalog&categoryId=" + categoryId.toString() + ">" +

categories.get(categoryId) +

"</A><BR>");

}

%>

</TD>

</TR>

</TABLE>

The Menu.jsp page includes a form that allows the user to search for certain products. The form also retrieves all records from the Categories table and displays them as clickable links to the

BrowseCatalog page. Retrieving the categories is done through a bean whose class is com.brainysoftware.burnaby.DbBean. This bean has an application scope shown here:

<jsp:useBean id="dbBean" scope="application"

class="com.brainysoftware.burnaby.DbBean"/>

The Default Page

The main page of this application is the Default.jsp page. Any request that does not carry an action parameter or any request whose "action" parameter's value is invalid will be forwarded to this page. This page simply displays a welcome message that is given in

Listing 18.7

.

Listing 18.7 Default.jsp

<HTML>

<HEAD>

<TITLE>Welcome</TITLE>

</HEAD>

<BODY>

<TABLE>

<TR>

<TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>

</TR>

<TR>

<TD><jsp:include page="Menu.jsp" flush="true"/></TD>

<TD VALIGN="TOP">

<H2>Welcome to Burnaby E-Mall.</H2>

</TD>

377

</TR>

</TABLE>

</BODY>

</HTML>

The SearchResults Page

The Menu.jsp page contains a search form and a number of hyperlinks to enable catalog browsing.

When submitted, the search form will be forwarded to the SearchResults.jsp page, presented in

Listing 18.8

.

Listing 18.8 SearchResults.jsp

<%@ page import="com.brainysoftware.burnaby.Product" %>

<%@ page import="java.sql.*" %>

<%@ page import="java.util.*" %>

<jsp:useBean id="dbBean" scope="application"

class="com.brainysoftware.burnaby.DbBean"/>

<%

String base = (String) application.getAttribute("base");

%>

<HTML>

<HEAD>

<TITLE>Search Results</TITLE>

</HEAD>

<BODY>

<TABLE>

<TR>

FL

Y

</TR>

<TR>

<TD VALIGN="TOP">

<%

if (keyword != null && !keyword.trim().equals("")) {

%>

<TABLE>

<TR>

<TD><FONT FACE="Verdana" SIZE="3"><B>Name</B></FONT></TD>

<TD><FONT FACE="Verdana"

SIZE="3"><B>Description</B></FONT></TD>

<TD><FONT FACE="Verdana" SIZE="3"><B>Price</B></FONT></TD>

<TD><FONT FACE="Verdana" SIZE="3"><B>Details</B></FONT></TD>

</TR>

<%

ArrayList products = dbBean.getSearchResults(keyword);

Iterator iterator = products.iterator();

while (iterator.hasNext()) {

Product product = (Product) iterator.next();

%>

<TR>

<TD><FONT FACE="Verdana" SIZE="2"><%=product.name%></FONT></TD>

<TD><FONT FACE="Verdana"

SIZE="2"><%=product.description%></FONT></TD>

<TD><FONT FACE="Verdana"

SIZE="2"><%=product.price%></FONT></TD>

<TD><A

HREF="<%=base%>?action=productDetails&productId=<%=product.id%>">

<FONT FACE="Verdana" SIZE="2">Details</FONT></A></TD>

Team-Fly ®

</TR>

<%

}

}

else

out.println("Please enter a search keyword.");

%>

</TD>

</TR>

</TABLE>

</BODY>

</HTML>

Note that the search keyword is contained in the "keyword" parameter.

The BrowseCatalog Page

When the user clicks one of the category hyperlinks on the menu, all products in that category are displayed by the BrowseCatalog.jsp page. This JSP page is similar to the SearchResults.jsp page, except that it accepts a "categoryId" parameter instead of "keyword."

The BrowseCatalog.jsp page is given in Listing 18.9

.

Listing 18.9 BrowseCatalog.jsp

<%@ page import="com.brainysoftware.burnaby.Product" %>

<%@ page import="java.sql.*" %>

<%@ page import="java.util.*" %>

<jsp:useBean id="dbBean" scope="application" class="com.brainysoftware.burnaby.DbBean"/>

<%

String base = (String) application.getAttribute("base");

%>

<HTML>

<HEAD>

<TITLE>Browse Catalog</TITLE>

</HEAD>

<BODY>

<TABLE>

<TR>

<TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>

</TR>

<TR>

<TD><jsp:include page="Menu.jsp" flush="true"/></TD>

<TD VALIGN="TOP">

<%

String categoryId = request.getParameter("categoryId");

if (categoryId != null && !categoryId.trim().equals("")) {

%>

<TABLE>

<TR>

<TD><FONT FACE="Verdana" SIZE="3"><B>Name</B></FONT></TD>

<TD><FONT FACE="Verdana"

SIZE="3"><B>Description</B></FONT></TD>

<TD><FONT FACE="Verdana" SIZE="3"><B>Price</B></FONT></TD>

<TD><FONT FACE="Verdana" SIZE="3"><B>Details</B></FONT></TD>

</TR>

379

<%

ArrayList products = dbBean.getProductsInCategory(categoryId);

Iterator iterator = products.iterator();

while (iterator.hasNext()) {

Product product = (Product) iterator.next();

%>

<TR>

<TD><FONT FACE="Verdana" SIZE="2"><%=product.name%></FONT></TD>

<TD><FONT FACE="Verdana"

SIZE="2"><%=product.description%></FONT></TD>

<TD><FONT FACE="Verdana"

SIZE="2"><%=product.price%></FONT></TD>

<TD><A

HREF="<%=base%>?action=productDetails&productId=<%=product.id%>">

<FONT FACE="Verdana" SIZE="2">Details</FONT></A></TD>

</TR>

<%

}

}

else

out.println("Invalid category.");

%>

</TD>

</TR>

</TABLE>

</BODY>

</HTML>

The ProductDetails Page

From the SearchResults page or the BrowseCatalog page, the user can click the Details hyperlink to display a product's details. A product's details are processed by the ProductDetails.jsp page, and from this page, the user can click the Add to Cart link to add the product to the shopping cart. The

ProductDetails.jsp page is given in

Listing 18.10

.

Listing 18.10 ProductDetails.jsp

<%@ page import="com.brainysoftware.burnaby.Product" %>

<%@ page import="java.sql.*" %>

<%@ page import="java.util.*" %>

<jsp:useBean id="dbBean" scope="application" class="com.brainysoftware.burnaby.DbBean"/>

<%

String base = (String) application.getAttribute("base");

String imageUrl = (String) application.getAttribute("imageUrl");

%>

<HTML>

<HEAD>

<TITLE>Product Details</TITLE>

</HEAD>

<BODY>

<TABLE>

<TR>

<TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>

</TR>

<TR>

<TD><jsp:include page="Menu.jsp" flush="true"/></TD>

<TD VALIGN="TOP">

<%

380

try {

int productId =

Integer.parseInt(request.getParameter("productId"));

Product product = dbBean.getProductDetails(productId);

if (product != null) {

%>

<TABLE>

<TR>

<TD><IMG BORDER="0" WIDTH="100" SRC="<%=(imageUrl + product.id)%>.gif"></TD>

<TD><B><%=product.name%></B><BR>

<%=product.description%><BR>

Price : $<%=product.price%></TD>

</TR>

<TR>

<TD COLSPAN="2" ALIGN="RIGHT">

<A

HREF="<%=base%>?action=addShoppingItem&productId=<%=product.id%>">

Add To Cart</A>

</TD>

</TR>

</TABLE>

<%

}

}

catch (Exception e) {

out.println("Error: Invalid product identifier.");

}

%>

</TD>

</TR>

</TABLE>

</BODY>

</HTML>

The ShoppingCart.jsp Page

The shopping cart in this application is session based. Each shopping item is represented by the

ShoppingItem class and stored in a Hashtable object called shoppingCart. This Hashtable object is stored in the Session object of each particular user.

The ShoppingCart.jsp is given in

Listing 18.11

.

Listing 18.11 ShoppingCart.jsp

<%@ page import="com.brainysoftware.burnaby.Product" %>

<%@ page import="com.brainysoftware.burnaby.ShoppingItem" %>

<%@ page import="java.sql.*" %>

<%@ page import="java.util.*" %>

<jsp:useBean id="dbBean" scope="application" class="com.brainysoftware.burnaby.DbBean"/>

<%

String base = (String) application.getAttribute("base");

Hashtable shoppingCart = (Hashtable) session.getAttribute("shoppingCart");

if (shoppingCart == null)

shoppingCart = new Hashtable(10);

String action = request.getParameter("action");

381

if (action != null && action.equals("addShoppingItem")) {

try {

int productId =

Integer.parseInt(request.getParameter("productId"));

Product product = dbBean.getProductDetails(productId);

if (product != null) {

ShoppingItem item = new ShoppingItem();

item.productId = productId;

item.quantity = 1;

item.price = product.price;

item.name = product.name;

item.description = product.description;

shoppingCart.remove(Integer.toString(productId));

shoppingCart.put(Integer.toString(productId), item);

session.setAttribute("shoppingCart", shoppingCart);

}

}

catch (Exception e) {

out.println("Error adding the selected product to the shopping cart");

}

}

if (action != null && action.equals("updateShoppingItem")) {

try {

int productId =

Integer.parseInt(request.getParameter("productId"));

int quantity =

Integer.parseInt(request.getParameter("quantity"));

ShoppingItem item =

(ShoppingItem)shoppingCart.get(Integer.toString(productId));

if (item != null) {

item.quantity = quantity;

}

}

catch (Exception e) {

out.println("Error updating shopping cart");

}

}

if (action != null && action.equals("deleteShoppingItem")) {

try {

int productId =

Integer.parseInt(request.getParameter("productId"));

shoppingCart.remove(Integer.toString(productId));

}

catch (Exception e) {

out.println("Error deleting the selected item from the shopping cart");

}

}

%>

<HTML>

<HEAD>

<TITLE>Shopping Cart</TITLE>

</HEAD>

<BODY>

<TABLE>

<TR>

382

<TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>

</TR>

<TR>

<TD><jsp:include page="Menu.jsp" flush="true"/></TD>

<TD VALIGN="TOP">

<%

%>

<TABLE>

<TR>

<TD><FONT FACE="Verdana" SIZE="3"><B>Name</B></FONT></TD>

<TD><FONT FACE="Verdana"

SIZE="3"><B>Description</B></FONT></TD>

<TD><FONT FACE="Verdana" SIZE="3"><B>Price</B></FONT></TD>

<TD><FONT FACE="Verdana" SIZE="3"><B>Quantity</B></FONT></TD>

<TD><FONT FACE="Verdana" SIZE="3"><B>Subtotal</B></FONT></TD>

<TD><FONT FACE="Verdana" SIZE="3"><B>Update</B></FONT></TD>

<TD><FONT FACE="Verdana" SIZE="3"><B>Delete</B></FONT></TD>

</TR>

<%

Enumeration enum = shoppingCart.elements();

while (enum.hasMoreElements()) {

ShoppingItem item = (ShoppingItem) enum.nextElement();

%>

<TR>

<TD><FONT FACE="Verdana" SIZE="2"><%=item.name%></FONT></TD>

<TD><FONT FACE="Verdana"

SIZE="2"><%=item.description%></FONT></TD>

<TD><FONT FACE="Verdana" SIZE="2"><%=item.price%></FONT></TD>

<FORM>

<INPUT TYPE="HIDDEN" NAME="action" VALUE="updateShoppingItem">

<INPUT TYPE="HIDDEN" NAME="productId"

VALUE="<%=item.productId%>">

<TD><INPUT TYPE="TEXT" Size="2" NAME="quantity"

VALUE="<%=item.quantity%>"></TD>

<TD><FONT FACE="Verdana"

SIZE="2"><%=item.quantity*item.price%></FONT></TD>

<TD><INPUT TYPE="SUBMIT" VALUE="Update"></TD>

</FORM>

<FORM>

<INPUT TYPE="HIDDEN" NAME="action" VALUE="deleteShoppingItem">

<INPUT TYPE="HIDDEN" NAME="productId"

VALUE="<%=item.productId%>">

<TD><INPUT TYPE="SUBMIT" VALUE="Delete"></TD>

</FORM>

</TR>

<%

}

%>

<TR>

<TD COLSPAN="7"><A HREF="<%=base%>?action=checkOut">Check

Out</A></TD>

</TR>

</TABLE>

</TD>

</TR>

</TABLE>

</BODY>

</HTML>

The CheckOut Page

383

When users are finished shopping, they need to check out. This is done by confirming the purchase and filling in an HTML form in the CheckOut.jsp page. The Checkout page is given in

Listing 18.12

and is basically a very simple HTML form on which users fill in the delivery and

credit card details.

Listing 18.12 CheckOut.jsp

<%

String base = (String) application.getAttribute("base");

%>

<HTML>

<HEAD>

<TITLE>Check Out</TITLE>

</HEAD>

<BODY>

<TABLE>

<TR>

<TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>

</TR>

<TR>

<TD><jsp:include page="Menu.jsp" flush="true"/></TD>

<TD VALIGN="TOP">

<FORM>

<INPUT TYPE="HIDDEN" NAME="action" VALUE="order">

<TABLE>

<TR>

<TD COLSPAN="2"><I><B>Delivery Details</B></I></TD>

</TR>

<TR>

<TD>Contact Name:</TD>

<TD><INPUT TYPE="TEXT" NAME="contactName"></TD>

</TR>

<TR>

<TD>Delivery Address:</TD>

<TD><INPUT TYPE="TEXT" NAME="deliveryAddress"</TD>

</TR>

<TR>

<TD COLSPAN="2"><I><B>Credit Card Details</B></I></TD>

</TR>

<TR>

<TD>Name on Credit Card:</TD>

<TD><INPUT TYPE="TEXT" NAME="ccName"</TD>

</TR>

<TR>

<TD>Credit Card Number:</TD>

<TD><INPUT TYPE="TEXT" NAME="ccNumber"></TD>

</TR>

<TR>

<TD>Credit Card Expiry Date:</TD>

<TD><INPUT TYPE="TEXT" NAME="ccExpiryDate"</TD>

</TR>

<TR>

<TD>&nbsp;</TD>

<TD><INPUT TYPE="SUBMIT" VALUE="Check Out"></TD>

</TR>

</TABLE>

</FORM>

</TD>

</TR>

</TABLE>

384

</BODY>

</HTML>

The Order Page

When the user submits the form on the CheckOut page, the request will go to the Order page. This page inserts a record into the Orders table and inserts each shopping item into the OrderDetails table. The Order.jsp page is presented in

Listing 18.13

.

Listing 18.13 Order.jsp

<%@ page import="com.brainysoftware.burnaby.Product" %>

<%@ page import="java.sql.*" %>

<%@ page import="java.util.*" %>

<jsp:useBean id="dbBean" scope="application" class="com.brainysoftware.burnaby.DbBean"/>

<HTML>

<HEAD>

<TITLE>Order</TITLE>

</HEAD>

<BODY>

<TABLE>

<TR>

<TD COLSPAN=2><jsp:include page="Header.jsp" flush="true"/></TD>

</TR>

<TR>

<TD><jsp:include page="Menu.jsp" flush="true"/></TD>

<TD VALIGN="TOP">

<%

if (dbBean.insertOrder(request.getParameter("contactName"),

request.getParameter("deliveryAddress"),

request.getParameter("ccName"),

request.getParameter("ccNumber"),

request.getParameter("ccExpiryDate"),

(Hashtable) session.getAttribute("shoppingCart"))) {

session.invalidate();

out.println("Thank you for your purchase");

}

else

out.println("Error");

%>

</TD>

</TR>

</TABLE>

</BODY>

</HTML>

The DbBean JavaBean

All the JSP pages are kept as presentation pages wherever possible and use a JavaBean called

DbBean. This bean is given in

Listing 18.14

and contains all the methods used by the JSP pages.

Listing 18.14 DbBean.java

package com.brainysoftware.burnaby; import java.util.Hashtable; import java.util.ArrayList;

385

import java.util.Enumeration; import java.sql.*; public class DbBean {

public String dbUrl = "";

public String dbUserName = "";

public String dbPassword = "";

public void setDbUrl(String url) {

dbUrl = url;

}

public void setDbUserName(String userName) {

dbUserName = userName;

}

public void setDbPassword(String password) {

dbPassword = password;

}

public Hashtable getCategories() {

Hashtable categories = new Hashtable();

try {

Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);

Statement s = connection.createStatement();

String sql = "SELECT CategoryId, Category FROM Categories" +

" ";

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

categories.put(rs.getString(1), rs.getString(2) );

}

rs.close();

s.close();

connection.close();

}

catch (SQLException e) {}

return categories;

}

public ArrayList getSearchResults(String keyword) {

ArrayList products = new ArrayList();

try {

Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);

Statement s = connection.createStatement();

String sql = "SELECT ProductId, Name, Description, Price FROM

Products" +

" WHERE Name LIKE '%" + keyword.trim() + "%'" +

" OR Description LIKE '%" + keyword.trim() + "%'";

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

Product product = new Product();

product.id = rs.getInt(1);

product.name = rs.getString(2);

product.description = rs.getString(3);

product.price = rs.getDouble(4);

products.add(product);

}

rs.close();

s.close();

connection.close();

386

}

catch (SQLException e) {}

return products;

}

public ArrayList getProductsInCategory(String categoryId) {

ArrayList products = new ArrayList();

try {

Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);

Statement s = connection.createStatement();

String sql = "SELECT ProductId, Name, Description, Price FROM

Products" + " WHERE CategoryId=" + categoryId;

ResultSet rs = s.executeQuery(sql);

while (rs.next()) {

Product product = new Product();

product.id = rs.getInt(1);

product.name = rs.getString(2);

product.description = rs.getString(3);

product.price = rs.getDouble(4);

products.add(product);

}

rs.close();

s.close();

connection.close();

}

catch (SQLException e) {}

return products;

}

public Product getProductDetails(int productId) {

Product product = null;

try {

Connection connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);

Statement s = connection.createStatement();

String sql = "SELECT ProductId, Name, Description, Price FROM

Products" + " WHERE ProductId=" + Integer.toString(productId);

ResultSet rs = s.executeQuery(sql);

if (rs.next()) {

product = new Product();

product.id = rs.getInt(1);

product.name = rs.getString(2);

product.description = rs.getString(3);

product.price = rs.getDouble(4);

}

rs.close();

s.close();

connection.close();

}

catch (SQLException e) {}

return product;

}

public boolean insertOrder(String contactName, String deliveryAddress,

String ccName, String ccNumber, String ccExpiryDate, Hashtable shoppingCart) {

boolean returnValue = false;

long orderId = System.currentTimeMillis();

Connection connection = null;

387

try {

connection = DriverManager.getConnection(dbUrl, dbUserName, dbPassword);

connection.setAutoCommit(false);

Statement s = connection.createStatement();

String sql = "INSERT INTO Orders" +

" (OrderId, ContactName, DeliveryAddress, CCName, CCNumber,

CCExpiryDate)" +

" VALUES" +

" (" + orderId + ",'" + contactName + "','" + deliveryAddress

+ "'," + "'" + ccName + "','" + ccNumber + "','" + ccExpiryDate +

"')";

s.executeUpdate(sql);

// now insert items into OrderDetails table

Enumeration enum = shoppingCart.elements();

while (enum.hasMoreElements()) {

ShoppingItem item = (ShoppingItem) enum.nextElement();

sql = "INSERT INTO OrderDetails (OrderId, ProductId, Quantity,

Price)" + " VALUES (" + orderId + "," + item.productId + "," +

item.quantity + "," + item.price + ")";

s.executeUpdate(sql);

}

s.close();

connection.commit();

connection.close();

returnValue = true;

}

catch (SQLException e) {

try {

connection.rollback();

}

connection.close();

}

catch (SQLException se) {}

}

return returnValue;

}

TE

AM

FL

Y

Summary

In this chapter, you saw the development process of the Burnaby project, which is an online store.

Its sole purpose was to demonstrate how Model 2 applications can be designed and developed.

In the next chapter, "

XML-Based E-Books ," you take a look at another web project.

Team-Fly ®

Chapter 19. XML-Based E-Books

Because the Internet is getting more popular every day, more content is available online. Some content is simple HTML, but some is structured to resemble books. The latter includes online manuals, electronic books, and more.

An electronic book, also called an e-book, is not much different from a printed book in that it has a table of contents and a number of chapters. Because an electronic book is online, however, the publisher can take advantage of many features that are not available in printed books. For example, you can make an electronic book easy to navigate by displaying the table of contents all the time.

When readers want to change chapters, they can do it straight away by clicking the link to that chapter.

The format you choose for an electronic book is an important decision. The most popular format makes the electronic content viewable in a web browser window. In this type of project, the table of contents is displayed in an HTML frame on the left, as shown in

Figure 19.1

. The frame on the

right displays in HTML format the content of the selected chapter or chapter heading.

Figure 19.1. The visual representation of the book structure.

Compared to a paper book, an e-book gives you advantages beyond being easier to navigate. First, you can make your e-book available to an unlimited number of people by putting it on the Internet.

Second, you can update your electronic book at almost any time. No printing cost is incurred when you issue the next edition of your book. The main disadvantage is that your readers need an

Internet connection every time they want to read the book. Because access to the Internet is becoming more commonplace, however, this disadvantage is arguable. Also debatable is whether it is more convenient to read a non-electronic book.

This chapter discusses the many aspects of publishing an electronic book. Of utmost importance is the table of contents, which gets the first priority in this discussion. Then you see how to

389

implement an easy-to-navigate browser-independent electronic book. The two parts to this project are the client side and the server side. Finally, you explore a project implemented using

JavaServer pages. The same project can be implemented using any Internet technology, however, after you understand the concept.

The Table of Contents

The first issue in the electronic book system is to decide how you are going to store the book's table of contents; that is, the structure of chapters and headings. A book can have any number of chapters, and each chapter can have any number of headings. These headings, in turn, can have subheadings with sub-subheadings, and so on. In other words, a book's table of content, can be viewed as a tree of chapters/headings. It is hierarchical.

Having said that, you need a format in which you can easily work with hierarchical data. XML is probably the first and best choice available today. XML is widely accepted, and editing is easy because XML is essentially plain text. By storing your book structure in an XML document, you need only to edit the XML document when the book structure changes.

For example, the table of contents of the online book shown in

Figure 19.1

is given in

Listing 19.1

.

Listing 19.1 A Book's Table of Contents in XML

<?xml version="1.0" encoding="ISO-8859-1"?>

<book title="Fantasies for Dummies" url="bookTitle.html">

<chapter title="Introduction to Disneyland" url="ch1.html">

<heading1 title="Meet Mickey" url="mickey.html">

</heading1>

</chapter>

<chapter title="Going Inside" url="ch2.html">

<heading1 title="Meet Donald" url="donald.html">

<heading2 title="Kwik" url="kwik.html">

<heading3 title="You can't escape" url="noEscape.html" />

</heading2>

<heading2 title="Kwek" url="kwek.html">

</heading2>

<heading2 title="Kwak" url="kwak.html" />

</heading1>

</chapter>

<chapter title="Alice in Disneyland" url="Ch3.html" />

</book>

As you can see, the table of contents has the <book> tag as the root. Because of the difficulty in naming the multiple elements, this example calls the section under chapters "heading." Therefore, instead of subchapter, you call it heading1. Instead of sub-subchapter, you have heading2. A heading2 can have a subheading called heading3, heading3 can have a subheading called heading4, and so on.

Translating XML into the Object Tree

390

Having a very structured book content in an XML format is one thing; making it viewable by your reader is another. To make sure that your book can be used on as many browsers as possible, you should use JavaScript to make it browser-independent.

Note

Chapter 26 , "Working with Object Trees," gives you the background to understand how

to implement an object tree in JavaScript.

Because changing the appearance of the JavaScript object tree involves clearing and writing to a document object, working with frames is much easier. The frameset, which is the main document that the user requests, contains all the JavaScript code and two frames. The left frame displays the structure of the book. The right frame displays the selected HTML page.

As mentioned in Chapter 26 , a JavaScript object tree is a hierarchical structure with objects and

parent-child relationships between objects. Each object is a separate entity made from a JavaScript array. To create this object tree, you need two custom JavaScript functions: createObject and append. You use the createObject function to create an object in the object tree and the append function to create a relationship between two objects.

An object in the tree represents the book, a chapter, or a heading. Note that by heading I mean any heading: heading1, heading2, … or headingn. Each object has a unique identifier that is used to search for this object, a title to display, and a URL to the HTML content that is the object's content.

In addition to these three elements, an object also has a state: whether it is open or closed. An open object displays all its children, if any. A closed object that has children displays a plus sign

(+) at its node. To open this object, you click this node (plus sign). An open object has a minus sign (-) at its node. To close this object, you click the minus sign. In more technical terms, opening and closing an object is also called expanding or collapsing the object.

To create an object, you call the createObject function, passing a unique identifier, a title, and the

URL to the content. This function is given in Listing 19.2

.

Listing 19.2 The createObject Function

function createObject(id, title, url) {

var element = new Array();

element[0] = id;

element[1] = title;

element[2] = url;

element[3] = 0;

return element;

}

For example, to create the object that represents the book, you write the following line: var e1 = createObject(1, "Fantasies for Dummies", "bookTitle.html");

This code creates an object with identifier 1, title "Fantasies for Dummies," and "bookTitle.html" as the URL. Remember that an object in JavaScript is merely an array. The identifier is stored as the first array element, the title as the second, the URL as the third. The fourth element

(element[3]) stores the object state. 0 indicates that the object is closed. 1 indicates the object is open. By default, an object is created closed.

To create a relationship between two objects, you use the append function, as shown in

Listing

19.3

. The function accepts two arguments: the object to be the parent in the relationship and the

object that is intended to be the child in the relationship.

391

Listing 19.3 The append Function

function append(parent, child) {

parent[parent.length] = child;

}

To create the XML document in Listing 19.1

, you need to call the createObject and append

functions repeatedly to make the whole object tree. The code part is given in Listing 19.4

.

Listing 19.4 Creating a JavaScript Object Tree Based on the Structure in Listing

19.1

var e1 = createObject(1, "Fantasies for Dummies", "bookTitle.html"); var e2 = createObject(2, "Introduction to Disneyland", "ch1.html"); append(e1 , e2); var e3 = createObject(3, "Meet Mickey", "mickey.html"); append(e2 , e3); var e4 = createObject(4, "Going Inside", "ch2.html"); append(e1 , e4); var e5 = createObject(5, "Meet Donald", "donald.html"); append(e4 , e5); var e6 = createObject(6, "Kwik", "kwik.html"); append(e5 , e6); var e7 = createObject(7, "You can't escape", "noEscape.html"); append(e6 , e7); var e8 = createObject(8, "Kwek", "kwek.html"); append(e5 , e8); var e9 = createObject(9, "Kwak", "kwak.html"); append(e5 , e9); var e10 = createObject(10, "Alice in Disneyland", "Ch3.html"); append(e1 , e10);

Note that each object is given a unique identifier.

The challenge in creating a JavaScript object tree based on an XML document is resolving how to translate the XML document in

Listing 19.1

into JavaScript code in

Listing 19.4

. When the table

of contents changes, the XML document also changes. This change must be reflected by the

JavaScript objects and relationships between objects in

Listing 19.4

. This is the reason you need

the server-side processing to read the XML file every time the electronic book is requested:You need to ensure that the table of contents the user sees is current.

The Project

In this implementation, the complete project consists of two files: index.jsp and TocBean.java.

You also need HTML files for the contents, of course; but those static files are outside this discussion.

In addition to these two files, you need two other dummy files called toc.html and content.html, because a frameset must have physical pages to fill the frames.

The index.jsp file is the main file that contains the JavaScript functions for creating and manipulating the object tree. Its code is given in

Listing 19.5

.

392

Listing 19.5 The index.jsp File

<jsp:useBean id="TocBeanId" scope="page" class="TocBean" />

<HTML>

<HEAD>

<TITLE>Table of Contents</TITLE>

<SCRIPT LANGUAGE="JavaScript">

<!–– Hiding Script var selectedElementId = 1; var root; function createObject(id, title, url) {

var element = new Array();

element[0] = id;

element[1] = title;

element[2] = url;

element[3] = 0;

return element;

} function append(parent, child) {

parent[parent.length] = child;

} function redrawTree() {

var doc = top.treeFrame.window.document;

doc.clear();

doc.write("<HTML><HEAD><STYLE TYPE=\"text/css\">\n" +

".normal:link { text-decoration:none; color:black; fontfamily:verdana; font-size: 8pt; }\n" +

".selected:link { text-decoration:none; color:red; fontfamily:verdana; font-size: 9pt; }\n" +

"</STYLE></HEAD>");

doc.write("<BODY BGCOLOR='#ffffff'>");

redrawNode(root, doc, 0, 1, "");

doc.write("</BODY></HTML>");

doc.close();

} function closeBook() {

root[3] = 0;

redrawTree();

} function openBook() {

root[3] = 1;

redrawTree();

} function redrawNode(

foldersNode, doc, level, lastNode, leftSide) {

var j=0;

var i=0;

var id = foldersNode[0];

var title = foldersNode[1];

var url = foldersNode[2];

var hasSubNode = (foldersNode.length>4);

var expanded = foldersNode[3];

393

doc.write("<TABLE BORDER=0 CELLSPACING=0" +

" CELLPADDING=0>");

doc.write("<TR><TD VALIGN=middle NOWRAP>");

doc.write(leftSide);

if (id == 1) { // this is the book

if (root[3] == 0)

doc.write("<A HREF='javascript:top.openBook()'> <IMG

SRC=images/ClosedBook.gif

BORDER=0></A>");

else

doc.write("<A HREF='javascript:top.closeBook()'> <IMG

SRC=images/OpenBook.gif BORDER=0></A>");

}

var nodeLink =

"<A HREF='javascript:top.clickNode(" + id + ")'>";

if (level>0)

if (lastNode) { //the last folder in array

if (hasSubNode) {

if (expanded)

doc.write(nodeLink +

"<IMG SRC='images/LastNodeMinus.gif'" +

" BORDER=0 WIDTH=16 HEIGHT=22>" + "</A>");

else

doc.write(nodeLink +

"<IMG SRC='images/LastNodePlus.gif'" +

" BORDER=0 WIDTH=16 HEIGHT=22>" + "</A>");

}

else

doc.write("<IMG SRC='images/LastNode.gif'" +

" WIDTH=16 HEIGHT=22>");

leftSide += "<IMG SRC='images/blank.gif'" +

" WIDTH=16 HEIGHT=22>";

}

else { //not last folder

if (hasSubNode) {

if (expanded)

doc.write(nodeLink +

"<IMG SRC='images/NodeMinus.gif'" +

" BORDER=0 WIDTH=16 HEIGHT=22>" + "</A>");

else

doc.write(nodeLink +

"<IMG SRC='images/NodePlus.gif'" +

" BORDER=0 WIDTH=16 HEIGHT=22></A>");

}

else

doc.write("<IMG SRC='images/Node.gif'" +

" WIDTH=16 HEIGHT=22>");

leftSide += "<IMG SRC='images/VertLine.gif'" +

" WIDTH=16 HEIGHT=22>";

}

doc.write("<TD>&nbsp;");

if (id == selectedElementId)

doc.write("<A CLASS=selected");

else

doc.write("<A CLASS=normal");

394

doc.write(" HREF='javascript:top.clickElement("

+ id + ", \"" + url + "\")'>" + title + "</A>");

doc.write("</TABLE>")

if (hasSubNode && expanded) {

level++;

for (i=4; i<foldersNode.length;i++)

if (i == foldersNode.length-1)

redrawNode(

foldersNode[i], doc, level, 1, leftSide);

else

redrawNode(

foldersNode[i], doc, level, 0, leftSide);

}

} function clickElement(id, url) {

selectedElementId = id;

redrawTree();

parent.frames[1].location = url;

} function toggleNode(foldersNode, folderId) {

if (foldersNode[0] == folderId)

foldersNode[3] = 1 - foldersNode[3];

else if (foldersNode[3])

for (var i=4; i< foldersNode.length; i++)

toggleNode(foldersNode[i], folderId);

} function clickNode(folderId) {

toggleNode(root, folderId);

redrawTree();

} function initialize() {

root = e1;

redrawTree();

}

<%

TocBeanId.getToc("toc.xml");

out.println(TocBeanId.getString());

%>

// end hiding script ––>

</SCRIPT>

</HEAD>

<FRAMESET onLoad="initialize()" cols="225,*">

<FRAME SRC="toc.html" NAME="treeFrame">

<FRAME SRC="content.html" NAME="objectFrame">

<NOFRAMES>

<BODY>

Unfortunately, your browser cannot render frames.

Please upgrade your browser.

</BODY>

</NOFRAMES>

</FRAMESET>

</HTML>>

395

The rendered HTML file is given as follows:

<HTML>

<HEAD>

<TITLE>Table of Contents</TITLE>

<SCRIPT LANGUAGE="JavaScript">

<!–– Hiding Script var selectedElementId = 1; var root; function createElement(id, title, url) {

var element = new Array();

element[0] = id;

element[1] = title;

element[2] = url;

element[3] = 0;

return element;

} function append(parent, child) {

parent[parent.length] = child;

} function redrawTree() {

var doc = top.treeFrame.window.document;

doc.clear();

doc.write("<HTML><HEAD><STYLE TYPE=\"text/css\">\n" +

".normal:link { text-decoration:none; color:black; fontfamily:verdana; font-size: 8pt; }\n" +

".selected:link { text-decoration:none; color:red; fontfamily:verdana; font-size:

9pt; }\n" +

"</STYLE></HEAD>");

doc.write("<BODY BGCOLOR='#ffffff'>");

redrawNode(root, doc, 0, 1, "");

doc.write("</BODY></HTML>");

doc.close();

} function closeBook() {

root[3] = 0;

redrawTree();

} function openBook() {

root[3] = 1;

redrawTree();

} function redrawNode(

foldersNode, doc, level, lastNode, leftSide) {

var j=0;

var i=0;

var id = foldersNode[0];

var title = foldersNode[1];

var url = foldersNode[2];

var hasSubNode = (foldersNode.length>4);

var expanded = foldersNode[3];

396

doc.write("<TABLE BORDER=0 CELLSPACING=0" +

" CELLPADDING=0>");

doc.write("<TR><TD VALIGN=middle NOWRAP>");

doc.write(leftSide);

if (id == 1) { // this is the book

if (root[3] == 0)

doc.write("<A HREF='javascript:top.openBook()'> <IMG

SRC=images/ClosedBook.gif BORDER=0></A>");

else

doc.write("<A HREF='javascript:top.closeBook()'> <IMG

SRC=images/OpenBook.gif BORDER=0></A>");

}

var nodeLink =

"<A HREF='javascript:top.clickNode(" + id + ")'>";

if (level>0)

if (lastNode) { //the last folder in array

if (hasSubNode) {

if (expanded)

doc.write(nodeLink +

"<IMG SRC='images/LastNodeMinus.gif'" +

" BORDER=0 WIDTH=16 HEIGHT=22>" + "</A>");

else

doc.write(nodeLink +

"<IMG SRC='images/LastNodePlus.gif'" +

" BORDER=0 WIDTH=16 HEIGHT=22>" + "</A>");

}

else

doc.write("<IMG SRC='images/LastNode.gif'" +

" WIDTH=16 HEIGHT=22>");

leftSide += "<IMG SRC='images/blank.gif'" +

" WIDTH=16 HEIGHT=22>";

}

else { //not last folder

if (hasSubNode) {

if (expanded)

doc.write(nodeLink +

"<IMG SRC='images/NodeMinus.gif'" +

" BORDER=0 WIDTH=16 HEIGHT=22>" + "</A>");

else

doc.write(nodeLink +

"<IMG SRC='images/NodePlus.gif'" +

" BORDER=0 WIDTH=16 HEIGHT=22>" + "</A>");

}

else

doc.write("<IMG SRC='images/Node.gif'" +

" WIDTH=16 HEIGHT=22>");

leftSide += "<IMG SRC='images/VertLine.gif'" +

" WIDTH=16 HEIGHT=22>";

}

doc.write("<TD>&nbsp;");

if (id == selectedElementId)

doc.write("<A CLASS=selected");

else

doc.write("<A CLASS=normal");

397

doc.write(" HREF='javascript:top.clickElement("

+ id + ", \"" + url + "\")'>" + title + "</A>");

doc.write("</TABLE>")

if (hasSubNode && expanded) {

level++;

for (i=4; i<foldersNode.length;i++)

if (i == foldersNode.length-1)

redrawNode(

foldersNode[i], doc, level, 1, leftSide);

else

redrawNode(

foldersNode[i], doc, level, 0, leftSide);

}

} function clickElement(id, url) {

selectedElementId = id;

redrawTree();

parent.frames[1].location = url;

} function toggleNode(foldersNode, folderId) {

if (foldersNode[0] == folderId)

foldersNode[3] = 1 - foldersNode[3];

else if (foldersNode[3])

FL

toggleNode(foldersNode[i], folderId);

}

AM

Y function clickNode(folderId) {

redrawTree();

}

TE function initialize() {

root = e1;

redrawTree();

} var e1 = createElement(1, "Fantasies for Dummies", "bookTitle.html"); var e2 = createElement(2, "Introduction to Disneyland", "ch1.html"); append(e1 , e2); var e3 = createElement(3, "Meet Mickey", "mickey.html"); append(e2 , e3); var e4 = createElement(4, "Going Inside", "ch2.html"); append(e1 , e4); var e5 = createElement(5, "Meet Donald", "donald.html"); append(e4 , e5); var e6 = createElement(6, "Kwik", "kwik.html"); append(e5 , e6); var e7 = createElement(7, "You can't escape", "noEscape.html"); append(e6 , e7); var e8 = createElement(8, "Kwek", "kwek.html"); append(e5 , e8);

Team-Fly ®

var e9 = createElement(9, "Kwak", "kwak.html"); append(e5 , e9); var e10 = createElement(10, "Alice in Disneyland", "Ch3.html"); append(e1 , e10);

// end hiding script ––>

</script>

</HEAD>

<FRAMESET onLoad="initialize()" cols="225,*"> <FRAME SRC="toc.html"

NAME="treeFrame">

<FRAME SRC="content.html" NAME="objectFrame">

<NOFRAMES>

<BODY>Unfortunately, your browser cannot render frames.

Please upgrade your browser.

</BODY>

</NOFRAMES>

</FRAMESET>

</HTML>

As you can see from the bottom part of Listing 19.5

, the index.jsp file hosts two frames: toc.html and content.html. The first frame is named treeFrame and the second frame objectFrame, as follows:

<FRAMESET onLoad="initialize()" cols="225,*">

<FRAME SRC="toc.html" NAME="treeFrame">

<FRAME SRC="content.html" NAME="objectFrame">

<NOFRAMES>

<BODY>

Unfortunately, your browser cannot render frames.

Please upgrade your browser.

</BODY>

</NOFRAMES>

</FRAMESET>

The treeFrame frame is where you display the structure of you book. The objectFrame frame, on the other hand, displays the content of the selected page. For example, if the user clicks the first chapter title, the content of

Chapter 1 is displayed (refer to

Figure 19.1

)

The index.jsp file also contains the following JavaScript functions:

createObject. As given in Listing 19.3

, this function creates an array object with four elements.

Each element has a unique identifier.

append. Creates a parent-child relationship between two objects.

redrawTree. This function is responsible for clearing the treeFrame document and writing new content to it when the user interacts with the object tree. From the frameset (index.jsp), the document of the treeFrame frame is referred to as treeFrame.window.document. Because this function will be invoked from the treeFrame page, however, the document is referred to as the following: var doc = top.treeFrame.window.document;

Therefore, the variable doc here refers to the document object of the treeFrame frame.

399

The redrawTree function first clears the document and writes some static HTML to doc, as follows: doc.clear(); doc.write("<HTML><HEAD><STYLE TYPE=\"text/css\">\n" +

".normal:link { text-decoration:none; color:black; " +

"font-family:verdana; font-size: 8pt; }\n" +

".selected:link { text-decoration:none; color:red; " +

"font-family:verdana; font-size: 9pt; }\n" +

"</STYLE></HEAD>"); doc.write("<BODY BGCOLOR='#ffffff'>");

Then it calls the redrawNode function, passing the variable root and doc: redrawNode(root, doc, 0, 1, "");

Then it outputs the closing </BODY> and </HTML> tags to doc: doc.write("</BODY></HTML>");

Finally, it closes the document: doc.close();

redrawNode. This is a recursive function that actually redraws the book structure.

closeBook. Changes the root object to the collapsed state, as follows: function closeBook() {

root[3] = 0;

redrawTree();

}

openBook. Changes the root object to the expanded state, as you see here: function openBook() {

root[3] = 1;

redrawTree();

}

clickElement. The clickElement function is invoked when the user clicks an element in the object tree. It accepts two arguments: id and url. When the user clicks an element, the element with its identifier id becomes the selected element.

The selected element is drawn with a different color, which means that because the tree has a new selected element, the tree must be redrawn using the following: redrawTree();

The last thing this function does is change the content of the second frame using frames[1].location = url. However, because the clickElement function is invoked from the treeFrame frame, the correct code is as follows: parent.frames[1].location = url;

Note that url is the second argument passed to the function.

400

clickNode. This function is invoked when the user clicks a node. This function calls the toggleNode function and the redrawTree function: toggleNode(root, folderId); redrawTree();

toggleNode. Toggles the clicked node from the expanded state to the collapsed state and vice versa. To do this, the function must first search for the node with the correct identifier. When it is found, the function changes the fourth array element of the object from 0 to 1 or 1 to 0, as you see here: if (foldersNode[0] == folderId)

foldersNode[3] = 1 - foldersNode[3];

If the current node is not the clicked node, the function continues searching by recursively calling itself: else if (foldersNode[3])

for (var i=4; i< foldersNode.length; i++)

toggleNode(foldersNode[i], folderId);

The index.jsp also contains the following code that uses the TocBean.java bean:

<%

TocBeanId.getToc("toc.xml");

out.println(TocBeanId.getString());

%>

These two lines uses the JavaBean that translates the table of contents in XML (as shown in

Listing 19.1

) into the JavaScript object tree (as shown in

Listing 19.4

).

TocBean.java

As previously mentioned, you need server-side code to translate the XML document containing the table of contents into the JavaScript code like the one in

Listing 19.4

. The TocBean.java bean

is the one responsible for it. The code is given in

Listing 19.6

.

First, you need a Java XML parser. Here I use the one from Sun, downloadable from http://java.sun.com/xml/index.html

. If you choose to use another parser from another vendor, however, you should still be able to use the code without any modification other than the import statement in

Listing 19.6

.

Listing 19.6 The TocBean.java File

import java.io.*; import org.w3c.dom.*; import javax.xml.parsers.*; import com.sun.xml.tree.*; public class TocBean {

DocumentBuilderFactory factory;

Document document;

StringBuffer output = new StringBuffer(2048);

int objectId = 1;

401

public String getString() {

return output.toString();

}

public void getToc(String tocFilename) {

factory = DocumentBuilderFactory.newInstance();

try {

DocumentBuilder builder = factory.newDocumentBuilder();

document = builder.parse( new File(tocFilename) );

Node rootNode = document.getFirstChild();

NamedNodeMap nnm = rootNode.getAttributes();

if (nnm != null) {

Node title = nnm.getNamedItem("title" );

Node url = nnm.getNamedItem("url");

// output the first element of the following form

// var e1 = createObject(1, "book title", "book url.html");

output.append("var e1 = createObject(1, \"" +

title.getNodeValue() + "\", \"" +

url.getNodeValue() + "\");\n");

}

getChildNode(rootNode, output);

}

catch (Exception e) {

e.toString();

}

}

void getChildNode(Node parentNode, StringBuffer s) {

try {

int currentObjectId = objectId;

Node childNode = parentNode.getFirstChild();

// get chapters' & headings' titles and URLs

while (childNode != null) {

String nodeName = childNode.getNodeName();

if (nodeName != null && (nodeName.equals("chapter") ||

nodeName.startsWith("heading")) ) {

objectId++;

NamedNodeMap nnm = childNode.getAttributes();

if (nnm != null) {

Node title = nnm.getNamedItem("title" );

Node url = nnm.getNamedItem("url");

s.append("var e" + objectId + " =

createObject(" + objectId + ", " +

(title == null? "null" : "\"" + title.getNodeValue() +

"\"") + ", " +

(url == null? "null" : "\"" + url.getNodeValue() +

"\"") + ");\n");

s.append("append(e" + currentObjectId + " , " +

"e" + objectId + ");\n");

}

if (childNode.hasChildNodes())

getChildNode(childNode, s);

}

childNode = childNode.getNextSibling();

} // end while

}

catch (Exception e) {

System.out.println("Error:" + e.toString() );

}

}

402

} // end class

Basically, the JavaBean reads the XML file passed to it in the getToc() method and composes a string in the StringBuffer called output. You then can read this output using the getString method and send it to the web browser.

The getToc and getChildNode methods are explained in the following sections.

getToc()

The getToc method accepts one argument: the filename of the XML document containing the book's table of contents. The method retrieves the root object (the <book> tag) as the first object with identifier 1 and appends this information to the output StringBuffer. Using the XML document in

Listing 19.1

, the output should be the following:

var e1 = createObject(1, "Fantasies for Dummies", "bookTitle.html");

The method then calls the getChildNode method to process the rest of the tags. Note that objectId is used to register the object identifier.

getChildNode()

This method reads a tag whose name starts with "chapter" or "heading." The tag found is appended to the output StringBuffer.

Pre-Render the Table of Contents

Every time someone reads your electronic book, the XML document containing the table of contents must be parsed into the HTML/JavaScript equivalent of the hierarchical structure. This takes more time than simply sending a static page to the browser. Because the table of contents most likely does not change every day, you can pre-render the table of contents for a busy site so that it is available as a static page. For this purpose, you can use the output caching technique

explained in Chapter 15 , "Caching."

Summary

In this chapter, you learned how to create an electronic book application whose table of content is based on an XML document. When the structure changes, you need to update only the XML document.

403

Chapter 20. Web-Based Document Management

How do you secure a file on the web so that only authorized people can access it? Some people simply put the file in one of the virtual host's sub-directories and provide no link to it, so that only those who know the full path can download it. This method is of course, only as secure as the full path to the document, and you probably would not secure your corporate confidential documents this way.

What people normally do is to utilize the web server and operating system authentication method so that every time someone tries to download a file, that person needs to type in the correct user name and password. This is a good approach, but it is too simple in many circumstances. One problem with this solution is that you need to tell the password to everyone you want to be able to download the file. This approach is like sharing the same NT or UNIX user name and password with everyone in the corporation—it doesn't work. People don't share passwords for the same reasons they don't share secrets. In addition to the privacy and security issues, this approach is less than suitable when you want more functionality, such as document versioning and full activity records, without relying on the web server log files.

Another solution is to store the files in a database and allow access to them only after authenticating the user. Putting Binary Large Object Blocks (BLOBs) in the database is excruciatingly slow and resource-hungry, however. The better solution is to store those files in a directory outside the virtual host (virtual directory) so they are not visible from the

Internet/intranet when the user types a URL. To download a file, the user has to direct the browser to a special page and type the user name and password. Upon successful authentication, the web server fetches the file and sends it to the browser.

This chapter introduces the concept of document management, an important topic not often discussed in beginner or advanced Java or web programming books. The discussion presented in this chapter is based on docman, the commercial web-based document management project from

Brainysoftware.com. Not all of its features are included in here, though, because of space limitations. The complete project may take a book of its own.

The basic concepts of this project are revealed in this chapter. By understanding these concepts, you easily can extend the functionality according to your needs. The four key features discussed in this chapter are these:

Database structure of the project.

Programmable file download.

File upload.

The client-side tool that makes navigating through the document as easy as using

Windows Explorer. In fact, the user interface will look very familiar to any Windows user.

Note

Programmable file download and file upload are discussed in

Chapter 12 , "Programmable

File Download," and Chapter 13 , "File Upload" and will not be repeated here. If you

would like to understand this project fully, you should first read those two chapters. Also important to understanding how the navigation tool works is

Chapter 26 , "Working with

Object Trees."

404

The Docman Project

In brief, docman is a Windows Explorer on the web. This Internet application is implemented using Java Server Pages technology to present a web-based hierarchical file system similar to those in a non-web environment. There are two types of objects: files and folders/directories. A

file is any document you store in the file system. A folder or directory is a container that can store

any number of files and any number of other folders. If Folder B is located under Folder A, Folder

B is said to be a subfolder of Folder A. Folder A is referred to as the parent folder of Folder B and any file Folder A contains. The topmost folder in the hierarchy is called root. It is the first folder that users see when they browse the system. As you would expect, root does not have a parent folder.

Docman supports any number of users. Users each have their own permission set. This means you can allow users to view files in one directory but not in the other. This is naturally useful in an organization with different depart-ments. For example, the marketing people can see the documents belonging to the marketing department but not IT-related files. Those working in the

IT department, on the other hand, have access to these IT-related documents, but not to the HR's remuneration archive. Users can browse the system from root down the hierarchy as long as they have the permission.

Figure 20.1

shows the user interface of docman. Notice the familiar object tree on the left side.

Figure 20.1. The docman project's user interface.

System Requirements

The docman project relies on the two JavaBeans included on the accompanying CD:

The BrainySoftware.com

File Download bean for programmable file download

The BrainySoftware.com

File Upload bean version 2.0 for uploading files

405

Using these two beans will save you writing hundreds of lines of Java code and make your code look neater.

Before you start, you need to copy the .jar files in the software/ FileDownloadBean and software/FileUploadBean directories into your WEB-INF/lib directory of your application directory and restart Tomcat. Please also look at the license agreement of the two beans. If you choose to write your own beans, Chapters

12 and

13 should give you sufficient information to do

so.

The following section discusses the database structure and all the JSP pages and bean comprising the project. The whole project is ready for deployment and can be found in the software/docman directory on the accompanying CD.

The Database Structure

In this implementation, file or folder information is stored in a relational database. However, all files are stored in one single folder outside the virtual root or virtual directory, regardless of their position in the hierarchy. This may sound strange at first but will seem logical after you read the next section.

The way in which files are stored doesn't matter as long as they are not directly accessible to users who type a URL in the web browser and the information on the file system structure remains intact. In this implementation, each object (file or folder) has the following properties:

Id. A unique object identifier

Parent Id. The identifier of the parent folder.

Type. The object type, whether it is a folder or a file. A folder has a type of 0 and a file of

1.

Name. The name of the object. In other words, either a filename or a folder name.

Of special interest is the record that has an object Id of 1 and is called root. root is the first object in the system and has a parent Id of 0, which means it does not have a parent.

Object-related information is stored in a table called Objects. As you can see, the object Id and the parent Id of each object gives you enough information to know the hierarchical structure of all folders and files

The structure of the Objects table in the Access database is given in

Table 20.1

.

Table 20.1. The Structure of the Objects Table

Field Name Data Type

ID Number

ParentID Number

Type Number

Name Text

Note

You also can use your favorite database server to create these tables. One thing to note, though; your database server must support subqueries because they are used in the SQL statements used to access the database. Most popular database servers, such as Microsoft

SQL Server, Oracle, Sybase, and IBM's DB2, support subqueries.

406

This implementation also uses two other tables: Users and Permissions. The Users table stores information about users, and the Permissions table stores information about which users have permission to various files or folders. The structures of these two tables in an Access database are given in

Table 20.2

and Table 20.3

.

Table 20.2. The Structure of the Users Table

Field Name Data Type

ID Number

UserName Text

Password Text

Table 20.3. The Structure of the Permissions Table

Field Name Data Type

UserId Number

ObjectId Number

The Permissions table is very important in the docman project. If a user has permission to an object, this information must be present in the Permissions table. Therefore, if user A, whose user

ID is 7, has permission to access a folder whose object ID is 133, there must be a record in the

Permissions table with UserID 7 and ObjectID 133.

Now that you understand the database structure, let's work on an example: the directory structure of a fictitious company called Door Never Closed Pty, Ltd. The file and folder collection in this example is small for the sake of simplicity, but the hierarchy should reflect that of a real system.

The hierarchy of all the folders and files is shown in

Figure 20.2

.

Figure 20.2. The directory structure of the file system.

Under root, you see two directories: Marketing and Sales. There is also a README.TXT for everyone new to read. (This file contains instructions from the system administrator on how to use the system). The people in the Marketing department store their folders and files in the Marketing folder. Access to this folder is limited to the Marketing people only. The Sales folder is for the

Sales department, and only the employees working in the Sales department can access it.

The content of the Objects table looks like

Table 20.4

.

Table 20.4. The Data in the Objects Table

ID ParentID Type Name

1 0 0 root

407

2 1

3 2

4 1

5 1

6 2

7 6

8 6

9 5

10 5

11 5

0

1

1

0

0

1

1

1

1

1

Marketing

Strategy.doc

README.TXT

Sales

Managers evaluation.doc remuneration.doc europe.doc asia.doc america.doc

Note

The ID is assigned to an object at the time of the file upload, which means that there is no guarantee that files in a folder will have consecutive object IDs. This doesn't matter, however, because object IDs and other metadata are invisible to the user. All users see is a hierarchical file system.

Note also that files are stored in one single directory using their object Ids. This means that the Strategy.doc file is stored as 3. Because all files are given unique numbers as

Y other with the login name bulbul. The content of the Users table looks like that shown in

Table

20.5

.

ID UserName

1 boni

2 bulbul

TE

Password

secret brownhair

Now comes the tricky part—the permission set. Boni is the marketing manager. She definitely has access to the Marketing department's files but has nothing to do with the Sales department. Bulbul, on the other hand, is the National Sales Director of Door Never Closed Pty, Ltd. He has access to all Sales department's files, but Marketing is not his territory. The README.TXT is for everyone, so both Boni and Bulbul have access to it. This description is reflected in the Permissions table shown in

Table 20.6

.

Table 20.6. The Permissions Table

ObjectID UserID

1 1

1 2

2 1

3 1

4 1

4 2

5 2

6 1

7 1

Team-Fly ®

8 1

9 2

10 2

11 2

The Code

After the database is in place, the coding part comes easy. In fact, with a complete system like this, you need only three files and one bean for database and object manipulation. The three files are as follows:

Login.html. A simple HTML file for users to type in their user name and password.

DisplayObjects.jsp. A jsp file that displays all objects in a particular folder. This file also contains the form to upload a file into a folder.

DownloadObject.jsp. A jsp file that fetches a file and sends it to the browser as an attachment.

The DBBean Bean

The DBBean bean does most of the work. You use it to connect to the database, get all objects in a particular folder, and get a filename for download. Of particular importance are the two connect methods. The first method is the one that receives three parameters: url, userName, and password.

The url is your JDBC URL, whereas userName and password are the connection details that you need to get access to the database. You use only one user name and one password for getting a database connection. This user name and password pair is used by the system only and is referred to in the bean as dbUserName and dbPassword. All application end users know nothing about this.

Don't confuse them with the user name and password that belong to a user. The latter are used to get access to a particular object in the database tables.

The second connect method accepts no parameter. You use this when you want to use the default values in the bean or you have passed those three arguments in previous statements (you set the url, dbUserName, and dbPassword using the setDbUrl, setDbUserName, and setDbPassword methods, respectively). There is another database-related method: setJDBCDriverName. You call this method if your driver name is that other than "sun.jdbc.odbc.JdbcOdbcDriver".

This example uses the JDBC-ODBC driver to access a Microsoft Access database on a Windows system. You must create a Data Source Name (DSN) called docman for the application to work.

The choice of database is your decision. You need only to make sure that you use the correct

JDBC driver. Because of the SQL statements used, as stated earlier, your database must support sub-queries.

The following is the code for the connect methods: try {

Class.forName( JDBCDriverName );

connection = DriverManager.getConnection(url,

userName, password);

} catch (Exception e) {}

Note

The code for the connect methods could be different, depending on your database JDBC driver. Refer to your JDBC driver documentation for details.

409

The DBBean also has a static final String called DATA_PATH that contains the physical path to a special directory that will host all the uploaded files. You can change the value of this string to any directory you want to use. For security purposes, however, make sure the directory is outside your application directory.

The other methods used in the bean are listed in the following sections.

verifyUser(String userName, String password)

Use this method to verify that the user is authorized. This method checks the Users table for the

UserName userName and Password password. The method returns true if it can find the user name and password in the table; otherwise, it returns false (not an authorized user). The SQL statement used is this:

SELECT ID FROM Users

WHERE UserName=userName AND Password = password

getDataPath()

This method returns the physical directory on the server where you store all the files. You use this method when downloading or uploading a file. The data path must be set to a directory outside the virtual host.

getFolderName(String id, String userName, String password)

You call this method in the DisplayObjects.jsp to get the folder name of the current folder. You need this information because you need to display the folder name to make users aware of their position in the hierarchy tree. You might think that you could easily get the folder name and parent ID by using the following SQL statement:

SELECT Name, ParentID FROM Objects WHERE ID=id

However, you want to make sure that only users with sufficient permission can get information about specific folders. Therefore, you use the following more complex SQL statement instead:

SELECT O.Name, O.ParentID

FROM Objects O, Permissions P, Users U

WHERE O.ID = id

AND O.ID = P.ObjectID

AND P.UserID = U.ID

AND U.UserName = userName

AND U.Password = password

getParentId()

This method returns the object ID of the parent folder for the current folder. The SQL statement that retrieves a ParentID only if the user has permission to view the parent object is as follows:

SELECT O.ParentID

FROM Objects O, Users U, Permissions P

WHERE O.ID=objectID

AND O.ParentID = P.ObjectID

AND P.UserID = U.ID

AND U.UserName = userName

AND U.Password = password

410

getChildObjects(String parentId, String userName, String password)

This method returns an ArrayList containing all child objects in the current folder. You will need the ID, Type, and Name of each object. These three fields are joined together into a string and each field is separated by a comma. Again, instead of using the following SQL statement:

SELECT ID, Type, Name

FROM Objects

WHERE ParentID = id

Use the more "secure" SQL statement:

SELECT ID, Type, Name

FROM Objects

WHERE ParentID =

(SELECT ObjectID FROM Permissions

WHERE ObjectID = id

AND UserID =

(SELECT ID FROM Users

WHERE UserName = userName

AND Password = password

)

)

ORDER BY Type ASC

The ORDER BY clause is there to guarantee that all folders (Type=0) will appear first.

getFilename(String objectId, String userName, String password)

This method is used to get the filename of the file object the user requests to download. The following SQL statement is used to guarantee that only users who have permission to access this file can download it:

SELECT Name

FROM Objects

WHERE ID =

(SELECT ObjectID FROM Permissions

WHERE ObjectID = objectId

AND UserID =

(SELECT ID FROM Users

WHERE UserName = userName

AND Password = password

)

)

getCookie(javax.servlet.http.HttpServletRequest request, String cookie)

This method returns the value of a cookie if the cookie is found in the HTTP request; otherwise, it returns null. Finding a cookie is done by looping the Cookie array of the HTTP request, comparing the cookie sought and the name of each cookie in the array, as follows:

Cookie cookies[] = request.getCookies(); if (cookies != null)

for (int i=0; i<cookies.length; ++i)

if (cookies[i].getName().equals(cookie))

return cookies[i].getValue();

411

Note

The complete code for the DBBean method is given later in this chapter in

Listing 20.2

.

Some methods not described here will also be explained later.

hasUploadPermission(String id, String userName, String password)

This method is called when the user tries to upload a file. It returns true if the user can upload a file into a directory whose identifier is specified as the id argument.

synchronized public int getLastObjectId()

This method returns the last object identifier in the Objects table. The output of this method plus one is the identifier for the next object to be uploaded.

insertObject(String parentId, String objectId, String filename)

This method inserts a row into the Tables object and is called when uploading a file.

insertPermissions(String parentId, String objectId)

This method inserts a row in the Permissions table for a given object and the user who uploads the file.

The complete code of the DBBean class is given in

Listing 20.1

.

Listing 20.1 The DBBean

package docman; import java.sql.*; import java.util.ArrayList; import java.io.FileOutputStream; import java.io.File; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.Cookie; public class DBBean {

public static final String DATA_PATH =

"C:\\123Data\\JavaProjects\\docman\\Data\\";

public String getDataPath() {

return DATA_PATH;

}

// database connection

private Connection connection=null;

// JDBC URL, change the string value below

// appropriately

String dbUrl = "jdbc:odbc:docman";

// user name for database access

String dbUserName = "";

// password for database access

String dbPassword = "";

// JDBC driver name, the value depends

// on the driver you are using

412

String JDBCDriverName =

"sun.jdbc.odbc.JdbcOdbcDriver";

public void setUrl(String dbUrl) {

// this method allows the JDBC URL to be changed

// if the different one from the default

// is needed

this.dbUrl = dbUrl;

}

public void setDbUserName(String dbUserName) {

// this method allows the database

// user name to be changed

this.dbUserName = dbUserName;

}

public void setDbPassword(String dbPassword) {

// this method allows the database

// password to be changed

this.dbPassword = dbPassword;

}

public void setJDBCDriverName

(String JDBCDriverName) {

// this method allows the database

// JDBC driver to be changed

this.JDBCDriverName = JDBCDriverName;

}

public void connect() {

// try to connect to the database

// using url, username, and password

// previously set

connect(dbUrl, dbUserName, dbPassword);

}

public void connect

(String url, String userName, String password) {

// try to connect to the database

// using url, username, and password

// passed as parameters

try {

Class.forName( JDBCDriverName);

connection = DriverManager.getConnection(url,

userName, password);

}

catch (Exception e) {}

}

public ArrayList getChildObjects(String id,

String userName, String password) {

// the return value;

ArrayList records = new ArrayList();

try {

if (connection == null)

connect();

String sql = "SELECT ID, Type, Name" +

" FROM Objects" +

" WHERE ParentID=" +

413

" (SELECT ObjectID FROM Permissions" +

" WHERE ObjectID=" + id +

" AND UserID=" +

" (SELECT ID FROM Users" +

" WHERE UserName='" + userName + "'" +

" AND Password='" + password + "'))" +

" ORDER BY Type ASC";

Statement s = connection.createStatement();

ResultSet r = s.executeQuery( sql );

while(r.next()) {

records.add(r.getString("ID") + "," +

r.getString("Type") + "," +

r.getString("Name"));

}

s.close(); // Also closes ResultSet

}

catch(Exception e) {

e.printStackTrace();

}

return records;

}

public String getCookie(

HttpServletRequest request, String cookie) {

// returns the cookie value if the cookie

// is found in request; otherwise returns null

Cookie cookies[] = request.getCookies();

if (cookies != null)

for (int i=0; i<cookies.length; ++i)

if (cookies[i].getName().equals(cookie))

return cookies[i].getValue();

return null;

}

public String getParentId(String objectId,

String userName, String password) {

String parentId = null;

String sql = "SELECT O.ParentID" +

" FROM Objects O, Users U, Permissions P" +

" WHERE O.ID=" + objectId +

" AND O.ParentID = P.ObjectID" +

" AND P.UserID = U.ID" +

" AND U.UserName='" + userName + "'" +

" AND U.Password='" + password + "'";

try {

if (connection == null)

connect();

Statement s = connection.createStatement();

// SQL code:

ResultSet r = s.executeQuery( sql );

while(r.next()) {

parentId = r.getString("ParentID");

}

s.close(); // Also closes ResultSet

}

catch(Exception e) { }

return parentId;

}

414

public boolean verifyUser(String userName,

String password) {

String sql = "SELECT ID FROM Users" +

" WHERE UserName='" + userName + "'" +

" AND Password='" + password + "'";

boolean retval = false;

try {

if (connection == null)

connect();

Statement s = connection.createStatement();

ResultSet r = s.executeQuery( sql );

if (r.next()) {

retval = true;

}

s.close(); // Also closes ResultSet

}

catch(Exception e) {

return false;

}

return retval;

}

public String getFolderName(String id,

String userName, String password) {

String folderName = null;

String sql = "SELECT O.Name, O.ParentID" +

" FROM Objects O, Permissions P, Users U" +

" WHERE O.ID=" + id +

" AND O.ID = P.ObjectID" +

" AND P.UserID = U.ID" +

" AND U.UserName='" + userName + "'" +

" AND U.Password = '" + password + "'";

try {

if (connection == null)

connect();

Statement s = connection.createStatement();

ResultSet r = s.executeQuery( sql );

while(r.next()) {

folderName = r.getString("Name");

}

s.close(); // Also closes ResultSet

}

catch(Exception e) { }

return folderName;

}

public String getFilename(String objectId,

String userName, String password) {

String filename = null;

String sql = "SELECT Name" +

" FROM Objects" +

" WHERE ID=" +

" (SELECT ObjectID FROM Permissions" +

" WHERE ObjectID=" + objectId +

" AND UserID=" +

" (SELECT ID FROM Users" +

" WHERE UserName='" + userName + "'" +

" AND Password='" + password + "'))";

try {

if (connection == null)

connect();

415

java.sql.Statement s =

connection.createStatement();

java.sql.ResultSet r = s.executeQuery( sql );

if (r.next())

filename = r.getString("Name");

s.close(); // Also closes ResultSet

}

catch (Exception e) {}

return filename;

}

public boolean hasUploadPermission(String id,

String userName, String password) {

boolean retval = false;

try {

if (connection == null)

connect();

String sql = "SELECT ObjectID FROM Permissions" +

" WHERE ObjectID=" + id +

" AND UserID=" +

" (SELECT ID FROM Users" +

" WHERE UserName='" + userName + "'" +

" AND Password='" + password + "')";

Statement s = connection.createStatement();

ResultSet r = s.executeQuery( sql );

while(r.next()) {

retval = true;

}

s.close(); // Also closes ResultSet

}

catch(Exception e) {

e.printStackTrace();

}

return retval;

}

synchronized public int getLastObjectId() {

int retval = 0;

try {

if (connection == null)

connect();

String sql = "SELECT MAX(ID) AS LastID FROM Objects";

Statement s = connection.createStatement();

ResultSet r = s.executeQuery( sql );

while (r.next())

retval = Integer.parseInt(r.getString("LastID"));

s.close(); // Also closes ResultSet

}

catch(Exception e) {}

return retval;

}

public void insertObject(String parentId,

String objectId, String filename) {

416

try {

if (connection == null)

connect();

// insert record into the Objects table

String sql = "INSERT INTO Objects" +

" (ID, ParentID, Type, Name)" +

" VALUES" +

" (" + objectId +

"," + parentId +

",1," +

"'" + filename + "')";

Statement s = connection.createStatement();

ResultSet r = s.executeQuery( sql );

s.close();

}

catch(Exception e) {}

}

public void insertPermissions(String parentId,

String objectId) {

try {

if (connection == null)

connect();

// insert records to the Permissions table

String sql = "INSERT INTO Permissions" +

" (ObjectID, UserID)" +

" SELECT " + objectId + ", UserID" +

" FROM Permissions" +

" WHERE ObjectID=" + parentId;

Statement s = connection.createStatement();

ResultSet r = s.executeQuery( sql );

s.close();

}

catch(Exception e) {}

}

}

The Pages

The project has three JSP pages, each of which is described in the following sections.

Login.html

Login.html, the first page in the application, is a simple HTML file with a form whose ACTION

attribute is set to "DisplayObjects.jsp". The HTML code is given in Listing 20.2

and the page is

shown in

Figure 20.3

.

Figure 20.3. The Login page.

417

Listing 20.2 Login.html

<HTML>

<HEAD>

<TITLE>Login Page</TITLE>

</HEAD>

FL

Y

<BODY>

<H2>Door Never Closed Pty Ltd</H2>

<TABLE BORDER="0">

TE

<TR>

<TD>User Name</TD>

AM

<TD><INPUT TYPE="TEXT" NAME="userName"></TD>

</TR>

<TR>

<TD>Password</TD>

<TD><INPUT TYPE="PASSWORD" NAME="password"></TD>

</TR>

<TR>

<TD COLSPAN="2" ALIGN="RIGHT">

<INPUT TYPE="SUBMIT" VALUE="LOGIN">

</TD>

</TR>

</TABLE>

</FORM>

</BODY>

</HTML>

DisplayObjects.jsp

After the user types the user name and password and presses the Submit button in Login.html, the

HTTP request is processed by the DisplayObjects.jsp page. The page first checks the validation of

Team-Fly ®

the user name and password. If the user name and password are not valid, the user is redirected back to the Login page. If the entries are valid, the page tries to display the objects.

Cookies are used so that the user needs to log in only once. After a successful login happens, the user name and password are sent to the browser as cookies. These cookies will be sent back to the server on the next HTTP request. The cookies live until the user closes the browser.

The code for DisplayObjects.jsp is given in

Listing 20.3

.

Listing 20.3 The DisplayObjects.jsp

<%@ page import="java.util.ArrayList" %>

<%@ page import="java.util.StringTokenizer" %>

<jsp:useBean id="DBBeanId" scope="page"

class="docman.DBBean" />

<%

// check HTTP request for userName and password

// for request from the Login page

String userName = request.getParameter("userName");

String password = request.getParameter("password");

if (userName == null || password == null) {

// either userName or password is not found,

// the request is not from the Login page,

// check cookies

userName =

DBBeanId.getCookie(request, "userName");

password =

DBBeanId.getCookie(request, "password");

}

if (userName == null || password == null) {

// userName and password still not found

// this must be an illegal attempt to bypass

// the Login page

response.sendRedirect("Login.html");

}

// now userName and password are found,

// verify if it is an authorized user

if (!DBBeanId.verifyUser(userName, password))

response.sendRedirect("Login.html");

else {

//authorized user, create cookies here

Cookie cookieUserName =

new Cookie("userName", userName);

Cookie cookiePassword =

new Cookie("password", password);

response.addCookie(cookieUserName);

response.addCookie(cookiePassword);

}

%>

<HTML>

<HEAD>

<TITLE>DisplayObjects</TITLE>

</HEAD>

<BODY>

<%

// string containing javascript script

// built on the fly.

419

String js="";

// ––––––––––––––––––––––––––––––––––––––

String parentId = null;

// the current folder id

String id = request.getParameter("id");

boolean atRoot = false;

if (id == null)

id = "1"; // 1 is the root

if (id.equals("1"))

atRoot = true;

if (!atRoot) {

// display the link to go up one level.

// this link calls this same page,

// passing the parent id

parentId = DBBeanId.getParentId(id, userName,

password);

out.println("<A HREF=\"DisplayObjects.jsp?id="

+ parentId + "\">"

+ "<IMG SRC=\"images/Up.gif\" "

+ "BORDER=\"0\"></A><BR>");

}

String currentFolderName =

DBBeanId.getFolderName(id, userName, password);

if (currentFolderName == null)

out.println("<B>You don't have permission to"

+ " view this folder.</B>");

else {

out.println("<B>Current Folder: "

+ currentFolderName + "</B>");

%>

<TABLE WIDTH=600>

<TR BGCOLOR=#D6D6D6>

<TD WIDTH=100>Name</TD>

<TD >Type</TD>

</TR>

<%

ArrayList records = DBBeanId.getChildObjects(

id, userName, password);

for (int i=0; i<records.size(); i++) {

String row = (String) records.get(i);

StringTokenizer st =

new StringTokenizer(row, ",");

String objectId = (String) st.nextElement();

String type = (String) st.nextElement();

String name = (String) st.nextElement();

String imagePath;

String objectLink;

String objectType;

if (type.equals("0")) { //folder

imagePath =

"<IMG SRC=\"images/folder.gif\" BORDER=\"0\">";

objectLink =

"<A HREF=\"DisplayObjects.jsp?id=" +

objectId + "\">";

420

objectType = "Folder";

// –––– this is for part 2 ––––––––––––––––––

//create javascript string for subfolders

js+="parent.appendFolder(parent.folderTree,"

+ id + ",parent.createFolder("

+ objectId + ",'" + name + "'));\n";

// ————————————————————-

}

else { //file

imagePath =

"<IMG SRC=\"images/file.gif\" BORDER=\"0\">";

objectLink =

"<A HREF=\"DownloadObject.jsp?id=" +

objectId + "\">";

objectType = "File";

}

out.println("<TR>\n");

out.println(" <TD>" + objectLink + imagePath

+ "</A>&nbsp;" + objectLink + name

+ "</A></TD>\n");

out.println(" <TD>" + objectType +

"</TD>\n");

out.println("</TR>\n");

}

%>

<TR>

<TD COLSPAN=2><HR></TD>

</TR>

<TR>

<TD COLSPAN=2 ALIGN=RIGHT>

<FORM METHOD=POST ENCTYPE=MULTIPART/FORM-DATA

ACTION=UploadObject.jsp>

<INPUT TYPE=HIDDEN NAME=parentId VALUE="<%=id%>">

<B>Upload File:</B>

<INPUT TYPE=FILE NAME=filename SIZE=25>

<INPUT TYPE=SUBMIT VALUE=Upload>

</FORM>

</TD>

</TR>

</TABLE>

<SCRIPT LANGUAGE="JavaScript"> parent.deleteSubfolder(parent.folderTree, <%=id%>);

<%=js%> parent.openFolderId=<%=id%>; parent.redrawTree();

</SCRIPT>

<%

}

%>

</BODY>

</HTML>

The DisplayObjects.jsp page is a recursive page that gets called from the link in its own body. It will first try to find the request parameters "userName" and "password".

421

String userName = request.getParameter("userName");

String password = request.getParameter("password");

This assumes that the request is from the Login page. The DisplayObjects.jsp page can also be called from within itself, however. If this is the case, the request parameters "userName" and

"password" aren't used, but there must be cookies by the same names, which means the code needs to check for the cookies in the HTTP request: if (userName == null || password == null) {

// either userName or password is not found,

// the request is not from the Login page,

// check cookies

userName =

DBBeanId.getCookie(request, "userName");

password =

DBBeanId.getCookie(request, "password");

}

If the cookies are not found, the HTTP request could be coming from someone who is trying to bypass the Login page, or it could be that the browser is not supporting cookies. In either case, the user is redirected to the Login page.

If user name and password entries are found, either as request parameters or as cookies, you can't assume that the request is coming from an authorized user. You still need to verify the user name and password against the database each time this page is requested. If verification fails, the page sends the user back to the Login page. If it is successful, the code creates the "userName" and

"password" cookies so that future requests from the user in the session will be successful. This is done in the following snippet: if (!DBBeanId.verifyUser(userName, password))

response.sendRedirect("Login.html"); else {

//authorized user, create cookies here

Cookie cookieUserName =

new Cookie("userName", userName);

Cookie cookiePassword =

new Cookie("password", password);

response.addCookie(cookieUserName);

response.addCookie(cookiePassword);

}

Every HTTP request for this page should bring with it the folder ID of the folder whose child objects are to be displayed. An exception to this is when the user first logs in. In this case, folder

ID 1 (root) is implied and the atRoot flag is set. The code is given here:

String id = request.getParameter("id"); boolean atRoot = false; if (id == null)

id = "1"; // 1 is the root if (id.equals("1"))

atRoot = true;

If the current folder is not the root, the folder must have a parent folder. The following code creates the link that the user can click to go back to the parent folder: if (!atRoot) {

422

// display the link to go up one level.

// this link calls this same page,

// passing the parent id

parentId = DBBeanId.getParentId(id, userName,

password);

out.println("<A HREF=\"DisplayObjects.jsp?id="

+ parentId + "\">"

+ "<IMG SRC=\"images/Up.gif\" "

+ "BORDER=\"0\"></A><BR>");

}

Note that this code uses the getParentID method of the DBBean to get the parent ID of the current folder. This parent ID will then be fed as the value for the ID parameter of the DisplayObjects.jsp page. This shows the recursive nature of this page.

To give users indication of their position in the hierarchy, you display the folder name here.

Notice that if an unauthorized user tries to bypass the Login page, the getFolderName method will return null:

String currentFolderName =

DBBeanId.getFolderName(id, userName, password); if (currentFolderName == null)

out.println("<B>You don't have permission to"

+ " view this folder.</B>"); else {

out.println("<B>Current Folder: "

+ currentFolderName + "</B>");

Now comes the main method that actually retrieves all the child objects of the current folder. The getChildObjects method of the DBBean returns an ArrayList. Again, only authorized users can view this:

ArrayList records =

DBBeanId.getChildObjects(id, userName, password);

Each item in the records ArrayList is a String containing the Object ID, Type, and Name of the child object separated by commas. Therefore, you need a StringTokenizer to get each field. The following code loops through the records ArrayList and gets the values of Object ID, Type, and

Name of each object: for (int i=0; i<records.size(); i++) {

String row = (String) records.get(i);

StringTokenizer st =

new StringTokenizer(row, ",");

String objectId = (String) st.nextElement();

String type = (String) st.nextElement();

String name = (String) st.nextElement();

String imagePath;

String objectLink;

String objectType;

.

.

.

}

If you want to give users a descriptive visual interface, use different icons to represent files and folders. To be precise, for each folder, use the Folder.gif image, and for each file, use the File.gif image. The other difference is the destination links of each type. When the user clicks on a folder,

423

the application will display all the child objects of that folder that the user has permission to view.

This will call the DisplayObjects.jsp. When the user clicks on a file, however, the application will send the file as an attachment to the browser if the user has permission to view that file. This is depicted in the following code:

if (type.equals("0")) { //folder

imagePath =

"<IMG SRC=\"images/folder.gif\" BORDER=\"0\">";

objectLink =

"<A HREF=\"DisplayObjects.jsp?id=" +

objectId + "\">";

objectType = "Folder";

}

else { //file

imagePath =

"<IMG SRC=\"images/file.gif\" BORDER=\"0\">";

objectLink =

"<A HREF=\"DownloadObject.jsp?id=" +

objectId + "\">";

objectType = "File";

}

And finally display the child objects. out.println("<TR>\n"); out.println(" <TD>" + objectLink + imagePath +

"</A>&nbsp;" + objectLink + name +

"</A></TD>\n"); out.println(" <TD>" + objectType + "</TD>\n"); out.println("</TR>\n");

Figure 20.4

shows this page in action.

Figure 20.4. The DisplayObjects.jsp page.

424

The DisplayObjects.jsp page displays the list of objects in a directory and a form the user can use to upload a file to the directory.

DownloadObject.jsp

The DownloadObject.jsp page is given in

Listing 20.4

.

Listing 20.4 The DownloadObject.jsp Code

<jsp:useBean id="dbBean" scope="page" class="docman.DBBean" />

<jsp:useBean id="downloadBean" scope="page" class="com.brainysoftware.web.FileDownloadBean" />

<%

String objectId = request.getParameter("id");

String userName = dbBean.getCookie(request, "userName");

String password = dbBean.getCookie(request, "password");

if (userName == null || password == null)

response.sendRedirect("Login.html");

// 'userName' and 'password' cookies are found

// now let's see if user has access to the file

String filename = dbBean.getFilename(objectId, userName, password);

if (filename == null)

response.sendRedirect("Login.html");

else {

downloadBean.forceFilename(filename);

downloadBean.download(response, dbBean.getDataPath() + objectId);

}

%> </