Instructor's Resource Manual to Programming the World Wide Web Third Edition R.W. Sebesta Preface Table of Contents Preface OVERVIEW It is difficult to overestimate the effect the World Wide Web has had on the day-to-day lives of people, at least those in the developed countries. In just a few years, we have learned to use the Web for a myriad of disparate tasks, ranging from the mundane task of shopping for airline tickets to the crucial early- morning gathering of business news for a high-stakes day trader. The speed at which millions of Web sites have appeared would seem to indicate that the technologies used to build them were sitting on the shelf, fully developed and ready to use, even before the Web was developed. Also, one might guess that the tens of thousands of people who built those sites were sitting around unemployed, waiting for an opportunity and already possessing the knowledge and abilities required to carry out this mammoth construction task when it appeared. Neither of these was true. The need for new technologies was quickly filled by a large number of entrepreneurs, some at existing companies and some who started new companies. A large part of the programmer need was filled, at least to the extent to which it has been filled, by new programmers, some straight from high school. Many, however, were previously employed by other sectors of the software development industry. All of them had to learn to use new languages and new software systems. Until recently, programmers learned Web software technologies through company in-house training, a scattering of courses focused on one specific Web technology at colleges and universities, or on their own. A visit to a local bookstore will turn up a large supply of books on those technologies aimed at the practicing professional. In the last few years college courses have begun to appear that attempt to cover a broad spectrum of Web programming technologies. One difficulty encountered by those teaching these courses is the lack of a textbook that is targeted to their needs. Most of the books that discuss Web programming were written for professionals, rather than college students. Such books are typically written to fulfill the needs of professionals, which are quite different from those of college students. One major difference between an academic book and a professional book lies in the assumptions made by the author about the prior knowledge and experience of the audience. The backgrounds of professionals vary widely, making it difficult to assume much of anything. On the other hand, a book written for junior computer science majors can make some definite assumptions about the background of the reader. This book is written for those students. The goal of this book is to provide the reader with a comprehensive introduction to the programming tools and skills required to build and maintain server sites on the Web. A wide variety of technologies are used in the construction of a Web site. There are now many books available, for professionals that focus on these technologies. For example, there are dozens of books that specifically address only XHTML. The same is true for a half-dozen other technologies. This book provides an overview of how the Web works, as well as descriptions of many of the most widely used Web technologies. The first and second editions of this book were used to teach a junior-level Web programming course at the University of Colorado at Colorado Springs. The challenge for students in the course is to learn to use several different programming languages and technologies in one semester. A heavy load of programming exercises is essential to the success of the course. Students build a basic, static Web site using only XHTML as the first assignment. Throughout the remainder of the semester they add features to their site as the new technologies are discussed in the course. Our students’ prior course work in Java, data structures, and assembly language are helpful, as is the fact that many of them know some XHTML before taking the course. The most important prerequisite to the material of this book is a solid background in programming in some language that supports object-oriented programming. It is helpful to have some knowledge of a second programming language and a bit of UNIX, which helps with the Perl part of the course. Also, UNIX is still a popular platform choice for Web servers. Familiarity with a second language makes learning the new languages easier. TABLE OF CONTENTS The book is organized into three sections, introduction (Chapter 1), client-side technologies (Chapters 2–8), and server-side technologies (Chapters 9–14). Chapter 1 lays the groundwork for the rest of the book. A few fundamentals are introduced, including the history and nature of the Internet, the World Wide Web, browsers, servers, URLs, MIME types, and HTTP. Also included in Chapter 1 are brief overviews of the most important topics of the rest of the book. Chapter 2 provides an introduction to XHTML, including images, links, lists, tables, frames, and forms. Small examples are used to illustrate the many XHTML elements that are discussed in this chapter. The topic of Chapter 3 is Cascading Style Sheets, which have quickly become the standard way of imposing style on the content specified in XHTML tags. Because of the size and complexity of the topic, the chapter does not cover all of the aspects of style sheets. The topics discussed are levels of style sheets, style specification formats, selector formats, property values, and color. Among the properties covered are those for fonts, lists, and margins. Small examples are used to illustrate the subjects being discussed. Chapter 4 introduces the core of JavaScript, a powerful language that could be used for a variety of different applications. Our interest, of course, is its use in Web programming. Although JavaScript has become a large and complex language, we use the student’s knowledge of programming in some other language to leverage our discussion, thereby providing a useful introduction to the language in a manageably small number of pages. Topics covered are the object model of JavaScript, its control statements, objects, arrays, functions, constructors, and pattern matching. In Chapter 5 we discuss some of the features of JavaScript that are related to XHTML documents. Included is the use of the basic and DOM 2 event and event-handling model, which can be used in conjunction with some of the elements of XHTML documents. Perhaps the most exciting and interesting application of JavaScript is for building dynamic XHTML documents using the Document Object Model (DOM). Chapter 6 provides descriptions of a collection of some of the document changes that can be made using JavaScript and the DOM. Included are element positioning, moving elements, changing the visibility of elements, changing the color, style, and size of text, changing the content of tags, changing the stacking order of overlapped elements, slow movement of elements, and dragging and dropping elements. Java applets are described in Chapter 7. First, the fundamentals of applet activities and the paintComponent method are introduced. Then, the <object> tag and applet parameters are discussed. Next, the chapter introduces the graphics that can be created by applets. Applets that can interact with the user through Swing widgets are then covered. Java is now being used in the introductory programming sequence at many colleges and universities. This allows us to discuss Java applets without first introducing Java. For those institutions that do not use Java as the language vehicle for their introductory programming courses, we provide a quick introduction to Java in an appendix. Chapter 8 presents an introduction to XML, which provides the means to design topic-specific markup languages that can be shared among users with common interests. Included are the syntax and document structure used by XML, data type definitions, namespaces, schemas, and the display of XML documents with both Cascading Style Sheets and XML Transformations. Also included is an introduction to Web services and XML processors. Chapter 9 introduces the characteristics and capabilities of Perl as a general-purpose programming language. Both before and since the arrival of the Web, the power and flexibility of Perl have been used on a variety of non- Web applications, including UNIX system administration and as the language for many of the small to medium size programming tasks formally done in C. For the most part, we limit our focus on Perl to those parts of the language that are needed for CGI programming. Control statements, arrays, hashes, references, functions, pattern matching, and file input and output are discussed. Chapter 10 introduces the use of Perl for Common Gateway Interface (CGI) programming. Although there are now alternatives to CGI, it is still widely used, and when it is, it is most often done in Perl. CGI and CGI linkage are introduced first. Then the form of query strings for form data is described. Finally, the CGI.pm module is introduced, which greatly simplifies CGI programming in Perl. Several examples are used to show how common CGI tasks are designed and programmed in Perl using CGI.pm. Java servlets and JSP are discussed in Chapter 11. The chapter introduces the mechanisms for building Java servlets and presents several examples of how servlets can be used to present interactive Web documents. Then, two approaches to storing information on clients using servlets, cookies and session tracking, are introduced and illustrated with examples. Finally, JSP is introduced through a series of examples. Chapter 12 introduces PHP, a server-side scripting language that is currently gaining popularity, especially as a database access language. The basics of the language are discussed, as well as the use of cookies and session tracking. The use of PHP as a Web database access language is covered in Chapter 14. Chapter 13 is an introduction to ASP.NET, though it begins with a brief introduction to C#. ASP.NET controls are among the topics discussed in this chapter. Constructing Web services with ASP.NET is also introduced. Chapter 14 provides an introduction to database access through the Web. This chapter includes an introduction to the nature of relational databases, architectures for database access, the structured query language, SQL, and the free database system, MySQL. Then, three approaches to Web access to databases are discussed: using Perl, using PHP, and using Java JDBC. The JDBC section is lengthy, including a complete Java database application program, as well as metadata and the use of JDBC in servlets. All of the program examples in the chapter use MySQL. This book includes an appendix that introduces Java to those who have experience with C++ and object-oriented programming. Students who do not know Java can learn enough of the language from this appendix to allow them to understand the Java applets, servlets, JSP, and JDBC that appear in this book. SUPPORT MATERIALS The supplements for the book are available at Addison-Wesley’s Web site www.aw.com/cssupport. Support materials available to all readers of this book include A set of lecture notes in the form of PowerPoint files. The notes were developed to be the basis for class lectures on the book material. Code for example programs PowerPoint slides of all the figures Additional support material including solutions to selected exercises are available only to instructors adopting this textbook for classroom use. Please contact your school’s Addison-Wesley representative for information on obtaining access to this material. SOFTWARE AVAILABILITY Most of the software systems described in this book are available free to students. These include browsers, which provide an interpreter for JavaScript and the Java Virtual Machine. Also, Perl, PHP, and Java language processors, as well as Java class libraries to support servlets and Java JDBC, are available and free. ASP.NET is supported by the .NET software available from Microsoft. DIFFERENCES BETWEEN THE SECOND EDITION AND THE THIRD EDITION The third edition differs significantly from the second. Chapter 13, on ASP.NET, is entirely new. Chapter 11 was dramatically changed: the material on Web servers was moved to Chapter 1 and a lengthy section on JSP was added. Chapter 3 was reorganized to a more rational order. Also, sections were added on borders and selector formats. Chapter 5 was also reorganized. A section on Web services was added to Chapter 8. (The new Chapter 13 also includes a section on Web services.) Finally, the section on running applets in Java threads in Chapter 7 was eliminated. Throughout the book, the XHTML was updated to conform to the XHTML 1.1 recommendation, and all documents were validated under the 1.1 standard. Also, numerous small changes were made to improve the correctness and clarity of the material. ACKNOWLEDGEMENTS The quality of this book was significantly improved as a result of the extensive suggestions, corrections, and comments provided by its reviewers. It was reviewed by: Dunren Che Southern Illinois University Richard C. Deter Middle Tennessee State University George Holmes University of Arkansas Kadathur Lakshmanan State University of New York at Brockport Tim Margush University of Akron Robert Noonan College of William and Mary Jeff Offutt George Mason University Marius C. Silaghi Florida Institute of Technology Chen-chi Shing Radford University Donald S. Szarkowicz Indiana University Northwest Michael Weiss Carleton University Jonwook Woo California State University, Los Angeles Tom Wulf University of Cincinnati Mir Farook Ali Elizabeth Leboffee Matt Goldstein, Editor, Katherine Harutunian, Project Editor, Patty Mahtani, Managing Editor, and Sarah Bartlett, Production Assistant, all deserve my gratitude for their encouragement and help in completing the manuscript. Also, thanks to Tarida Anantachai at Argosy Publishing for quickly converting the collection of files I provided into a bound book. Finally, I thank my children, Jake and Darcie, for their patience in enduring my absence from them throughout the many hours I invested in writing this book. Contents Preface xix 1 Fundamentals 1 1.1 A Brief Introduction to the Internet 2 1.1.1 Origins 2 1.1.2 What the Internet Is 3 1.1.3 Internet Protocol Addresses 3 1.1.4 Domain Names 4 1.2 The World Wide Web 6 1.2.1 Origins 6 1.2.2 Web or Internet? 7 1.3 Web Browsers 7 1.4 Web Servers 8 1.4.1 Web Server Operation 8 1.4.2 General Server Characteristics 9 1.4.3 Apache 10 1.4.4 IIS 11 1.5 Uniform Resource Locators 12 1.5.1 URL Formats 12 1.5.2 URL Paths 13 1.6 Multipurpose Internet Mail Extensions 14 1.6.1 Type Specifications 14 1.6.2 Experimental Document Types 15 1.7 The Hypertext Transfer Protocol 16 1.7.1 The Request Phase 16 1.7.2 The Response Phase 18 1.8 The Web Programmer’s Toolbox 19 1.8.1 Overview of XHTML 20 1.8.2 Tools for Creating XHTML Documents 20 1.8.3 Plug-ins and Filters 21 1.8.4 Overview of XML 22 1.8.5 Overview of JavaScript 22 1.8.6 Overview of Java 23 1.8.7 Overview of Perl 24 1.8.8 Overview of PHP 24 1.9 Summary 25 Review Questions 26 Exercises 28 2 Introduction to XHTML 29 2.1 Origins and Evolution of HTML and XHTML 30 2.1.1 Versions of HTML and XHTML 30 2.1.2 HTML versus XHTML 31 2.2 Basic Syntax 32 2.3 Standard XHTML Document Structure 33 2.4 Basic Text Markup 35 2.4.1 Paragraphs 35 2.4.2 XHTML Document Validation 37 2.4.3 Line Breaks 38 2.4.4 Headings 39 2.4.5 Block Quotations 40 2.4.6 Font Styles and Sizes 42 2.4.7 Character Entities 44 2.4.8 Horizontal Rules 45 2.4.9 The meta Element 45 2.5 Images 45 2.5.1 Image Formats 45 2.5.2 The <img /> Tag 46 2.6 Hypertext Links 49 2.6.1 Links 49 2.6.2 Targets within Documents 52 2.6.3 Using Links 52 2.7 Lists 53 2.7.1 Unordered Lists 53 2.7.2 Ordered Lists 54 2.7.3 Definition Lists 57 2.8 Tables 58 2.8.1 Basic Table Tags 58 2.8.2 The rowspan and colspan Attributes 60 2.8.3 The align and valign Attributes 63 2.8.4 The cellpadding and cellspacing Attributes 64 2.8.5 Table Sections 66 2.9 Forms 66 2.9.1 The <form> Tag 67 2.9.2 The <input> Tag 67 2.9.3 The <select> Tag 71 2.9.4 The <textarea> Tag 73 2.9.5 The Submit and Reset Buttons 74 2.9.6 A Complete Form Example 75 2.10 Frames 79 2.10.1 Framesets 79 2.10.2 Frames 80 2.11 Syntactic Differences between HTML and XHTML 85 2.12 Summary 87 Review Questions 88 Exercises 90 3 Cascading Style Sheets 93 3.1 Introduction 94 3.2 Levels of Style Sheets 95 3.3 Style Specification Formats 96 3.4 Selector Forms 97 3.4.1 Simple Selector Forms 97 3.4.2 Class Selectors 98 3.4.3 Generic Selectors 99 3.4.4 id Selectors 99 3.4.5 Pseudo Classes 99 3.5 Property Value Forms 100 3.6 Font Properties 102 3.6.1 Font Families 102 3.6.2 Font Sizes 103 3.6.3 Font Styles 103 3.6.4 Font Weights 104 3.6.5 Font Shorthands 104 3.6.6 Text Decoration 106 3.7 List Properties 108 3.8 Color 111 3.8.1 Color Groups 112 3.8.2 Color Properties 112 3.9 Alignment of Text 113 3.10 The Box Model 116 3.10.1 Borders 116 3.10.2 Margins and Padding 119 3.11 Background Images 121 3.12 The <span> and <div> Tags 123 3.13 Summary 124 Review Questions 126 Exercises 127 4 The Basics of JavaScript 129 4.1 Overview of JavaScript 130 4.1.1 Origins 130 4.1.2 JavaScript and Java 130 4.1.3 Uses of JavaScript 131 4.1.4 Event-Driven Computation 132 4.1.5 Browsers and XHTML/JavaScript Documents 132 4.2 Object Orientation and JavaScript 133 4.2.1 JavaScript Objects 133 4.3 General Syntactic Characteristics 134 4.4 Primitives, Operations, and Expressions 136 4.4.1 Primitive Types 136 4.4.2 Numeric and String Literals 137 4.4.3 Other Primitive Types 138 4.4.4 Declaring Variables 138 4.4.5 Numeric Operators 139 4.4.6 The Math Object 140 4.4.7 The Number Object 140 4.4.8 The String Catenation Operator 141 4.4.9 Implicit Type Conversions 141 4.4.10 Explicit Type Conversions 142 4.4.11 String Properties and Methods 143 4.4.12 The typeof Operator 144 4.4.13 Assignment Statements 145 4.4.14 The Date Object 145 4.5 Screen Output and Keyboard Input 146 4.6 Control Statements 150 4.6.1 Control Expressions 150 4.6.2 Selection Statements 151 4.6.3 The switch Statement 152 4.6.4 Loop Statements 155 4.7 Object Creation and Modification 158 4.8 Arrays 160 4.8.1 Array Object Creation 160 4.8.2 Characteristics of Array Objects 160 4.8.3 Array Methods 163 4.9 Functions 165 4.9.1 Fundamentals 166 4.9.2 Local Variables 167 4.9.3 Parameters 167 4.9.4 The sort Method, Revisited 170 4.10 An Example 171 4.11 Constructors 172 4.12 Pattern Matching Using Regular Expressions 174 4.12.1 Character and Character-Class Patterns 174 4.12.2 Anchors 177 4.12.3 Pattern Modifiers 177 4.12.4 Other Pattern-Matching Methods of String 178 4.13 Another Example 179 4.14 Errors in Scripts 181 4.15 Summary 183 Review Questions 185 Exercises 187 5 JavaScript and HTML Documents 189 5.1 The JavaScript Execution Environment 190 5.2 The Document Object Model 191 5.3 Element Access in JavaScript 193 5.4 Events and Event Handling 196 5.4.1 Basic Concepts of Event Handling 196 5.4.2 Events, Attributes, and Tags 197 5.5 Handling Events from Body Elements 200 5.6 Handling Events from Button Elements 201 5.6.1 Plain Buttons 201 5.6.2 Checkboxes and Radio Buttons 202 5.7 Handling Events from Text Box and Password Elements 207 5.7.1 The Focus Event 207 5.7.2 Validating Form Input 209 5.8 The DOM 2 Event Model 217 5.8.1 Event Propagation 217 5.8.2 Event Handler Registration 218 5.8.3 An Example of the DOM 2 Event Model 220 5.9 The navigator Object 222 5.10 Summary 224 Review Questions 225 Exercises 226 6 Dynamic Documents with JavaScript 6.1 Introduction 230 6.2 Element Positioning 230 6.2.1 Absolute Positioning 231 6.2.2 Relative Positioning 235 6.2.3 Static Positioning 236 6.3 Moving Elements 236 6.4 Element Visibility 239 6.5 Changing Colors and Fonts 241 6.5.1 Changing Colors 241 6.5.2 Changing Fonts 242 6.6 Dynamic Content 244 6.7 Stacking Elements 246 6.8 Locating the Mouse Cursor 250 229 6.9 Reacting to a Mouse Click 253 6.10 Slow Movement of Elements 254 6.11 Dragging and Dropping Elements 258 6.12 Summary 262 Review Questions 263 Exercises 264 7 Java Applets 267 7.1 Introduction 268 7.2 The Primary Applet Activities 270 7.3 The paintComponent Method 271 7.4 The <object> Tag 274 7.5 Applet Parameters 275 7.6 Simple Graphics 278 7.6.1 The Coordinate System 278 7.6.2 Lines 278 7.6.3 Rectangles 279 7.6.4 Polygons 280 7.6.5 Ovals 282 7.7 Color 282 7.8 Interactive Applets 283 7.8.1 Java Swing GUI Components 284 7.8.2 The Java Event Model 288 7.9 Summary 293 Review Questions 293 Exercises 294 8 Introduction to XML 297 8.1 Introduction 298 8.2 The Syntax of XML 300 8.3 XML Document Structure 303 8.4 Document Type Definitions 304 8.4.1 Declaring Elements 305 8.4.2 Declaring Attributes 307 8.4.3 Declaring Entities 308 8.4.4 A Sample DTD 309 8.4.5 Internal and External DTDs 310 8.5 Namespaces 312 8.6 XML Schemas 314 8.6.1 Schema Fundamentals 314 8.6.2 Defining a Schema 315 8.6.3 Defining a Schema Instance 316 8.6.4 An Overview of Data Types 317 8.6.5 Simple Types 318 8.6.6 Complex Types 319 8.6.7 Validating Instances of Schemas 321 8.7 Displaying Raw XML Documents 322 8.8 Displaying XML Documents with CSS 324 8.9 XSLT Style Sheets 326 8.9.1 Overview of XSLT 327 8.9.2 XSL Transformations for Presentation 328 8.10 XML Processors 335 8.10.1 The Purposes of XML Processors 336 8.10.2 The SAX Approach 337 8.10.3 The DOM Approach 337 8.11 Web Services 338 8.12 Summary 339 Review Questions 341 Exercises 342 9 The Basics of Perl 345 9.1 Origins and Uses of Perl 346 9.2 Scalars and Their Operations 346 9.2.1 Numeric and String Literals 347 9.2.2 Scalar Variables 348 9.2.3 Numeric Operators 349 9.2.4 String Operators 350 9.2.5 String Functions 351 9.3 Assignment Statements and Simple Input and Output 352 9.3.1 Assignment Statements 352 9.3.2 Keyboard Input 352 9.3.3 Screen Output 353 9.4 Control Statements 354 9.4.1 Control Expressions 355 9.4.2 Selection and Loop Statements 357 9.5 Fundamentals of Arrays 359 9.5.1 List Literals 359 9.5.2 Arrays 360 9.5.3 The foreach Statement 361 9.5.4 Built-In Functions for Arrays and Lists 362 9.5.5 An Example 364 9.6 Hashes 365 9.7 References 367 9.8 Functions 368 9.8.1 Fundamentals 368 9.8.2 Local Variables 369 9.8.3 Parameters 369 9.8.4 The sort Function, Revisited 370 9.8.5 An Example 371 9.9 Pattern Matching 373 9.9.1 The Basics of Patterns and Pattern Matching 373 9.9.2 Remembering Matches 377 9.9.3 Substitutions 377 9.9.4 The Transliterate Operator 378 9.10 File Input and Output 378 9.11 An Example 381 9.12 Summary 383 Review Questions 385 Exercises 386 10 Using Perl for CGI Programming 10.1 The Common Gateway Interface 390 10.2 CGI Linkage 392 10.3 Query String Format 395 10.4 The CGI.pm Module 397 10.4.1 Common CGI.pm Functions 397 10.4.2 A Complete Form Example 401 10.5 A Survey Example 407 10.6 Cookies 419 10.7 Summary 424 Review Questions 425 Exercises 426 389 11 429 Servlets and Java Server Pages 11.1 Overview of Servlets 430 11.2 Servlet Details 431 11.3 A Survey Example 435 11.4 Storing Information on Clients 442 11.4.1 Cookies 442 11.4.2 Session Tracking 451 11.5 Java Server Pages 456 11.5.1 Motivations for JSP 456 11.5.2 JSP Documents 457 11.5.3 Scriptlets 459 11.5.4 Expression Language 463 11.5.5 JSTL Control Action Elements 465 11.6 Summary 470 Review Questions 471 Exercises 472 12 Introduction to PHP 475 12.1 Origins and Uses of PHP 476 12.2 Overview of PHP 476 12.3 General Syntactic Characteristics 477 12.4 Primitives, Operations, and Expressions 479 12.4.1 Variables 479 12.4.2 Integer Type 479 12.4.3 Double Type 480 12.4.4 String Type 480 12.4.5 Boolean Type 480 12.4.6 Arithmetic Operators and Expressions 481 12.4.7 String Operations 482 12.4.8 Scalar Type Conversions 483 12.4.9 Assignment Operators 484 12.5 Output 484 12.6 Control Statements 486 12.6.1 Relational Operators 486 12.6.2 Boolean Operators 486 12.6.3 Selection Statements 486 12.6.4 Loop Statements 487 12.6.5 Alternative Compound Delimiters 487 12.6.6 An Example 488 12.7 Arrays 489 12.7.1 Array Creation 489 12.7.2 Accessing Array Elements 491 12.7.3 Dealing with Arrays 492 12.7.4 Sequential Access to Array Elements 493 12.7.5 Sorting Arrays 495 12.8 Functions 498 12.8.1 General Characteristics of Functions 498 12.8.2 Parameters 498 12.8.3 The Scope of Variables 500 12.8.4 The Lifetime of Variables 501 12.9 Pattern Matching 502 12.10 Form Handling 505 12.11 Files 511 12.11.1 Opening and Closing Files 511 12.11.2 Reading from a File 513 12.11.3 Writing to a File 514 12.11.4 Locking Files 514 12.12 Cookies 514 12.13 Session Tracking 515 12.14 Summary 516 Review Questions 517 Exercises 519 13 13.1 13.1.1 13.1.2 13.1.3 13.1.4 13.2 13.2.1 Introduction to ASP.NET 523 Overview of the .NET Framework 523 Background 523 The Common Language Runtime 524 .NET Languages 524 The Common Language Infrastructure 525 Introduction to C# 526 Origins 526 13.2.2 Primitive Types and Expressions 527 13.2.3 Data Structures 527 13.2.4 Control Statements 528 13.2.5 Classes, Methods, and Structures 529 13.2.6 Properties 530 13.2.7 Delegates 531 13.2.8 Program Structure 531 13.2.9 File Storage for Programs 532 13.3 Introduction to ASP.NET 533 13.3.1 The Basics 533 13.3.2 ASP.NET Documents 535 13.3.3 Code-Behind Files 537 13.4 ASP.NET Controls 539 13.4.1 HTML Controls 539 13.4.2 Life Cycle of a Simple ASP.NET Document 541 13.4.3 Page-Level Events 544 13.4.4 Control Events 545 13.4.5 Web Controls 547 13.4.6 Creating Control Elements with Code 548 13.4.7 Response Output for Controls 549 13.4.8 An Example 550 13.4.9 Validation Controls 552 13.5 Web Services 555 13.5.1 Constructing Web Services 555 13.5.2 Advertising Web Services 559 13.6 Summary 560 Review Questions 561 Exercises 563 14 14.1 14.2 14.2.1 14.2.2 14.2.3 14.2.4 14.2.5 14.2.6 14.2.7 14.3 14.3.1 14.3.2 14.3.3 14.3.4 14.3.5 14.3.6 Database Access through the Web 565 Relational Databases 566 An Introduction to the Structured Query Language 570 The CREATE TABLE SQL Command 570 The INSERT SQL Command 571 The SELECT SQL Command 571 The UPDATE SQL Command 572 The DELETE SQL Command 572 The DROP SQL Command 573 Joins 573 Architectures for Database Access 575 Client/Server Architectures 575 Database Access with Embedded SQL 576 The Microsoft Access Architecture 576 The Perl DBI/DBD Architecture 577 PHP and Database Access 577 The Java JDBC Architecture 577 14.4 The MySQL Database System 578 14.5 Database Access with Perl and MySQL 581 14.5.1 The DBI Module 581 14.5.2 An Example 583 14.6 Database Access with PHP and MySQL 586 14.6.1 Potential Problems with Special Characters 586 14.6.2 Connecting to MySQL and Selecting a Database 587 14.6.3 Requesting MySQL Operations 588 14.6.4 A PHP/MySQL Example 589 14.7 Database Access with JDBC and MySQL 596 14.7.1 Approaches to Using JDBC Outside the Web 596 14.7.2 JDBC and MySQL 597 14.7.3 A Complete JDBC/MySQL Example 601 14.7.4 Metadata 604 14.7.5 JDBC and Servlets 606 14.8 Summary 610 Review Questions 612 Exercises 613 APPENDIX Index 633 Introduction to Java 615 Solutions to Selected Exercises Chapter 2 Exercise 2.1 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e2_1.html This is a solution to Exercise 2.1 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 2.1 </title> </head> <body> <h2> Ruper B. Baggins </h2> <p> 1321 Causeway Circle <br /> Middle, Earth <br /> rbaggins@miderth.net<br /> </p> <hr /> <h3> Bush Watcher </h3> <p> <big> Forest Keepers, Limited </big> <br /> 14 Cranberry Way <br /> Middle, Earth <br /> <small> (no web site yet) </small> </p> </body> </html> Exercise 2.3 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e2_3.html This is a solution to Exercise 2.3 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 2.3 </title> </head> <body> <h2> Ruper B. Baggins </h2> <p> 1321 Causeway Circle <br /> Middle, Earth <br /> rbaggins@miderth.net<br /><br /> <a href = "e2_31.html"> Mr. Baggins' Background </a> </p> <hr /> <h3> Bush Watcher </h3> <p> <big> Forest Keepers, Limited </big> <br /> 14 Cranberry Way <br /> Middle, Earth <br /> <small> (no web site yet) </small> </p> </body> </html> <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e2_31.html This is part of the solution to Exercise 2.3 (The second document for the background info) --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 2.3 (background) </title> </head> <body> <p> Although we share the same family name, I am not in any way related to the famous (or is it infamous) adventurer, Bilbo. I have a lovely wife, Elvira, and two grown children, Max and Miriam. Max has chosen to follow me in my profession, which is described below. Miriam is a beekeeper for the town bookkeeper, who keeps bees as a second job. </p> <p> I am employed by Forest Keepers, Limited. My job, as I understand it, is to keep an eye on the 4 acres of wild cranberries that grow in the swamp at the edge of the village forest. I am required to file a daily report, in triplicate, on the condition of the cranberry bushes. To accomplish my task, I walk by and inspect every cranberry bush in the swamp every workday. My employer provides me with wading boots for my job. I pick up the boots at the office every weekday morning and turn them back in, after a thorough cleaning, after each workday. </p> </body> </html> Exercise 2.4 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e2_4.html A solution to Exercise 2.4 - an unordered list --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Unordered List </title> </head> <body> <h3> Grocery List </h3> <ul> <li> milk - 2%, 2 gallons </li> <li> bread - butter top wheat </li> <li> cheddar cheese - sharp, 1 lb. </li> <li> soup - vegetable beef, 3 cans </li> <li> hamburger - 80% fat free, 2 lbs. </li> <li> orange juice - not from concentrate, 1/2 gallon </li> <li> eggs - large, 1 dozen </li> </ul> </body> </html> Exercise 2.8 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e2_8.html A solution to Exercise 2.8 - a nested, ordered list --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> An Ordered List </title> </head> <body> <h3> My Uncles, Aunts, and Cousins </h3> <ol> <li> Violet Vinelli (my mother) </li> <li> Frederick Vinelli <ol> <li> Mary Vinelli </li> <li> Betty Ann Boop </li> <li> Bob Vinelli </li> <li> Roger Vinelli </li> </ol> </li> <li> Maxine Robinson <ol> <li> John Robinson </li> <li> Patty Robinson </li> <li> Lucille Robinson </li> </ol> </li> <li> Thomas Vinelli <ol> <li> Albert Vinelli </li> <li> Alison MacKinsey </li> <li> Alton Vinelli </li> </ol> </li> </ol> <ol> <li> Albert Alphonso (my father) </li> <li> Herbert Alphonso <ol> <li> Louise Alphonso </li> <li> Pam Alphonso </li> <li> Fred Alphonso </li> </ol> </li> <li> Ann Marie Predicate <ol> <li> George Predicate </li> <li> Michael Predicate </li> <li> Darcie Predicate </li> </ol> </li> <li> Ferdinand Alphonso <ol> <li> Noah Alphonso </li> <li> Leah Alphonso </li> <li> Jo Alphonso </li> </ol> </li> </ol> </body> </html> Exercise 2.9 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e2_9.html A solution to Exercise 2.9 - a simple table --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> A simple table </title> </head> <body> <table border = "border"> <caption> Trees </caption> <tr> <th> </th> <th> <th> <th> <th> </tr> <tr> <th> <td> <td> <td> <td> </tr> <tr> <th> <td> <td> <td> <td> </tr> <tr> <th> <td> <td> <td> <td> </tr> <tr> <th> <td> <td> <td> <td> </tr> </table> </body> </html> Pine </th> Maple </th> Oak </th> Fir </th> Average Height (feet) </th> 55 </td> 50 </td> 50 </td> 65 </td> Average Width (inches) </th> 18 </td> 26 </td> 24 </td> 28 </td> Typical Lifespan (years) </th> 150 </td> 230 </td> 310 </td> 135 </td> Leaf Type </th> Long needles </td> Broadleaf </td> Split leaf </td> Short needles </td> Exercise 2.10 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e2_10.html A solution to Exercise 2.10 - a simple table --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> A simple table </title> </head> <body> <table border = "border"> <caption> Tree Characteristics </caption> <tr> <td rowspan = "2" colspan = "2"> </td> <th colspan = "4"> Tree </th> </tr> <tr> <th> Pine </th> <th> Maple </th> <th> Oak </th> <th> Fir </th> </tr> <tr> <th rowspan = "4"> Characteristic </th> <th> Average Height (feet) </th> <td> 55 </td> <td> 50 </td> <td> 50 </td> <td> 65 </td> </tr> <tr> <th> Average Width (inches) </th> <td> 18 </td> <td> 26 </td> <td> 24 </td> <td> 28 </td> </tr> <tr> <th> Typical Lifespan (years) </th> <td> 150 </td> <td> 230 </td> <td> 310 </td> <td> 135 </td> </tr> <tr> <th> Leaf Type </th> <td> Long needles </td> <td> Broadleaf </td> <td> Split leaf </td> <td> Short needles </td> </tr> </table> </body> </html> Exercise 2.14 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.0 Frameset//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd"> <!-- e2_14.html A solution to Exercise 2.14 - frames --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Family Frames </title> </head> <frameset rows = "60%, 40%" cols = "25%, *"> <frame src = "mothers_side.html" /> <frame src = "blank.html" name = "mothers_descr" /> <frame src = "fathers_side.html" /> <frame src = "blank.html" name = "fathers_descr" /> </frameset> </html> <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- mothers_side.html Part of a solution to Exercise 2.14 - frames --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Mother's Side </title> </head> <body> <h3> My Mother's Side: </h3> <ul> <li> <a href = "georgia_descr.html" target = "mothers_descr"> Georgia (my mother) </a> </li> <li> <a href = "max_descr.html" target = "mothers_descr"> Max </a> </li> <li> <a href = "fred_descr.html" target = "mothers_descr"> Fred </a> </li> </ul> </body> </html> <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <!-- fathers_side.html Part of a solution to Exercise 2.14 - frames --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Father's Side </title> </head> <body> <h3> My Father's Side: </h3> <ul> <li> <a href = "mike_descr.html" target = "fathers_descr"> Mike (my father) </a> </li> <li> <a href = "mary_descr.html" target = "fathers_descr"> Mary </a> </li> <li> <a href = "dennis_descr.html" target = "fathers_descr"> Dennis </a> </li> </ul> </body> </html> <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- georgia_descr.html Part of a solution to Exercise 2.14 - frames --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Georgia </title> </head> <body> <p> Georgia was born in 1918 in Championville, North Dakota. She attended Championville High School, where she was on the varsity tennis team. </p> </body> </html> <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- max_descr.html Part of a solution to Exercise 2.14 - frames --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Max </title> </head> <body> <p> Max was born in 1921 in Championville, North Dakota. He attended Championville High School, where he was on the varsity football and baseball teams. </p> </body> </html> <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- fred_descr.html Part of a solution to Exercise 2.14 - frames --> <html> <head> <title> Fred </title> </head> <body> <p> Fred was born in 1924 in Championville, North Dakota. He attended Championville High School, where he was captain of the chess team. </p> </body> </html> <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- mike_descr.html Part of a solution to Exercise 2.14 - frames --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Mike </title> </head> <body> <p> Mike was born in 1914 in Losertown, South Dakota. He attended Loosertown High School, but was unable to finish for a variety of reasons. </p> </body> </html> <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- mary_descr.html Part of a solution to Exercise 2.14 - frames --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Mary </title> </head> <body> <p> Mary was born in 1917 in Losertown, South Dakota. She attended Loosertown High School, but after six years of serious effort, she gave it up. </p> </body> </html> <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- dennis_descr.html Part of a solution to Exercise 2.14 - frames --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Dennis </title> </head> <body> <p> Dennis was born in 1915 in Losertown, South Dakota. He attended Loosertown High School, but flunked more than half of the courses he took, so he did not graduate. </p> </body> </html> Chapter 3 Exercise 3.1 /* Book Layout Style Sheet */ h1 {font: bold 24pt Helvetica 'Times New Roman'} h2 {font: bold 20pt Helvetica 'Times New Roman'} h3 {font: bold 16pt Helvetica 'Times New Roman'} p {font: 12pt 'Times New Roman'} Exercise 3.2 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e3_2.html A solution to Exercise 3.2 - a styled table --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> A Styled Table </title> <style type = "text/css"> <!-td.win {font-size: 16pt; color: red;} td.lose {font-size: 14pt; color: blue;} --> </style> </head> <body> <table border = "border"> <caption style = "font-size: 18pt"> Football Scores </caption> <tr> <th> Team </th> <th> Score </th> </tr> <tr> <th style = "font-family: 'Century Gothic'; font-style: italic; color: gold;"> Colorado </th> <td class = "win"> 30 </td> </tr> <tr> <th style = "font-family: 'Century Gothic'; font-style: italic; color: red;"> Nebraska </th> <td class = "lose"> 29 </td> </tr> <tr> <th style = "font-family: 'Century Gothic'; font-style: italic; color: grey;"> Iowa State </th> <td class = "win"> 17 </td> </tr> <tr> <th style = "font-family: 'Century Gothic'; font-style: italic; color: blue;"> Kansas </th> <td class = "lose"> 10 </td> </tr> <tr> <th style = "font-family: 'Century Gothic'; font-style: italic; color: purple;"> Kansas State </th> <td class = "win"> 48 </td> </tr> <tr> <th style = "font-family: 'Century Gothic'; font-style: italic; color: green;"> Missouri </th> <td class = "lose"> 13 </td> </tr> </table> </body> </html> Exercise 3.4 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e3_4.html A solution for Exercise 3.4 - floating a text element --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Floating a text element </title> </head> <body> <p style = "float: left; width: 1.5in; margin-right: 10px; margin-bottom: 10px;" > My airplane soars like an eagle and handles like a hummingbird. </p> <p> The 210 is the flagship single-engine Cessna aircraft. Although the 210 began as a four-place aircraft, it soon acquired a third row of seats, stretching it to a six-place plane. The 210 is classified as a high-performance airplane, which means its landing gear is retractable and its engine has more than 200 horsepower. In its first model year, which was 1960, the 210 was powered by a 260-horsepower fuel-injected six-cylinder engine that displaced 471 cubic inches. The 210 is the fastest single-engine airplane ever built by Cessna. </p> </body> </html> Chapter 4 Exercise 4.1 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e4_1.html - A solution to Exercise 4.1 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 4.1 </title> </head> <body> <script type = "text/javascript"> <!-var number, square, cube; document.write("Number, Square, Cube <br /><br />"); for (number = 5; number < 16; number++) { square = number * number; cube = number * square; document.write(number + ", " + square + ", } // --> </script> </body> </html> " + cube + "<br />"); Exercise 4.2 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e4_2.html - A solution to Exercise 4.2 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 4.2 </title> </head> <body> <script type = "text/javascript"> <!-var first = 1, second = 1, next, count; document.write("First 20 Fibonacci Numbers <br/><br/>"); document.write("1 - 1 <br/> 2 - 1 <br/>"); for (count = 3; count <= 20; count++) { next = first + second; document.write(count + " - " + next + "<br/>"); first = second; second = next; } // --> </script> </body> </html> Exercise 4.4 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e4_4.html - A solution to Exercise 4.4 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 4.4 </title> </head> <body> <script type = "text/javascript"> <!-var first = 1, second = 1, next, count; number = prompt("How many Fibonacci numbers do you want? (3-50)", ""); if (number >= 3 && number <= 50) { document.write("First " + number + " Fibonacci Numbers <br /><br />"); document.write("1 - 1 <br/> 2 - 1 <br />"); for (count = 3; count <= number; count++) { next = first + second; document.write(count + " - " + next + "<br />"); first = second; second = next; } } else document.write("Error - number not in the range 3-50"); // --> </script> </body> </html> Exercise 4.6 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e4_6.html - A solution to Exercise 4.6 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 4.6 </title> </head> <body> <script type = "text/javascript"> <!-var first = 1, second = 1, next, count; str = prompt("Please input your sentence", ""); var words = str.split(" "); words = words.sort(); words_len = words.length; for (count = 0; count < words_len; count++) document.write(words[count] + "<br/>"); // --> </script> </body> </html> Exercise 4.7 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e4_7.html - A solution to Exercise 4.7 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 4.7 </title> <script type = "text/javascript"> <!-// A function to compare strings for reverse alphabetic order function dec_order(a, b) { if (a > b) return -1; else if (a < b) return 1; else return 0; } // --> </script> </head> <body> <script type = "text/javascript"> <!-var order, str, words, word_len, count; // Get the input str = prompt("Please input your sentence", ""); order = prompt("What order? (ascending or descending)", ""); // If the order is recognized, issue an error message if (order != "descending" && order != "ascending") document.write("Error - order is incorrectly specified <br/>"); // Otherwise, do the sort, depending on the requested order else { var words = str.split(" "); if (order == "ascending") words = words.sort(); else words = words.sort(dec_order); // Write out the results words_len = words.length; for (count = 0; count < words_len; count++) document.write(words[count] + "<br/>"); } // --> </script> </body> </html> Exercise 4.9 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e4_9.html - A solution to Exercise 4.9 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 4.9 </title> <script type = "text/javascript"> <!-// Function e_names // Parameter: an array of strings // Returns: the number of given strings that end // in either "ie" or "y" function e_names(names) { var len, index, count = 0; len = names.length; // Loop to use pattern matching to produce the count for (index = 0; index < len; index++) { position1 = names[index].search(/ie$/); position2 = names[index].search(/y$/); if (position1 + position2 > -2) count++; } return count; } // --> </script> </head> <body> <script type = "text/javascript"> <!-// Function e_names tester var new_names = new Array ("freddie", "bob", "mieke", "yahoo2", "georgey"); result = e_names(new_names); document.write("The number of special names is: " + result + "<br/>"); // --> </script> </body> </html> Exercise 4.14 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e4_14.html - A solution to Exercise 4.14 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 4.14 </title> <script type = "text/javascript"> <!-var result; // // // // // Function reverser Parameter: a number Returns: the number with its digits in reverse order Note: Math.floor must be used to get the integer part of the division operations function reverser(num) { var digit, position = 0; // If the number has just one digit, that's it if (num < 10) return num; // Get the first digit result = num % 10; num = Math.floor(num / 10); // Loop to produce the result for the rest do { digit = num % 10; result = 10 * result + digit; num = Math.floor(num / 10); } while (num >= 1); return result; } // --> </script> </head> <body> <script type = "text/javascript"> <!-// Function reverser tester var num1 = 2468, num2 = 7; result = reverser(num1); document.write("The reverse of 2468 is: " + result + "<br />"); result = reverser(num2); document.write("The reverse of 7 is: " + result + "<br />"); // --> </script> </body> </html> Chapter 5 Exercise 5.1 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e5_1.hmtl A solution to Exercise 5.1 - events with radio buttons --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 5.1 </title> <script language = "JavaScript"> // The event handler function to produce an alert message // about the chosen color function colorChoice (color) { switch (color) { case "red": alert("Your favorite color is red"); break; case "blue": alert("Your favorite color is blue"); break; case "green": alert("Your favorite color is green"); break; case "yellow": alert("Your favorite color is yellow"); break; case "orange": alert("Your favorite color is orange"); break; default: alert("Error in JavaScript function colorChoice"); break; } } </script> </head> <body> <h4> Choose your favorite color </h4> <form> <input type = "radio" name = "colorButton" value = onClick = "colorChoice('red')" /> Red <br /> <input type = "radio" name = "colorButton" value onClick = "colorChoice('blue')" /> Blue <br /> <input type = "radio" name = "colorButton" value = onClick = "colorChoice('green')" /> Green <br /> <input type = "radio" name = "colorButton" value = onClick = "colorChoice('yellow')" /> Yellow <br /> <input type = "radio" name = "colorButton" value = onClick = "colorChoice('orange')" /> Orange </form> </body> </html> "red" = "blue" "green" "yellow" "orange" Exercise 5.2 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e5_2.hmtl A solution to Exercise 5.2 - events with radio buttons --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 5.2 </title> <script language = "JavaScript"> // The event handler function to produce an alert message // about the chosen color function colorChoice () { var color; // Put the DOM address of the elements array in a local variable var radioElement = document.colorsForm.elements; // Determine which button was pressed for (var index = 0; index < radioElement.length; index++) { if (radioElement[index].checked) { color = radioElement[index].value; break; } } // Produce an alert message about the chosen color switch (color) { case "red": alert("Your favorite color is red"); break; case "blue": alert("Your favorite color is blue"); break; case "green": alert("Your favorite color is green"); break; case "yellow": alert("Your favorite color is yellow"); break; case "orange": alert("Your favorite color is orange"); break; default: alert("Error in JavaScript function colorChoice"); break; } } </script> </head> <body> <h4> Choose your favorite color </h4> <form name = "colorsForm"> <p> <input type = "radio" Red </p> <p> <input type = "radio" Blue </p><p> <input type = "radio" Green </p><p> <input type = "radio" Yellow </p><p> <input type = "radio" Orange </p> </form> name = "colorButton" value = "red" /> name = "colorButton" value = "blue" /> name = "colorButton" value = "green" /> name = "colorButton" value = "yellow" /> name = "colorButton" value = "orange" /> <script language = "JavaScript"> document.colorsForm.elements[0].onclick = colorChoice; document.colorsForm.elements[1].onclick = colorChoice; document.colorsForm.elements[2].onclick = colorChoice; document.colorsForm.elements[3].onclick = colorChoice; document.colorsForm.elements[4].onclick = colorChoice; </script> </body> </html> Exercise 5.4 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e5_4.html A solution to Exercise 5.4 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 5.4 </title> <script language = "JavaScript"> var total = 0; // The event handler functions for the text boxes function appleHandler() { var number = document.orderForm.apples.value; total = total + number * 0.59; } function orangeHandler() { var number = document.orderForm.oranges.value; total = total + number * 0.49; } function bananaHandler() { var number = document.orderForm.bananas.value; total = total + number * 0.39; } // The event handler function to produce the total cost message // when "submit" is clicked function finish() { total = total * 1.05; alert("Thank you for your order \n" + "Your total cost is: $" + total + "\n"); } </script> </head> <body> <h3> Order Form </h3> <form name = "orderForm" onSubmit = "finish()"> <p> <input type = "text" name = "apples" size = "3" onChange = "appleHandler()" /> Apples </p><p> <input type = "text" name = "oranges" size = "3" onChange = "orangeHandler()" /> Oranges </p><p> <input type = "text" name = "bananas" size = "3" onChange = "bananaHandler()" /> Bananas </p><p> <input type = "reset" name = "reset" /> <input type = "submit" name = "submit" /> </p> </form> </body> </html> Exercise 5.5 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e5_5.html A solution to Exercise 5.5 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 5.5 </title> <script type = "text/javascript"> var total = 0; // The event handler functions for the text boxes function appleHandler() { var myApple = document.getElementById("apples"); var number = myApple.value; if (number < 0 || number > 99) { alert("Error - the quantity you entered in not valid" + "\n [It is not in the range of 0 - 99] \n" + "Please enter a valid quantity"); myApple.focus(); myApple.select(); return false; } else { total = total + number * 0.59; return true; } } function orangeHandler() { var myOrange = document.getElementById("oranges"); var number = myOrange.value; if (number < 0 || number > 99) { alert("Error - the quantity you entered in not valid" + "\n [It is not in the range of 0 - 99] \n" + "Please enter a valid quantity"); myOrange.focus(); myOrange.select(); return false; } else { total = total + number * 0.39; return true; } } function bananaHandler() { var myBanana = document.getElementById("bananas"); var number = myBanana.value; if (number < 0 || number > 99) { alert("Error - the quantity you entered in not valid" + "\n [It is not in the range of 0 - 99] \n" + "Please enter a valid quantity"); myBanana.focus(); myBanana.select(); return false; } else { total = total + number * 0.49; return true; } } // The event handler function to produce the total cost message // when "submit" is clicked function finish() { total = total * 1.05; alert("Thank you for your order \n" + "Your total cost is: $" + total + "\n"); } </script> </head> <body> <h3> Order Form </h3> <form name = "" onSubmit = "finish()"> <p> <input type = "text" id = "apples" Apples size = "3" /> </p><p> <input type Oranges </p><p> <input type Bananas </p><p> <input type <input type </p> </form> = "text" id = "oranges" size = "3" /> = "text" id = "bananas" size = "3" /> = "reset" name = "reset" /> = "submit" name = "submit" /> <script type = "text/javascript"> <!-// Set form element object properties to their // corresponding event handler functions document.getElementById("apples").onchange = appleHandler; document.getElementById("oranges").onchange = orangeHandler; document.getElementById("bananas").onchange = bananaHandler; // --> </script> </body> </html> Exercise 5.6 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e5_6.html A solution to Exercise 5.6 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 5.6 </title> <script language = "JavaScript"> var total = 0; // The event handler functions for the text boxes function appleHandler() { var dom = document.getElementById("apples"); var number = dom.value; if (number < dom.min || number > dom.max) { alert("Error - the quantity you entered in not valid" + "\n [It is not in the range of " + dom.min + " to " + dom.max + "] \n" + "Please enter a valid quantity"); dom.focus(); dom.select(); return false; } else { total = total + number * 0.59; return true; } } function orangeHandler() { var dom = document.getElementById("oranges"); var number = dom.value; if (number < dom.min || number > dom.max) { alert("Error - the quantity you entered in not valid" + "\n [It is not in the range of " + dom.min + " to " + dom.max + "] \n" + "Please enter a valid quantity"); dom.focus(); dom.select(); return false; } else { total = total + number * 0.39; return true; } } function bananaHandler() { var dom = document.getElementById("bananas"); var number = dom.value; if (number < dom.min || number > dom.max) { alert("Error - the quantity you entered in not valid" + "\n [It is not in the range of " + dom.min + " to " + dom.max + "] \n" + "Please enter a valid quantity"); dom.focus(); dom.select(); return false; } else { total = total + number * 0.49; return true; } } // The event handler function to produce the total cost message // when "submit" is clicked function finish() { total = total * 1.05; alert("Thank you for your order \n" + "Your total cost is: $" + total + "\n"); } </script> </head> <body> <h3> Order Form </h3> <form name = "orderForm" onSubmit = "finish()"> <p> <input type = "text" id = "apples" size = "3" /> Apples </p><p> <input type = "text" id = "oranges" size = "3" /> Oranges </p><p> <input type = "text" id = "bananas" size = "3" /> Bananas </p><p> <input type = "reset" name = "reset" /> <input type = "submit" name = "submit" /> </p> </form> <script language = "JavaScript"> // Get DOM addresses of the text boxes var appleDom = document.getElementById("apples"); var orangeDom = document.getElementById("oranges"); var bananaDom = document.getElementById("bananas"); // Set the onchange properties for the event handlers appleDom.onchange = appleHandler; orangeDom.onchange = orangeHandler; bananaDom.onchange = bananaHandler; // Add properties for minimum and maximum values for the text boxes appleDom.max = 99; appleDom.min = 0; orangeDom.max = 99; orangeDom.min = 0; bananaDom.max = 99; bananaDom.min = 0; // --> </script> </body> </html> Chapter 6 Exercise 6.1 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e6_1.html A solution to Exercise 6.1 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 6.1 </title> <style type = "text/css"> /* A style for the paragraph of text */ .regtext {position: absolute; top: 100px; left: 100px; font-family: Times; font-size: 14pt; width: 330px} /* A style for the image */ .img {background-image: url(c172.gif); position: absolute; left: 190px; top: 180px; width: 100px} </style> </head> <body> <p class = "img"> <br/><br/><br/><br/><br/> </p> <p class = "regtext"> I was born on July 4th, 1976, in Huckabee, Alaska. I have three brothers and a sister, all older than I. My sister, Mary, is 26 years old. She lives in Kalkan, Montana. My oldest brother, Ron, is 32 years old. He lives in Huckabee. My youngest brother, Max, is 28 years old. He lives in Pinkee, Wyoming. My middle brother, Fred, is 30 years old. He lives in Kinkyhollow, Nebraska. My parents, who are both still living, still live in Huckabee. </p> </body> </html> Exercise 6.2 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e6_2.html A solution to Exercise 6.2 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 6.2 </title> <style type = "text/css"> /* A style for the paragraph of text */ .regtext {position: absolute; top: 150px; left: 100px; font-family: Times; font-size: 14pt; width: 330px} /* A style for the image */ .img {background-image: url(c172.gif); position: absolute; left: 100px; top: 150px; width: 100px} </style> <script language = "JavaScript"> /* A function to move an element */ function moveIt(movee, newTop, newLeft) { dom = document.getElementById(movee).style; /* Change the top and left properties to perform the move */ dom.top = newTop; dom.left = newLeft; } </script> </head> <body> <h2> Background Image Position Control Buttons </h2> <p> <form name = "moveControl"> <input type = "radio" name = "choser" checked = "checked" onclick = "moveIt('picture', 150, 100)" /> Northwest <p/><p> <input type = "radio" name = "choser" onclick = "moveIt('picture', 150, 300)" /> Northeast </p><p> <input type = "radio" name = "choser" onclick = "moveIt('picture', 300, 300)" /> Southeast <p/><p> <input type = "radio" name = "choser" onclick = "moveIt('picture', 300, 100)" /> Southwest </p> </form> <p class = "img" id = "picture"> <br/><br/><br/><br/><br/> </p> <p class = "regtext"> I was born on July 4th, 1976, in Huckabee, Alaska. I have three brothers and a sister, all older than I. My sister, Mary, is 26 years old. She lives in Kalkan, Montana. My oldest brother, Ron, is 32 years old. He lives in Huckabee. My youngest brother, Max, is 28 years old. He lives in Pinkee, Wyoming. My middle brother, Fred, is 30 years old. He lives in Kinkyhollow, Nebraska. My parents, who are both still living, still live in Huckabee. </p> </body> </html> Exercise 6.3 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e6_3.html A solution to Exercise 6.3 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 6.3 </title> <style type = "text/css"> /* A style for the paragraph of text */ .regtext {position: absolute; top: 150px; left: 100px; font-family: Times; font-size: 14pt; width: 330px} </style> <script language = "JavaScript"> /* A function to change the visibility of an element */ function flipImage(img) { dom = document.getElementById(img).style; /* Change the visibility property */ if (dom.visibility == "visible" || dom.visibility == "show") dom.visibility = "hidden"; else dom.visibility = "visible"; } </script> </head> <body> <h2> Background Image Visibility Control Buttons </h2> <form name = "visibilityControl"> <p> <input type = "checkbox" name = "choser" onclick = "flipImage('northwest')" /> Northwest <p/><p> <input type = "checkbox" name = "choser" onclick = "flipImage('northeast')" /> Northeast </p><p> <input type = "checkbox" name = "choser" onclick = "flipImage('southeast')" /> Southeast </p><p> <input type = "checkbox" name = "choser" onclick = "flipImage('southwest')" /> Southwest </p> </form> <p id = "northwest" style = "background-image: url(c172.gif); visibility: hidden; position: absolute; left: 100px; top: 150px; width: 100px"> <br/><br/><br/><br/><br/> </p> <p id = "northeast" style = "background-image: url(c172.gif); visibility: hidden; position: absolute; left: 300px; top: 150px; width: 100px"> <br/><br/><br/><br/><br/> </p> <p id = "southeast" style = "background-image: url(c172.gif); visibility: hidden; position: absolute; left: 300px; top: 300px; width: 100px"> <br/><br/><br/><br/><br/> </p> <p id = "southwest" style = "background-image: url(c172.gif); visibility: hidden; position: absolute; left: 100px; top: 300px; width: 100px"> <br/><br/><br/><br/><br/> </p> <p class = "regtext"> I was born on July 4th, 1976, in Huckabee, Alaska. I have three brothers and a sister, all older than I. My sister, Mary, is 26 years old. She lives in Kalkan, Montana. My oldest brother, Ron, is 32 years old. He lives in Huckabee. My youngest brother, Max, is 28 years old. He lives in Pinkee, Wyoming. My middle brother, Fred, is 30 years old. He lives in Kinkyhollow, Nebraska. My parents, who are both still living, still live in Huckabee. </p> </body> </html> Exercise 6.5 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- 6_5.html A solution to Exercise 6.5 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Exercise 6.5 </title> <script language = "JavaScript"> var top = "C172"; function toTop(newTop) { // Get DOM addresses for the new top and the old top elements domTop = document.getElementById(top).style; domNew = document.getElementById(newTop).style; // Set the zIndex properties of the two elements domTop.zIndex = "0"; domNew.zIndex = "10"; top = newTop; } </script> </head> <body> <p> <a href 1 </a> </p><p> <a href 2 </a> </p><p> <a href 3 </a> </p><p> <img id = "JAVASCRIPT:toTop('C172')"> = "JAVASCRIPT:toTop('cix')"> = "JAVASCRIPT:toTop('C182')"> = "C172" src = "c172.gif" style = "position: absolute; top: 100; left: 0; z-index: 0;" /> <img id = "cix" src = "cix.gif" style = "position: absolute; top: 100; left: 0; z-index: 0;" /> <img id = "C182" src = "c182.gif" style = "position: absolute; top: 100; left: 0; z-index: 0;" /> </p><p></p> </body> </html> Chapter 7 Exercise 7.1 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e7_1.html To test the applet, e7_1.java Solution to Exercise 7.1 Legal styles are BOLD, PLAIN, and ITALIC --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Test e7_1.java </title> </head> <body> <p> <object codetype = "application/java" code = "e7_1.class" width = "600" height = "100"> <param name = "size" value = "35" /> <param name = "font" value = "Courier" /> <param name = "style" value = "ITALIC" /> </object> </p> </body> </html> /* e7_1.java An applet to illustrate parameters */ import java.applet.*; import javax.swing.*; import java.awt.*; // The panel class on which the message will be painted class MessagePanel2 extends JPanel { Font myFont = new Font(e7_1.myFont, e7_1.myStyle, e7_1.mySize); public void paintComponent(Graphics grafObj) { super.paintComponent(grafObj); grafObj.setFont(myFont); grafObj.drawString("Welcome to my home page!", 50, 50); } } // The e7_1 applet public class e7_1 extends JApplet { static int mySize, myStyle; static String myFont; public void init() { Container messageArea = getContentPane(); String pString; // Get the fontsize parameter pString = getParameter("size"); // If it's null, set the size to 30, otherwise // use the parameter value if (pString == null) mySize = 30; else mySize = Integer.parseInt(pString); // Get the font parameter pString = getParameter("font"); // If it's null, set the font to 'Times Roman', // otherwise, use the parameter value if (pString == null) else myFont = pString; // Get the font style parameter pString = getParameter("style"); // If it's null, set the font to PLAIN, otherwise // use the parameter value if (pString == null) myStyle = Font.PLAIN; else if (pString.equals("BOLD")) myStyle = Font.BOLD; else if (pString.equals("ITALIC")) myStyle = Font.ITALIC; // Instantiate the panel with the message and add it to // the content pane MessagePanel2 myMessagePanel = new MessagePanel2(); messageArea.add(myMessagePanel); } } Exercise 7.3 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e7_3.html To test the applet, Olympic A solution to Exercise 7.3 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Test Olympic </title> </head> <body> <p> <object codetype = "application/java" code = "Olympic.class" width = "460" height = "180"> </object> </p> </body> </html> /* Olympic.java A solution to Exercise 7.3 - the applet */ import java.applet.*; import java.awt.*; import javax.swing.*; // The panel class for drawing class MyPanel extends JPanel { public void paint(Graphics grafObj) { Font myFont = new Font("TimesRoman", Font.ITALIC, 24); super.paintComponent(grafObj); grafObj.setColor(Color.green); grafObj.drawRect(10, 10, 440, 120); grafObj.setColor(Color.blue); grafObj.drawOval(20, 20, 100, 100); grafObj.drawOval(100, 20, 100, 100); grafObj.drawOval(180, 20, 100, 100); grafObj.drawOval(260, 20, 100, 100); grafObj.drawOval(340, 20, 100, 100); grafObj.setColor(Color.red); grafObj.setFont(myFont); grafObj.drawString("United States Olympic Committee", 60, 160); } } // The Olympic applet public class Olympic extends JApplet { Container olympicArea = getContentPane(); MyPanel newPanel = new MyPanel(); // The init method for the applet - adds the panel // to the content area of the applet public void init() { olympicArea.add(newPanel); } } Exercise 7.4 /* Mexfood.java A solution to Exercise 7.4 */ import java.awt.*; import java.applet.*; import javax.swing.*; public class Mexfood extends JApplet { // Create a content pane Container contentPane = getContentPane(); // The init method, which does everything in this applet public void init() { // Create a panel object and set its layout manager to put // the components in a column JPanel myPanel = new JPanel(); myPanel.setLayout(new GridLayout(4, 3, 10, 10)); myPanel.setBackground(Color.cyan); // Create checkboxes and textboxes for the different food items // and add them to the panel TextField t1 = new TextField(2); TextField t2 = new TextField(2); TextField t3 = new TextField(2); TextField t4 = new TextField(2); JLabel l1 = new JLabel("Tacos JLabel l2 = new JLabel("Chalupas JLabel l3 = new JLabel("Burritos JLabel l4 = new JLabel("Nachos myPanel.add(l1); myPanel.add(t1); myPanel.add(l2); myPanel.add(t2); myPanel.add(l3); myPanel.add(t3); myPanel.add(l4); myPanel.add(t4); // Now add the panel contentPane.add(myPanel); } // End of init() } // End of Mexfood applet Exercise 7.5 /* FoodCost.java A solution to Exercise 7.5 */ import java.awt.*; import java.awt.event.*; Quantity:"); Quantity:"); Quantity:"); Quantity:"); import java.applet.*; import javax.swing.*; // The applet public class FoodCost extends JApplet implements ActionListener { private JPanel myPanel = new JPanel(); private JTextField t1, t2, t3, t4, t5; private JLabel l1, l2, l3, l4, l5; private double totalCost = 0.0; Container contentPane = getContentPane(); public void init() { // Create a panel object and set its layout manager to put // the components in a column myPanel.setLayout(new GridLayout(5, 2, 10, 10)); myPanel.setBackground(Color.cyan); // Create checkboxes and textboxes for the different food items // and add them to the panel l1 l2 l3 l4 l5 t1 t2 t3 t4 t5 = = = = = = = = = = new new new new new new new new new new JLabel("Tacos JLabel("Chalupas JLabel("Burritos JLabel("Nachos JLabel("Total Cost:"); JTextField(2); JTextField(2); JTextField(2); JTextField(2); JTextField(6); myPanel.add(l1); myPanel.add(t1); myPanel.add(l2); myPanel.add(t2); myPanel.add(l3); myPanel.add(t3); myPanel.add(l4); myPanel.add(t4); myPanel.add(l5); myPanel.add(t5); // Register the event handler t1.addActionListener(this); t2.addActionListener(this); t3.addActionListener(this); t4.addActionListener(this); // Now add the panel contentPane.add(myPanel); Quantity:"); Quantity:"); Quantity:"); Quantity:"); } // End of init() // The event handler public void actionPerformed(ActionEvent e) { // Determine which textbox has been changed and add the cost int quantity; Object source = e.getSource(); if (source == t1) { quantity = Integer.parseInt(t1.getText()); totalCost = totalCost + quantity * 0.79; } else if (source == t2) { quantity = Integer.parseInt(t2.getText()); totalCost = totalCost + quantity * 1.19; } else if (source == t3) { quantity = Integer.parseInt(t3.getText()); totalCost = totalCost + quantity * 1.39; } else if (source == t4) { quantity = Integer.parseInt(t4.getText()); totalCost = totalCost + quantity * 1.29; } String cost = Double.toString(totalCost); t5.setText("$" + cost); repaint(); } //* end of method ActionEvent } // End of Mexfood applet Chapter 8 Exercise 8.1 <?xml version = "1.0" encoding = "utf-8"?> <!-- cars.dtd - a document type definition for the cars.xml document A solution to Exercise 8.1 --> <!ELEMENT car_catalog (car+)> <!ELEMENT car (make, model, year, color, engine, number_of_doors, transmission_type, accessories)> <!ELEMENT make (#PCDATA)> <!ELEMENT model (#PCDATA)> <!ELEMENT year (#PCDATA)> <!ELEMENT color (#PCDATA)> <!ELEMENT engine (number_of_cylinders, fuel_system)> <!ELEMENT number_of_doors (#PCDATA)> <!ELEMENT transmission_type (#PCDATA)> <!ELEMENT accessories (#PCDATA)> <!ATTLIST <!ATTLIST <!ATTLIST <!ATTLIST <!ATTLIST <!ENTITY <!ENTITY <!ENTITY <!ENTITY <!ENTITY <!ENTITY accessories accessories accessories accessories accessories c f d h n t radio CDATA #REQUIRED> air_conditioning CDATA #REQUIRED> power_windows CDATA #REQUIRED> power_steering CDATA #REQUIRED> power_brakes CDATA #REQUIRED> "Chevrolet"> "Ford"> "Dodge"> "Honda"> "Nisson"> "Toyota"> Exercise 8.2 <?xml version = "1.0" encoding = "utf-8"?> <!-- cars.xml - A solution to Exercise 8.2 --> <!DOCTYPE car_catalog SYSTEM "cars.dtd"> <?xml-stylesheet type = "text/css" href = "cars.css"?> <car_catalog> <car> <year> 1997 </year> <make> &c; </make> <model> Impala </model> <color> Light blue </color> <engine> <number_of_cylinders> 8 cylinder </number_of_cylinders> <fuel_system> multi-port fuel injected </fuel_system> </engine> <number_of_doors> 4 door </number_of_doors> <transmission_type> 4 speed automatic </transmission_type> <accessories radio = "yes" air_conditioning = "yes" power_windows = "yes" power_steering = "yes" power_brakes = "yes" /> </car> <car> <year> 1965 </year> <make> &f; </make> <model> Mustang </model> <color> White </color> <engine> <number_of_cylinders> 8 cylinder </number_of_cylinders> <fuel_system> 4BBL carburetor </fuel_system> </engine> <number_of_doors> 2 door </number_of_doors> <transmission_type> 3 speed manual </transmission_type> <accessories radio = "yes" air_conditioning = "no" power_windows = "no" power_steering = "yes" power_brakes = "yes" /> </car> <car> <year> 1985 </year> <make> &t; </make> <model> Camry </model> <color> Blue </color> <engine> <number_of_cylinders> 4 cylinder </number_of_cylinders> <fuel_system> fuel injected </fuel_system> </engine> <number_of_doors> 4 door </number_of_doors> <transmission_type> 4 speed manual </transmission_type> <accessories radio = "yes" air_conditioning = "yes" power_windows = "no" power_steering = "yes" power_brakes = "yes" /> </car> </car_catalog> Exercise 8.4 <!-- cars.css - a style sheet for the cars.xml document A solution to Exercise 8.4 --> car {display: block; margin-top: 15px; color: blue;} year, make, model {color: red; font-size: 16pt;} color {display: block; margin-left: 20px; font-size: 12pt;} engine {display: block; margin-left: 20px;} number_of_cylinders {font-size: 12pt;} fuel_system {font-size: 12pt;} number_of_doors {display: block; margin-left: 20px; font-size: 12pt;} transmission_type {display: block; margin-left: 20px; font-size: 12pt;} Exercise 8.5 <?xml version = "1.0" encoding = "utf-8"?> <!-- xslcar.xsl A solution to Exercise 8.3 --> <xsl:stylesheet xmlns:xsl = "http://www.w3.org/TR/WD-xsl" xmlns = "http://www.w3.org/TR/REC-html40"> <xsl:template match = "/"> <h2> Car Description </h2> <span style = "font-style: italic"> Year: </span> <xsl:value-of select = "car_catalog/car/year" /> <br /> <span style = "font-style: italic"> Make: </span> <xsl:value-of select = "car_catalog/car/make" /> <br /> <span style = "font-style: italic"> Model: </span> <xsl:value-of select = "car_catalog/car/model" /> <br /> <span style = "font-style: italic"> Color: </span> <xsl:value-of select = "car_catalog/car/color" /> <br /> <span style = "font-style: italic"> Cylinders: </span> <xsl:value-of select = "car_catalog/car/engine/number_of_cylinders" /> <br /> <span style = "font-style: italic"> Fuel system: </span> <xsl:value-of select = "car_catalog/car/engine/fuel_system" /> <br /> <span style = "font-style: italic"> Doors: </span> <xsl:value-of select = "car_catalog/car/number_of_doors" /> <br /> </xsl:template> </xsl:stylesheet> Exercise 8.6 <?xml version = "1.0" encoding = "utf-8"?> <!-- xslcars.xsl A solution to Exercise 8.6 --> <xsl:stylesheet xmlns:xsl = "http://www.w3.org/TR/WD-xsl" xmlns = "http://www.w3.org/TR/REC-html40"> <xsl:template match = "/"> <h2> Car Description </h2> <xsl:for-each select = "car_catalog/car"> <span style = "font-style: italic"> Year: </span> <xsl:value-of select = "year" /> <br /> <span style = "font-style: italic"> Make: </span> <xsl:value-of select = "make" /> <br /> <span style = "font-style: italic"> Model: </span> <xsl:value-of select = "model" /> <br /> <span style = "font-style: italic"> Color: </span> <xsl:value-of select = "color" /> <br /> <span style = "font-style: italic"> Cylinders: </span> <xsl:value-of select = "engine/number_of_cylinders" /> <br /> <span style = "font-style: italic"> Fuel system: </span> <xsl:value-of select = "engine/fuel_system" /> <br /> <span style = "font-style: italic"> Doors: </span> <xsl:value-of select = "number_of_doors" /> <br /><br /> </xsl:for-each> </xsl:template> </xsl:stylesheet> Chapter 9 Exercise 9.1 # e9_1.pl - A solution to Exercise 9.1 # # Input: Three numbers, a, b, and c, each on its own line, # from the keyboard. # Output: The value of the expression 10ab-((c-1)/17.44) # Get input print "Please input the value of a "; $a = <STDIN>; print "Please input the value of b "; $b = <STDIN>; print "Please input the value of c "; $c = <STDIN>; # Compute the value of the expression $value = 10 * $a * $b -(($c - 1) / 17.44); print "The value of the expression is: $value \n"; Exercise 9.3 # e9_3.pl - A solution to Exercise 9.3 # # Input: Three names, on separate lines, from the keyboard # Output: The input names in alphabetical order, without # using an array # Get input print "Please input the value of name1: "; chomp($name1 = <STDIN>); print "Please input the value of name2: "; chomp($name2 = <STDIN>); print "Please input the value of name3: "; chomp($name3 = <STDIN>); # Pass one - compare/interchange both pairs if ($name2 lt $name1) { $temp = $name1; $name1 = $name2; $name2 = $temp; } if ($name3 lt $name2) { $temp = $name2; $name2 = $name3; $name3 = $temp; } # Pass two - compare/interchange the first two if ($name2 lt $name1) { $temp = $name1; $name1 = $name2; $name2 = $temp; } print "The input numbers in order are: $name1, $name2, ", "$name3 \n"; Exercise 9.5 # e9_5.pl - A solution to Exercise 9.5 # # Input: A list of numbers in a file specified on # the command line # Output: Two lists of numbers, one with the input # numbers that are greater than zero, and one # with those that are less than zero (ignore # the zero-valued numbers) # Method: You must first build two arrays with the # required output numbers, before you # display any of them # Loop to read input and build the two new arrays while ($next = <>) { if ($next > 0) { push @pos_list, $next; } else { if ($next < 0) { push @neg_list, $next; } } } # Output the results print "The array of positive numbers: \n @pos_list \n"; print "\nThe array of negative numbers: \n @neg_list \n"; Exercise 9.7 # e9_7.pl - A solution to Exercise 9.7 # # Input: A file in which each line contains a string of # the form: name+sales # where in some cases the sales will be absent # (but not the plus sign), specified on the command # line # Output: A list of the names and sales numbers that remain # after the following processing: # a) names with sales numbers are added to a hash # when they are first found, along with their # sales numbers # b) names with absent sales numbers are deleted # from the hash if they are already there # c) when a name appears that is already in the hash, # the new sales number is added to the old sales # number (the one already in the hash) # Loop to read input and build the two new arrays while ($next = <>) { # Split the next line into a name and sales ($name, $sales) = split /\+/, $next; # If the sales part is empty, delete the element if ($sales == 0) { delete $totals{$name}; } else { # Otherwise, if the name already exists, add sales to the element if (exists $totals{$name}) { $totals{$name} += $sales; } else { # Or else, create the element $totals{$name} = $sales; } } } # Output the results foreach $name (keys %totals) { print "For $name, total sales are: $totals{$name} \n"; } Exercise 9.9 # e9_9.pl - A solution to Exercise 9.9 # # Input: A file specified on the command line that contains # a C program # Output: For each line of the input: # 1. The number of words (variables and reserved # words) on the line # 2. The number of numeric literals without decimal # points on the line (we assume the decimal points # are embedded in digits) # 3. The number of numeric literals with decimal points # on the line # 4. The number of braces and parentheses on the line # Loop to read input and compute the results while (<>) { print "The next line is: $_ \n"; # Find the variables and reserved words $words = s/[A-Za-z]+//g; # Find and erase the numeric literals with decimal points $decimals = s/[0-9]+\.[0-9]+//g; # Find the numeric literals without decimal points $ints = s/[0-9]+//g; # Find the braces and parentheses $bra_parens = s/[\{\}\)\(]//g; # Change the null strings to zeros for output $words += 0; $decimals += 0; $ints += 0; $bra_parens += 0; # Output the results print "For this line, " The number of " The number of $decimals \n", " The number of \n", " The number of \n", words is: $words \n", numeric literals with decimal points is: numeric literals without decimal points is: $ints braces and parentheses is: $bra_parens \n"; } Exercise 9.10 # e9_10.pl - A solution to Exercise 9.10 # A function: # Parameter: An array of strings, passed by value # Return value: A list of the unique strings in # the parameter array sub unique { my @strgs = @_; my %uniq; # Loop to build a hash of the unique words foreach $word (@strgs) { $uniq{$word} = 0; } return keys %uniq; } Exercise 9.12 # # # # # e9_12.pl - A solution to Exercise 9.12 A function: Parameter: A reference to an array of strings Return value: A list of the unique strings in the parameter array sub unique { my $ref_strgs = @_[0]; my %uniq; # Loop to build a hash of the unique words foreach $word (@$ref_strgs) { $uniq{$word} = 0; } return keys %uniq; } Chapter 10 Exercise 10.1 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e10_1.html - calls a CGI program, e10_1.pl, that produces one of five different greetings A solution to Exercise 10.1 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Call e10_1.pl </title> </head> <body> <p> <a href = "http://cs.uccs.edu/cgi-bin/sebesta/e10_1.pl" > Click here for a greeting </a> </p> </body> </html> #!/usr/local/bin/perl # e10_1.pl - a CGI program to produce one of five # five different greetings when called # A solution to Exercise 10.1 @greetings = ("Hi there, Web surfer!\n", "Are you lost??? \n", "This must be your lucky day, you're here! \n", "Top of the day to you! \n", "Thanks for thinking of me! \n"); $rand; $number = int(rand 5); print print print print "Content-type: text/html\n\n"; "<html><html>\n"; "<title> CGI - greeting </title></head> \n"; "<body>\n"; $greeting = $greetings[$number]; print "$greeting"; print "</body> </html> \n"; Exercise 10.3 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e10_3.html - This describes lightbulb sales form page A solution to Exercise 10.3 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Lightbulb Sales (Exercise 10.2) </title> </head> <body> <!-- The next line gives the address of the CGI program --> <form action = "http://www.cs.uccs.edu/cgi-bin/sebesta/e10_5.pl" method = "post"> <h2> Welcome to the Lightbulb Sales Order Form </h2> <!-- Text widget for customer's name --> <p> Buyer's Name: <input type = "text" </p> name = "name" size = "30" /> <!-- Table for bulb items --> <table border = "border"> <!-- First, the column headings --> <tr> <th> Product Name </th> <th> Price </th> <th> Quantity </th> </tr> <!-- Now, the table data entries --> <tr> <td> <td> <td> </tr> <tr> <td> <td> <td> </td> </tr> <tr> <td> <td> <td> </tr> <tr> <td> <td> <td> </td> </tr> Four 100-watt regular bulbs </td> $2.39 </td> <input type = "text" name = "four100" Eight 100-watt regular bulbs </td> $4.29 </td> <input type = "text" name = "eight100" Four 100-watt long-life bulbs </td> $3.95 </td> <input type = "text" name = "fourll" Eight 100-watt long-life bulbs </td> $7.49 </td> <input type = "text" name = "eightll" size ="2" /> </td> size = "2" /> size = "2" /> </td> size = "2" /> </table> <!-- The radio buttons for the payment method --> <h3> Payment Method: </h3> <p> <input type = "radio" name = checked = "checked" /> <input type = "radio" name = <br /> <input type = "radio" name = <br /> "payment" value = "visa" Visa <br /> "payment" value = "mc" /> Master Card "payment" <!-- The submit and reset buttons --> value = "discover" /> Discover <input type = "submit" value = "Submit Order" /> <input type = "reset" value = "Clear Order Form" /> </p> </form> </body> </html> Exercise 10.4 #!/usr/local/bin/perl # This is e10_4.pl # It is a CGI program to process the light bulb sales form # This is a solution to Exercise 10.4 # Initialize total price and total number of purchased items $total_price = 0; $total_items = 0; # Produce the header part of the HTML return value print print print print "Content-type: text/html\n\n"; "<html><head>\n"; "<title> CGI-Perl Lightbulb Sales Form "<body>\n"; </title></head> \n"; # Determine the request method and get the query string $request_method = $ENV{'REQUEST_METHOD'}; if ($request_method eq "GET") { $query_string = $ENV{'QUERY_STRING'}; } elsif ($request_method eq "POST") { read(STDIN, $query_string, $ENV{'CONTENT_LENGTH'}); } # Split the query string into the name/value pairs @name_value_pairs = split(/&/, $query_string); # Loop to process the array of item names and quantities foreach $name_value (@name_value_pairs) { # Split the pairs into names and values and translate the values # into text by decoding the hex characters ($name, $value) = split (/=/, $name_value); $value =~ tr/+/ /; $value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack("C", hex($1))/eg; # Add the number of these items to the total items ordered, # compute the cost of the item, and add its cost to the total price, # Get the customer number into local variables } if ($name eq "name") { $cust_name = $value; } elsif ($name eq "payment") { $payment = $value; } elsif ($name eq "four100") { $four100 = $value; $cost = 2.39 * $value; $total_price += $cost; $total_items += $value; } elsif ($name eq "eight100") { $eight100 = $value; $cost = 4.29 * $value; $total_price += $cost; $total_items += $value; } elsif ($name eq "fourll") { $fourll = $value; $cost = 3.95 * $value; $total_price += $cost; $total_items += $value; } elsif ($name eq "eightll") { $eightll = $value; $cost = 7.49 * $value; $total_price += $cost; $total_items += $value; } ##- end of if ##- end of foreach # Compute the sales tax and the total $tax = 0.062 * $total_price; $total_cost = $total_price + $tax; # Produce the result information to the browser and finish the page print "Customer: $cust_name<br/>\n"; print "Payment method: $payment <br /><br />\n"; print "<table border = 'border'><caption>Items ordered</caption>\n"; print "<tr><th>Item</th><th>Price</th><th>Quantity</th></tr>\n"; print "<tr><th>4 100-watt reg.</th><td> \$2.39</td><td>$four100</td><tr>\n"; print "<tr><th>8 100-wat reg.</th><td> \$4.29</td><td>$eight100</td></tr>\n"; print "<tr><th>4 long life</th><td> \$3.95</td><td>$fourll</td></tr>\n"; print "<tr><th>8 long life</th><td> \$7.49</td><td>$eightll</td></tr>\n"; print "</table> <h4> Thankyou for your order </h4>\n"; print "The total cost of the items you ordered is: \$ $total_price <br /> \n"; print "The tax on this order is: \$ $tax <br />\n"; print "The total bill is: \$ $total_cost <br />\n"; print "</body> </html> \n"; <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> Exercise 10.7 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e10_7.html A document to present the user with a consumer electronics purchasing survey form This is a solution to Exercise 10.7 --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> Consumer Electronics Purchasing Survey </title> </head> <body> <form action = "http://www.cs.uccs.edu/cgi-bin/sebesta/e10_71.pl" method = "post"> <h2> Welcome to the Consumer Electronics Purchasing Survey </h2> <h4> Your Age Category: </h4> <p> <input type = "radio" name = "age" value = "b1025" checked = "checked" /> 10-25 <br /> <input type = "radio" name = "age" value = "b2640" /> 26-40 <br /> <input type = "radio" name = "age" value = "b4160" /> 41-60 <br /> <input type = "radio" name = "age" value = "o60" /> Over 60 <br /> <br /> </p> <h4> Your Gender: </h4> <p> <input type = "radio" name = "gender" value = "female" checked = "checked" /> Female <br /> <input type = "radio" name = "gender" value = "male" /> Male <br /> <br /> </p> <h4> Your Next Consumer Electronics Purchase will be: </h4> <p> <input type = "radio" name = "vote" value = "0" /> Conventional TV <br /> <input type = "radio" name = "vote" value = "1" /> HDTV <br /> <input type = "radio" name = "vote" value = "2" /> VCR <br /> <input type = "radio" name = "vote" value = "3" /> D player <br /> <input type = "radio" name = "vote" value = "4" /> Mini CD player/recorder <br /> <input type = "radio" name = "vote" value = "5" /> DIVD player <br /> <input type = "radio" name = "vote" value ="6" checked = "checked" /> Other <br /> <br /> <input type = "submit" value = "Submit Order" /> <input type = "reset" value = "Clear Order Form" /> </p> </form> <hr/> <p> To see the results of the survey so far, click <a href = "http://www.cs.uccs.edu/cgi-bin/sebesta/e10_72.pl"> here </a>; </p> </body> </html> Exercise 10.8 #!/usr/local/bin/perl # e10_8.pl # error - a function to produce an error message for the client # and exit in case of open errors sub error { print "Error - file could not be opened in conelec1.pl <br/>"; print end_html(); exit(1); } # This CGI program processes the consumer electronics survey form # and updates the file that stores the survey data, survdat.dat # This is a solution to Exercise 10.8 use CGI qw(:standard); # Get the form values my($age, $gender, $vote) = (param("age"), param("gender"), param("vote")); # Produce the header for the reply page - do it here so error # messages appear on the page print header(); # Set names for file locking and unlocking $LOCK = 2; $UNLOCK = 8; # Set $index to the line index of the current vote $index = 0; if ($gender eq "male") { $index = 4; } if ($age eq "b2640") { $index += 1 } elsif ($age eq "b4160") { $index += 2 } elsif ($age eq "o60") { $index += 3 } # Open and lock the survey data file open(SURVDAT, "<survdat.dat") or error(); flock(SURVDAT, $LOCK); # Read the survey data file, unlock it, and close it $total_votes = <SURVDAT>; $total_votes++; for ($count = 0; $count <= 7; $count++) { chomp($file_lines[$count] = <SURVDAT>); } flock(SURVDAT, $UNLOCK); close(SURVDAT); # Split the line into its parts, increment the chosen device, and # put it back together again @file_votes = split / /, $file_lines[$index]; $file_votes[$vote]++; $file_lines[$index] = join(" ", @file_votes); # Reopen the survey data file for writing and lock it open(SURVDAT, ">survdat.dat") or error(); flock(SURVEY, $LOCK); # Write out the file data, unlock the file, and close it print SURVDAT "$total_votes\n"; for ($count = 0; $count <= 7; $count++) { $line = $file_lines[$count]; print SURVDAT "$line\n"; } flock(SURVDAT, $UNLOCK); close(SURVDAT); # Build the web page to thank the survey participant print start_html("Thankyou"); print "Thank you for participating in our survey <br /> \n"; print "The total number of votes so far is: $total_votes<br /> \n"; print end_html(); #!/usr/local/bin/perl # error - a function to produce an error message for the client # and exit in case of open errors sub error { print "Error - file could not be opened in conelec2.pl <br/>"; print end_html(); exit(1); } Exercise 10.9 # e10_9.pl - display the survey results # A solution to the second part of Exercise 10.9 use CGI qw(:standard); # Initialize file locking/unlocking parameter $LOCK = 2; $UNLOCK = 8; print header(); # Open, lock, read, and unlock the survey data file open(SURVDAT, "<survdat.dat") or error(); flock(SURVDAT, $LOCK); $total_votes = <SURVDAT>; @vote_data = <SURVDAT>; flock(SURVDAT, $UNLOCK); # Create the beginning of the result web page print start_html("Survey Results"); print "<H2> Results of the Consumer Electronics Purchasing Survey </H2><BR> \n"; # Split the input lines for females into age arrays @age1 @age2 @age3 @age4 = = = = split(/ split(/ split(/ split(/ /, /, /, /, $vote_data[0]); $vote_data[1]); $vote_data[2]); $vote_data[3]); # Compute percentages for the data for ($index = 0; $age1[$index] $age2[$index] $age3[$index] $index < 7; $index++) = 100 * $age1[$index] = 100 * $age2[$index] = 100 * $age3[$index] { / $total_votes; / $total_votes; / $total_votes; $age4[$index] = 100 * $age4[$index] / $total_votes; } # Add the row titles to the age arrays unshift(@age1, unshift(@age2, unshift(@age3, unshift(@age4, "10-25"); "26-40"); "41-60"); "Over 60"); # Make the column titles array @col_titles = ("Age Group", "Conventional TV", "HDTV", "VCR", "CD player", "MiniCD player/recorder", "DIVD player", "Other"); # Create the column titles in HTML by giving their address to the th # function and storing the return value in the @rows array @rows = th(\@col_titles); # Now create the data rows with the td function # and add them to the row addresses array push(@rows, td(\@age1), td(\@age2), td(\@age3), td(\@age4)); # Create the table for the female survey results # The address of the array of row addresses is passed to Tr print table({-border => "border"}, caption("<h3>Survey Data for Females (%) </h3>"), Tr(\@rows) ); # Split the input lines for the males into age arrays @age1 @age2 @age3 @age4 = = = = split(/ split(/ split(/ split(/ /, /, /, /, $vote_data[4]); $vote_data[5]); $vote_data[6]); $vote_data[7]); # Compute the percentages of votes for ($index = 0; $age1[$index] $age2[$index] $age3[$index] $age4[$index] } $index < 7; $index++) = 100 * $age1[$index] = 100 * $age2[$index] = 100 * $age3[$index] = 100 * $age4[$index] { / / / / $total_votes; $total_votes; $total_votes; $total_votes; # Add the first column titles to the rows of color votes unshift(@age1, unshift(@age2, unshift(@age3, unshift(@age4, "10-25"); "26-40"); "41-60"); "Over 60"); # Create the column titles in HTML by giving their address to the th # function and storing the return value in the @rows array @rows = th(\@col_titles); # Now create the data rows with the td function # and add them to the row addresses array push(@rows, td(\@age1), td(\@age2), td(\@age3), td(\@age4)); # Create the table for the female survey results # The address of the array of row addresses is passed to Trsults print "<BR><BR>"; print table({-border=>undef}, caption("<h3>Survey Data for Males (%) </h3>"), Tr(\@rows) ); print "<br /><br />The total number of votes so far is $total_votes <br />\n"; print end_html(); Chapter 12 Exercise 12.1 <?xml version = "1.0" encoding = "utf-8"?> <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e12_1.php A solution to Exercise 12.1 --> <html> <head> <title> e12_1.php </title> <?php function unique($strings) { $uniqueStrings = array(); foreach ($strings as $string) { foreach ($uniqueStrings as $uString) { if ($string == $uString) break; } if ($string != $uString) $uniqueStrings[] = $string; } return $uniqueStrings; } ?> </head> <body> <?php $str = array(42, 24, 2, 4, 42, 24, 2, 4, 24, 42, 42, 24); $uStr = unique($str); foreach ($uStr as $st) print ("$st <br />"); ?> </body> </html> Exercise 12.3 <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1 //EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e12_3.php Uses a function to determine the three most frequently occurring strings in a given array of strings and returns them in an array. --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> e12_3.php </title> </head> <body> <?php // Function the_three // Parameter: an array of string // Returns: an array of the three strings that occur most often // in the given array function the_three($in_array) { // Create the empty word frequency array $freq = array(); // Loop to count the words (either increment or initialize to 1) foreach ($in_array as $word) { $keys = array_keys($freq); if(in_array($word, $keys)) $freq[$word]++; else $freq[$word] = 1; } arsort($freq); $new_keys = array_keys($freq); return array($new_keys[0], $new_keys[1], $new_keys[2]); } #** End of the_three // Main test driver $test_array = array("apples", "are", "good", "for", "you", "or", "don't", "you", "like", "apples", "or", "maybe", "you", "like", "oranges", "better", "than", "apples"); // Call the function $tbl = the_three($test_array); // Display the words and their frequencies print "<br /> The Three Most Frequently Occurring Words<br /><br />"; $sorted_keys = array_keys($tbl); sort($sorted_keys); foreach ($sorted_keys as $word) print "$tbl[$word] <br />"; ?> </body> </html> Exercise 12.5 <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1 //EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e12_5.php Use a function to find the first four-digit number in a given string. --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> e12_5.php </title> </head> <body> <?php // Function first_four // Parameter: a string containing numbers separated by spaces // Returns: the first four-digit number found in the string; // returns zero if the string has no four-digit // number function first_four($str) { // Split the given string into its numbers $numbers = preg_split("/ +/", $str); foreach ($numbers as $numb) if (strlen($numb) == 4) return $numb; // If there was no four-digit number, return 0 return 0; } #** End of first_four // Main test driver $test_str = "22 1 444 66 333 4444 55555 66666 2 1 9 555"; // Call the function $result = first_four($test_str); // If the returned value has four digits, display it if ($result != 0) print("The first four-digit number is: $result <br />"); else print("There was no four-digit number in the string <br />"); ?> </body> </html> Exercise 12.7 <!DOCTYPE html PUBLIC "-//w3c//DTD XHTML 1.1 //EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <!-- e12_7.php Uses a function to determine the three most frequently occurring words in the given string, where the words are delimited on the left by spaces and on the right by commas, periods, or question marks --> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title> e12_7.php </title> </head> <body> <?php // Function the_three // Parameter: a string containing words that are delimited // on the left by spaces and on the right by // commas, periods, or question marks // Returns: an array of the three words that occur most often // in the given array function the_three($in_str) { // Split the string into its words preg_match_all("/ +[A-Za-z]+[,.?]/u", $in_str, $word_list); foreach ($word_list[0] as $word) print("The words are: $word <br />"); // Create the empty word frequency array $freq = array(); // Loop to count the words (either increment or initialize to 1) foreach ($word_list[0] as $word) { // First, get rid of the delimiters preg_match("/[A-Za-z]+/", $word, $match); $word = $match[0]; // Now, get an array of the keys $keys = array_keys($freq); // Set the frequency for the work if(in_array($word, $keys)) $freq[$word]++; else $freq[$word] = 1; } // Sort the frequency array in reverse order of values arsort($freq); // Get the keys and return the first three $new_keys = array_keys($freq); return array($new_keys[0], $new_keys[1], $new_keys[2]); } #** End of the_three // Main test driver $test_str = " apples. are, good? for, you, or, don't? you, like? apples, or. maybe. you, like, oranges, better. than. apples?"; // Call the function $tbl = the_three($test_str); // Display the words and their frequencies print "<br /> The Three Most Frequently Occurring Words<br /><br />"; $sorted_keys = array_keys($tbl); sort($sorted_keys); foreach ($sorted_keys as $word) print "$tbl[$word] <br />"; ?> </body> </html> Chapter 13 Exercise 13.1 <!-- e13_1.aspx A solution to Exercise 13.1 Uses Int32.Parse to convert the string version of the input number to an integer for use in the C# code --> <%@ Page language="c#" %> <html> <head> <title> e13_1 </title> <script runat = "server"> // Build a pseudorandom number method Random randomGen = new Random(); string msg; private int [] myArray = new int[100]; // A method to fill the array with pseudorandom numbers public void fillArray() { for (int index = 0; index < Int32.Parse(number.Value) ; index++) // Generate a pseudorandom number in the range of 0 to 100 myArray[index] = randomGen.Next(0, 100); } </script> </head> <body> <form runat = "server"> <p> Please input a number between 10 and 100: <input type = "text" id = "number" runat = "server" /> <br /> <input type = "submit" value = "Submit" /> <br /> <% if (IsPostBack) { %> <!-- Code to call the fillArray method and display the array --> <% fillArray(); Response.Write( "<br /> <b>The array's contents are: </b><br /><br />"); for (int index = 0; index < Int32.Parse(number.Value); index++) { msg = string.Format("The element at {0} is: {1} <br />", index, myArray[index]); Response.Write(msg); } %> <% } %> </p> </form> </body> </html> Chapter 14 Exercise 14.2 No changes to access_cars.pl to handle UPDATE and INSERT SQL commands. Exercise 14.3 No changes to access_cars.php are required to handle UPDATE and INSERT SQL commands. The mysql_query function takes SQL commands as its parameter, whether they are queries, updates, or inserts. For example, we could have: $query = "INSERT INTO Corvettes VALUES (38, ′convertible′, 17.1, 1993, 15)"; $result = mysql_query($query); To determine the number of rows that were affected by the INSERT command, the mysql_affected_rows function is used (with the result as its parameter). Exercise 14.5 // e14_5.java // This servlet receives // connects to the cars // the database. If the // table of the results // This is a solution to import import import import import an SQL command from its HTML document, database, and performs the command on command was a query, it returns an HTML of the query Exercise 14.5 javax.servlet.*; javax.servlet.http.*; java.io.*; java.util.*; java.sql.*; public class e14_5 extends HttpServlet { private Connection myCon; private Statement myStmt; // The init method - instantiate the db driver, connect to the // db, and create a statement for an SQL command public void init() { // Instantiate the driver for MySQL try { Class.forName("org.gjt.mm.mysql.Driver").newInstance(); } catch (Exception e) { e.printStackTrace(); } // Create the connection to the cars db try { myCon = DriverManager.getConnection ( "jdbc:mysql://localhost/cars?user=root"); } catch (SQLException e) { e.printStackTrace(); } // Create the statement for SQL queries try { myStmt = myCon.createStatement(); } catch (Exception e) { e.printStackTrace(); } } //** end of the init method // The doPost method - get the query, perform it, and produce // an HTML table of the results public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ResultSet result; String command, colName, dat; int numCols, index; ResultSetMetaData resultMd; // Get the SQL command command = request.getParameter("Command"); // Set the MIME type and get a writer response.setContentType("text/html"); PrintWriter out = response.getWriter(); // Create the initial html and display the request out.println("<html>"); out.println("<head><title>JDBCServlet</title></head>"); out.println("<body>"); out.print("<p><b>The command is: </b>" + command + "</p>"); // If the command is a query, use executeQuery on it if (command.substring(0, 5).equalsIgnoreCase("SELECT")) { try { result = myStmt.executeQuery(command); // Get the result's metadata and the number of result rows resultMd = result.getMetaData(); numCols = resultMd.getColumnCount(); // Produce the table header and caption out.println("<table border>"); out.println("<caption> <b> Query Results </b> </caption>"); out.println("<tr>"); // Loop to produce the column headings for (index = 1; index <= numCols; index++) { colName = resultMd.getColumnLabel(index); out.print("<th>" + colName + "</th>"); } out.println("</tr>"); // Loop to produce the rows of the result while (result.next()) { out.println("<tr>"); // Loop to produce the data of a row of the result for (index = 1; index <= numCols; index++) { dat = result.getString(index); out.println("<td>" + dat + "</td>"); } //** end of for (index = 0; ... } out.println("</tr>"); //** end of while (result.next()) ... out.println("</table>"); } //** end of try catch (Exception e) { e.printStackTrace(); } //** end of catch } //** end of the then clause of if (command.substring... else { //** It is a non-query command try { myStmt.executeUpdate(command); } catch (Exception e) { e.printStackTrace(); } } //** end of else clause of if (command.substring... } } out.println("</body></html>"); //** end of doPost method //** end of class e14_5