Upload
karthickajay
View
97
Download
16
Tags:
Embed Size (px)
DESCRIPTION
mm
Citation preview
Instructor's Resource Manual
to
Programming the World Wide Web
Seventh Edition
R.W. Sebesta
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Preface
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 fewer than 20 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 appeared in the last two decades 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 appeared. 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 was 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 technologies.
A visit to a bookstore, either a bricks-and-mortar store or a Web site, will turn up a large variety of books on Web technologies aimed at the practicing professional. One difficulty encountered by those teaching courses in Web programming technologies in colleges is the lack of textbooks that are targeted to their needs. Most of the books that discuss Web programming were written for professionals, rather than college students. Such books are written to fulfill the needs of professionals, which are quite different from those of college
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
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. On the one hand, 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 aimed at college students, not necessarily only computer science majors, but anyone who has taken at least two courses in programming. Although students are the primary target, the book is also useful for professional programmers who wish to learn Web programming.
The goal of the 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 HTML. The same is true for at least a half-dozen other Web 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 six editions of the 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 in the course build a basic, static Web site, using only HTML 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 and data structures, as well as C and assembly language, is helpful, as is the fact that many of them have learned some HTML on their own 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, particularly if a UNIX-based Web server is used for the course. Familiarity with a second language makes learning the new languages easier.
Table of Contents
The book is organized into three parts: the introduction (Chapter 1), client-side technologies (Chapters 2–8), and server-side technologies (Chapters 9–15).
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
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Chapter 1 are brief overviews of the most important topics of the rest of the book.
Chapter 2 provides an introduction to HTML, including images, links, lists, tables, and forms. Small examples are used to illustrate many of the HTML elements that are discussed in this chapter. A discussion of the parts of HTML5 that are now widely supported is included.
The topic of Chapter 3 is cascading style sheets, which provide the standard way of imposing style on the content specified in HTML 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 that are 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 other languages to leverage the 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.
Chapter 5 discusses some of the features of JavaScript that are related to HTML 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 HTML documents. The HTML5 canvas element is introduced.
One of the interesting applications of JavaScript is building dynamic HTML documents with the Document Object Model (DOM). Chapter 6 provides descriptions of a collection of some of the changes that can be made to documents with the use of JavaScript and the DOM. Included are positioning elements; 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; moving elements slowly; and dragging and dropping elements.
Chapter 7 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, XML 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 8 introduces the Flash authoring environment, which is used to create a wide variety of visual and audio presentations—in particular, those that include animation. A series of examples is used to illustrate the development processes, including drawing figures, creating text, using color, creating motion and shape animations, adding sound tracks to presentations, and designing components that allow the user to control the Flash movie.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Chapter 9 introduces PHP, a server-side scripting language that enjoys wide popularity, especially as a database access language for Web applications. 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 13.
Chapter 10 introduces Ajax, the relatively recent technology that is used to build Web applications with extensive user interactions that are more efficient than those same applications if they do not use Ajax. In addition to a thorough introduction to the concept and implementation of Ajax interactions, the chapter includes discussions of return document forms, Ajax toolkits, and Ajax security. Several examples are used to illustrate approaches to using Ajax.
Java Web software is discussed in Chapter 11. The chapter introduces the mechanisms for building Java servlets and gives several examples of how servlets can be used to present interactive Web documents. The NetBeans framework is introduced and used throughout the chapter. Support for cookies in servlets is presented and illustrated with an example. Then JSP is introduced through a series of examples, including the use of code-behind files. This discussion is followed by an examination of JavaBeans and JavaServer Faces, along with examples to illustrate their use.
Chapter 12 is an introduction to ASP.NET, although it begins with a brief introduction to the .NET Framework and C#. ASP.NET Web controls and some of the events they can raise and how those events can be handled are among the topics discussed in this chapter. ASP.NET AJAX is also discussed. Finally, constructing Web services with ASP.NET is introduced. Visual Studio is introduced and used to develop all ASP.NET examples.
Chapter 13 provides an introduction to database access through the Web. This chapter includes a brief discussion of 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 PHP, using Java JDBC, and using ASP.NET. All three are illustrated with complete examples. All of the program examples in the chapter use MySQL.
Chapter 14 introduces the Ruby programming language. Included are the scalar types and their operations, control statements, arrays, hashes, methods, classes, code blocks and iterators, and pattern matching. There is, of course, much more to Ruby, but the chapter includes sufficient material to allow the student to use Ruby for building simple programs and Rails applications.
Chapter 15 introduces the Rails framework, designed to make the construction of Web applications relatively quick and easy. Covered are simple document requests, both static and dynamic, and applications that use databases, including the use of scaffolding.
Appendix A introduces Java to those who have experience with C++ and object-oriented programming, but who do not know Java. Such students 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.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Appendix B is a list of 140 named colors, along with their hexadecimal codings.
Support Materials
Supplements for the book are available at Addison-Wesley’s Web site www.pearsonhighered.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
•• A Word document listing errors found in the book
Additional support material, including solutions to selected exercises and figures from the book, are available only to instructors adopting this textbook for classroom use. Contact your school’s Pearson Education representative for information on obtaining access to this material, or visit pearsonhighered.com.
Software Availability
Most of the software systems described in this book are available free to students. These systems include browsers that provide interpreters for JavaScript and parsers for XML. Also, PHP, Ruby, and Java language processors, as well as the Rails framework, Java class libraries to support servlets, and Java JDBC, are available and free. ASP.NET is supported by the .NET software available from Microsoft. The Visual Web Developer 2010, a noncommercial version of Visual Studio, is available free from Microsoft. A free 30-day trial version of the Flash development environment is available from Adobe.
Differences between the Sixth Edition and the Seventh Edition
The seventh edition of this book differs significantly from the sixth.The markup documents in the whole book were modified to reflect the
change from XHTML 1.0 to HTML5. However, the XHTML syntax rules are used in all example documents.
Chapter 2 was revised to update the discussion for HTML, rather than XHTML 1.0. A section was added on some of the new elements in HTML5. Sections on align, valign, cellpadding, and cellspacing were removed. W3C validation was replaced by Total Validation.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Sections on contextual selectors and text spacing were removed from Chapter 3. All CSS sizes used in this chapter (and the remainder of the book) were changed from points to em.
A discussion of the HTML5 canvas element was added to Chapter 5.Chapter 8 was revised to cover Flash 5.5, rather than Flash 4. Also, a
section on importing graphic figures was added.Chapter 11 was revised to use version 7 of the NetBeans development
system, rather than 6.7. This required numerous changes. Chapter 12 was revised to use Visual Studio 2010.In Chapter 13, the discussion of the PHP/MySQL functions was revised to
reflect the new version of these functions. The PHP/MySQL examples also were updated to use these new functions. The section on JDBC/MySQL was updated to use NetBeans 7.
Chapter 15 was revised to discuss the use of Rails 3.1 rather than Rails 2.4. This required extensive changes. Also, the discussion of Instant Rails was dropped, as was the section on Rails with Ajax.
Throughout the book, numerous small changes were made to improve the correctness and clarity of the material.
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Table of ContentsPreface xiii
1 Fundamentals 00
1.1 A Brief Introduction to the Internet 00
1.2 The World Wide Web 00
1.3 Web Browsers 00
1.4 Web Servers 00
1.5 Uniform Resource Locators 00
1.6 Multipurpose Internet Mail Extensions 00
1.7 The Hypertext Transfer Protocol 00
1.8 Security 00
1.9 The Web Programmer’s Toolbox 00
Summary 00
Review Questions 00
Exercises 00
2 Introduction to HTML/XHTML 00
2.1 Origins and Evolution of HTML and XHTML 00
2.2 Basic Syntax 00
2.3 Standard HTML Document Structure 00
2.4 Basic Text Markup 00
2.5 Images 00
2.6 Hypertext Links 00
2.7 Lists 00
2.8 Tables 00
2.9 Forms 00
2.10 HTML5
2.11 Syntactic Differences between HTML and XHTML 00
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Summary 00
Review Questions 00
Exercises 00
3 Cascading Style Sheets 00
3.1 Introduction 00
3.2 Levels of Style Sheets 00
3.3 Style Specification Formats 00
3.4 Selector Forms 00
3.5 Property Value Forms 00
3.6 Font Properties 000
3.7 List Properties 000
3.8 Alignment of Text 000
3.9 Color 000
3.10 The Box Model 000
3.11 Background Images 000
3.12 The <span> and <div> Tags 000
3.13 Conflict Resolution 000
Summary 000
Review Questions 000
Exercises 000
4 The Basics of JavaScript 000
4.1 Overview of JavaScript 000
4.2 Object Orientation and JavaScript 000
4.3 General Syntactic Characteristics 000
4.4 Primitives, Operations, and Expressions 137
4.5 Screen Output and Keyboard Input 000
4.6 Control Statements 000
4.7 Object Creation and Modification 158©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
4.8 Arrays 000
4.9 Functions 000
4.10 An Example 000
4.11 Constructors 000
4.12 Pattern Matching Using Regular Expressions 000
4.13 Another Example 000
4.14 Errors in Scripts 000
Summary 000
Review Questions 000
Exercises 000
5 JavaScript and HTML Documents 000
5.1 The JavaScript Execution Environment 000
5.2 The Document Object Model 000
5.3 Element Access in JavaScript 000
5.4 Events and Event Handling 000
5.5 Handling Events from Body Elements 000
5.6 Handling Events from Button Elements 000
5.7 Handling Events from Text Box and Password Elements 000
5.8 The DOM 2 Event Model 000
5.9 The canvas Element
5.10 The navigator Object 000
5.11 DOM Tree Traversal and Modification 000
Summary 000
Review Questions 000
Exercises 000
6 Dynamic Documents with JavaScript 000
6.1 Introduction 000
6.2 Positioning Elements 000©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
6.3 Moving Elements 234
6.4 Element Visibility 000
6.5 Changing Colors and Fonts 000
6.6 Dynamic Content 000
6.7 Stacking Elements 000
6.8 Locating the Mouse Cursor 000
6.9 Reacting to a Mouse Click 000
6.10 Slow Movement of Elements 000
6.11 Dragging and Dropping Elements 000
Summary 000
Review Questions 000
Exercises 000
7 Introduction to XML 000
7.1 Introduction 000
7.2 The Syntax of XML 000
7.3 XML Document Structure 000
7.4 Document Type Definitions 000
7.5 Namespaces 000
7.6 XML Schemas 000
7.7 Displaying Raw XML Documents 000
7.8 Displaying XML Documents with CSS 000
7.9 XSLT Style Sheets 000
7.10 XML Processors 000
7.11 Web Services 000
Summary 000
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Review Questions 000
Exercises 000
8 Introduction to Flash 000
8.1 Origins and Uses of Flash 000
8.2 A First Look at the Flash Authoring Environment 000
8.3 Drawing Tools 000
8.4 Static Graphics 000
8.5 Animation and Sound 000
8.6 User Interactions 000
Summary 000
Review Questions 000
Exercises 000
9 Introduction to PHP 000
9.1 Origins and Uses of PHP 000
9.2 Overview of PHP 000
9.3 General Syntactic Characteristics 000
9.4 Primitives, Operations, and Expressions 000
9.5 Output 000
9.6 Control Statements 000
9.7 Arrays 000
9.8 Functions 000
9.9 Pattern Matching 000
9.10 Form Handling 000
9.11 Cookies 000
9.12 Session Tracking 000
Summary 000
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Review Questions 000
Exercises 000
10 Introduction to Ajax 000
10.1 Overview of Ajax 000
10.2 The Basics of Ajax 000
10.3 Return Document Forms 000
10.4 Ajax Toolkits 000
10.5 Security and Ajax 000
Summary 000
Review Questions 000
Exercises 000
11 Java Web Software 000
11.1 Introduction to Servlets 000
11.2 The NetBeans Integrated Development Environment 000
11.3 A Survey Example 000
11.4 Storing Information on Clients 000
11.5 JavaServer Pages 000
11.6 JavaBeans 000
11.7 Model-View-Controller Application Architecture 000
11.8 JavaServer Faces 000
Summary 000
Review Questions 000
Exercises 000
12 Introduction to ASP.NET 000
12.1 Overview of the .NET Framework 000
12.2 A Bit of C# 000
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
12.3 Introduction to ASP.NET 000
12.4 ASP.NET Controls 000
12.5 ASP.NET AJAX 000
12.6 Web Services 000
Summary 000
Review Questions 000
Exercises 000
13 Database Access through the Web 000
13.1 Relational Databases 000
13.2 An Introduction to the Structured Query Language 000
13.3 Architectures for Database Access 000
13.4 The MySQL Database System 000
13.5 Database Access with PHP and MySQL 000
13.6 Database Access with JDBC and MySQL 000
13.7 Database Access with ASP.NET and MySQL 000
Summary 000
Review Questions 000
Exercises 000
14 Introduction to Ruby 000
14.1 Origins and Uses of Ruby 000
14.2 Scalar Types and Their Operations 000
14.3 Simple Input and Output 000
14.4 Control Statements 000
14.5 Fundamentals of Arrays 000
14.6 Hashes 000
14.7 Methods 000
14.8 Classes 000
14.9 Blocks and Iterators 000©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
14.10Pattern Matching 000
Summary 000
Review Questions 000
Exercises 000
15 Introduction to Rails 000
15.1 Overview of Rails 000
15.2 Document Requests 000
15.3 Rails Applications with Databases 000
Summary 000
Review Questions 000
Exercises 000
Appendix A Introduction to Java 000
Appendix B Named Colors 000
Index 000
©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Solutions to Selected Exercises
Chapter 2
Exercise 2.1
<!DOCTYPE html><!-- e2_1.html This is a solution to Exercise 2.1 --><html lang = "en"><head> <title> Exercise 2.1 </title> <meta charset = "utf-8" /></head><body><h2> Ruper B. Baggins </h2><p>1321 Causeway Circle <br /> Middle, Earth <br />[email protected]<br /></p><hr /><h3> Bush Watcher </h3><p><em> Forest Keepers, Limited </em> <br />14 Cranberry Way <br />Middle, Earth <br /><strong> (no web site yet) </strong></p></body></html>
Exercise 2.3
<!DOCTYPE html"><!-- e2_3.html This is a solution to Exercise 2.3 --><html lang = "en"><head> <title> Exercise 2.3 </title> <meta charset = "utf-8" /></head><body>
16©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<h2> Ruper B. Baggins </h2><p>1321 Causeway Circle <br /> Middle, Earth <br />[email protected]<br /><br /><a href = "e2_31.html"> Mr. Baggins' Background </a></p><hr /><h3> Bush Watcher </h3><p><em> Forest Keepers, Limited </em> <br />14 Cranberry Way <br />Middle, Earth <br /><strong> (no web site yet) </strong></p></body></html>
<!DOCTYPE html><!-- e2_31.html This is part of the solution to Exercise 2.3 (The second document for the background info) --><html lang = "en"><head> <title> Exercise 2.3 (background) </title> <meta charset = "utf-8" /></head><body><p>Although we share the same family name, I am not in any wayrelated to the famous (or is it infamous) adventurer, Bilbo.I have a lovely wife, Elvira, and two grown children, Maxand Miriam. Max has chosen to follow me in my profession,which is described below. Miriam is a beekeeper for the townbookkeeper, who keeps bees as a second job.</p><p>I am employed by Forest Keepers, Limited. My job, as I understandit, is to keep an eye on the 4 acres of wild cranberries thatgrow in the swamp at the edge of the village forest. I am requiredto file a daily report, in triplicate, on the condition of thecranberry bushes. To accomplish my task, I walk by and inspect every cranberry bush in the swamp every workday. My employer providesme 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
<!DOCTYPE html>
17©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<!-- e2_4.html A solution to Exercise 2.4 - an unordered list --><html lang = "en"><head> <title> Unordered List </title> <meta charset = "utf-8" /></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
<!DOCTYPE html><!-- e2_8.html A solution to Exercise 2.8 - a nested, ordered list --><html lang = "en"><head> <title> An Ordered List </title> <meta charset = "utf-8" /></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>
18©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<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
<!DOCTYPE html><!-- e2_9.html A solution to Exercise 2.9 - a simple table --><html lang = "en"><head> <title> A simple table </title> <meta charset = "utf-8" /></head><body><table><caption> Trees </caption> <tr> <th> </th> <th> Pine </th> <th> Maple </th> <th> Oak </th> <th> Fir </th> </tr> <tr>
19©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<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.10
<!DOCTYPE html><!-- e2_10.html A solution to Exercise 2.10 - a simple table --><html lang = "en">
<head> <title> A simple table </title> <meta charset = "utf-8" /></head><body><table><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>
20©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
</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.17
<!DOCTYPE html><!-- e2_17.html A solution to Exercise 2.17 - a revision of 2.8 with headers and footers --><html lang = "en"><head> <title> An Ordered List </title> <meta charset = "utf-8" /></head><body><header> <h2> Bob's Relatives </h2> <h3> (Uncles, Aunts, and Cousins) </h3></header><ol> <li> Violet Vinelli (my mother) </li> <li> Frederick Vinelli <ol>
21©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<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><article> Family information can be neatly organized using any of several available software systems. These systems provide the capability of producing tree-structured drawings of the organization of a family.</article><footer><h4> As of January, 2012 <h4></footer></body>
22©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Chapter 3
Exercise 3.1
/* Book Layout Style Sheet */h1 {font: bold 2em Helvetica 'Times New Roman'}h2 {font: bold 1.8em Helvetica 'Times New Roman'}h3 {font: bold 1.2em Helvetica 'Times New Roman'}p {font: 1em 'Times New Roman'}
Exercise 3.2
<!DOCTYPE html><!-- e3_2.html A solution to Exercise 3.2 - a styled table --><html lang = "en"><head> <title> A Styled Table </title> <style type = "text/css"> <!-- td.win {font-size: 1.2em; color: red;} td.lose {font-size: 1.1em; color: blue;} --> </style> <meta charset = "utf-8" /></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>
23©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
</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
<!DOCTYPE html"><!-- e3_4.html A solution for Exercise 3.4 - floating a text element --><html lang = "en"><head> <title> Floating a text element </title> <meta charset = "utf-8" /></head><body><p style = "float: left; width: 1.5in; margin-right: 10px; margin-bottom: 10px;" >My airplane soars like an eagle and handles likea 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>
24©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
</html>
Exercise 3.6
<!DOCTYPE html><!-- e36.html A solution to Exercise 3.6 --><html lang = "en"> <head> <title> Exercise 3.6 </title> <style type = "text/css"> ol {list-style-type: upper-roman;} ol ol {list-style-type: upper-alpha;} ol ol ol {list-style-type: decimal;} li.pink {color: pink} li.blue {color: blue} li.red {color: red} </style> <meta charset = "utf-8" /> </head> <body> <ol> <li class = "pink"> Compact Cars <ol> <li> Two door
25©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<ol> <li> Hyundai Accent </li> <li> Chevrolet Cobalt </li> <li> Honda Civic </li> </ol> </li> <li> Four door <ol> <li> Hyundai Accent </li> <li> Chevrolet Cobalt </li> <li> Honda Civic </li> </ol> </li> </ol> </li> <li class = "blue"> Midsize Cars <ol> <li> Two door <ol> <li> Honda Accord </li> <li> Hyundai Genesis </li> <li> Nissan Altima </li> </ol> </li> <li> Four door <ol> <li> Honda Accord </li> <li> Dodge Avenger </li> <li> Ford Fusion </li> </ol> </li> </ol> </li> <li class = "red"> Sports Cars <ol> <li> Coupe <ol> <li> Jaguar XK </li> <li> Ford Mustang </li> <li> Nissan Z </li> </ol> </li> <li> Convertible <ol> <li> Mazda Miata </li> <li> Ford Mustang </li> <li> Lotus Elise </li> </ol> </li> </ol> </li> </ol> </body></html>
26©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Exercise 3.12
<!DOCTYPE html><!-- e312.html A solution to Exercise 3.12 --><html lang = "en"> <head> <title> Exercise 3.12 </title> <style type = "text/css"> dt {font-family: Courier; font-size: 1em;} dd {font-family: 'Times New Roman'; font-size: 1.1em; font-style: italic;} </style> <meta charset = "utf-8" /> </head> <body> <h3> Single-Engine Cessna Airplanes </h3> <dl> <dt> 152 </dt> <dd> Two-place trainer </dd> <dt> 172 </dt> <dd> Smaller four-place airplane </dd> <dt> 182 </dt> <dd> Larger four-place airplane </dd> <dt> 210 </dt> <dd> Six-place airplane - high performance </dd> </dl> </body></html>
Chapter 4
Exercise 4.1
<!DOCTYPE html><!-- e4_1.html - A solution to Exercise 4.1 --><html lang = "en"><head> <title> Exercise 4.1 </title> <meta charset = "utf-8" /></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;
27©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
document.write(number + ", " + square + ", " + cube + "<br />");}// --></script></body></html>
Exercise 4.2
<!DOCTYPE html><!-- e4_2.html - A solution to Exercise 4.2 --><html lang = "en"><head> <title> Exercise 4.2 </title> <meta charset = "utf-8" /></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
<!DOCTYPE html><!-- e4_4.html - A solution to Exercise 4.4 --><html lang = "en"><head> <title> Exercise 4.4 </title> <meta charset = "utf-8" /></head>
<body><script type = "text/javascript"><!--var first = 1, second = 1, next, count;
28©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
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
<!DOCTYPE html><!-- e4_6.html - A solution to Exercise 4.6 --><html lang = "en"><head> <title> Exercise 4.6 </title> <meta charset = "utf-8" /></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>
29©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Exercise 4.7
<!DOCTYPE html><!-- e4_7.html - A solution to Exercise 4.7 --><html lang = "en"><head> <title> Exercise 4.7 </title> <meta charset = "utf-8" /> <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/>");
30©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
}// --> </script></body></html>
Exercise 4.9
<!DOCTYPE html><!-- e4_9.html - A solution to Exercise 4.9 --><html lang = "en"><head> <title> Exercise 4.9 </title> <meta charset = "utf-8" /> <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>
31©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Exercise 4.14
<?xml version = "1.0" encoding = "utf-8"?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- e4_14.html - A solution to Exercise 4.14 --><html xmlns = "http://www.w3.org/1999/xhtml"><head> <title> Exercise 4.14 </title> <meta charset = "utf-8" /> <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);
32©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
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
<!DOCTYPE html><!-- e51.hmtl A solution to Exercise 5.1 - events with radio buttons --><html lang = "en"> <head> <title> Exercise 5.1 </title> <script type = "text/javascript" src = "e51.js" > </script> <meta charset = "utf-8" /> </head> <body> <h4> Choose your favorite color </h4> <form> <label> <input type = "radio" name = "colorButton" value = "red" onClick = "colorChoice('red')" /> Red </label> <br /> <label> <input type = "radio" name = "colorButton" value = "blue" onClick = "colorChoice('blue')" /> Blue </label> <br /> <label> <input type = "radio" name = "colorButton" value = "green" onClick = "colorChoice('green')" /> Green </label> <br /> <label> <input type = "radio" name = "colorButton" value = "yellow" onClick = "colorChoice('yellow')" /> Yellow </label> <br /> <label> <input type = "radio" name = "colorButton" value = "orange" onClick = "colorChoice('orange')" /> Orange </label> </form> </body></html>// e51.js - The JavaScript solution for Exercise 5.1//
33©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
// 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; }}
Exercise 5.2
<!DOCTYPE html><!-- e5_2.hmtl A solution to Exercise 5.2 - events with radio buttons --><html lang = "en"> <head> <title> Exercise 5.2 </title> <script type = "text/javascript" src = "e521.js" > </script> <meta charset = "utf-8" /> </head> <body> <h4> Choose your favorite color </h4>
<form id = "colorsForm"> <p> <label> <input type = "radio" name = "colorButton" value = "red" /> Red </label> </p> <p> <label> <input type = "radio" name = "colorButton" value = "blue" /> Blue </label> </p><p> <label> <input type = "radio" name = "colorButton" value = "green" /> Green
34©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
</label> </p><p> <label> <input type = "radio" name = "colorButton" value = "yellow" /> Yellow </label> </p><p> <label> <input type = "radio" name = "colorButton" value = "orange" /> Orange </label> </p> </form> <script type = "text/javascript" src = "e522.js" > </script> </body></html>
// e521.js - JavaScript for the solution to Exercise 5.2//// 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.getElementById("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");
35©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
break; default: alert("Error in JavaScript function colorChoice"); break; }}
// e522.js - Handler registration for the solution to // Exercise 5.2
var dom = document.getElementById("colorsForm");dom.elements[0].onclick = colorChoice;dom.elements[1].onclick = colorChoice;dom.elements[2].onclick = colorChoice;dom.elements[3].onclick = colorChoice;dom.elements[4].onclick = colorChoice;
Exercise 5.4
<!DOCTYPE html><!-- e54.html A solution to Exercise 5.4 --><html lang = "en"> <head> <title> Exercise 5.4 </title> <script type = "text/javascript" src = "e54.js" > </script> <meta charset = "utf-8" /> </head> <body> <h3> Order Form </h3> <form name = "orderForm" onSubmit = "finish()"> <p> <label> <input type = "text" name = "apples" size = "3" onChange = "appleHandler()" /> Apples </label> </p><p> <label> <input type = "text" name = "oranges" size = "3" onChange = "orangeHandler()" /> Oranges </label> </p><p> <label> <input type = "text" name = "bananas" size = "3" onChange = "bananaHandler()" /> Bananas </label> </p><p> <input type = "reset" name = "reset" />
36©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<input type = "submit" name = "submit" /> </p> </form> </body></html>
// e54.js - The JavaScript file for the solution// to Exercise 5.4
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");}
Exercise 5.5
<!DOCTYPE html><!-- e55.html The XHTML part of a solution to Exercise 5.5 --><html lang = "en"> <head> <title> Exercise 5.5 </title> <script type = "text/javascript" src = "e551.js"> </script> <meta charset = "utf-8" /> </head>
<body> <h3> Order Form </h3> <form name = "" onSubmit = "finish()">
37©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<p> <label> <input type = "text" id = "apples" size = "3" /> Apples </label> </p><p> <label> <input type = "text" id = "oranges" size = "3" /> Oranges </label> </p><p> <label> <input type = "text" id = "bananas" size = "3" /> Bananas </label> </p><p> <input type = "reset" name = "reset" /> <input type = "submit" name = "submit" /> </p> </form> <script type = "text/javascript" src = "e552.js"> </script> </body></html>
// e551.js -- The JavaScript part of the solution// to Exercise 5.5
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;
38©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
} 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");}
// e552.js - The JavaScript code to register the// handlers
document.getElementById("apples").onchange = appleHandler;document.getElementById("oranges").onchange = orangeHandler;document.getElementById("bananas").onchange = bananaHandler;
Exercise 5.6
<!DOCTYPE html><!-- e56.html A solution to Exercise 5.6 --><html lang = "en"> <head> <title> Exercise 5.6 </title> <script type = "text/javascript" src = "e561.js" > </script> <meta charset = "utf-8" /> </head>
39©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<body> <h3> Order Form </h3> <form name = "orderForm" onSubmit = "finish()"> <p> <label> <input type = "text" id = "apples" size = "3" /> Apples </label> </p><p> <label> <input type = "text" id = "oranges" size = "3" /> Oranges </label> </p><p> <label> <input type = "text" id = "bananas" size = "3" /> Bananas </label> </p><p> <input type = "reset" name = "reset" /> <input type = "submit" name = "submit" /> </p> </form> <script type = "text/javascript" src = "e562.js" > </script> </body></html>
// e561.js - Event handlers for the solution to// Exercise 5.6
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 +
40©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
" 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");}
// e562.js - The body part of the JavaScript for the// solution to Exercise 5.6
// 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
41©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
appleDom.max = 99;appleDom.min = 0;orangeDom.max = 99;orangeDom.min = 0;bananaDom.max = 99;bananaDom.min = 0;
Chapter 6
Exercise 6.1
<!DOCTYPE html><!-- e6_1.html A solution to Exercise 6.1 --><html lang = "en"><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> <meta charset = "utf-8" /></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>
42©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
</body></html>
Exercise 6.2
<!DOCTYPE html><!-- e62.html The XHTML part of a solution to Exercise 6.2 --><html lang = "en"> <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 type = "text/javascript" src = "e62.js" > </script> <meta charset = "utf-8" /> </head> <body>
<h2> Background Image Position Control Buttons </h2> <p> <form name = "moveControl"> <label> <input type = "radio" name = "choser" checked = "checked" onclick = "moveIt('picture', 150, 100)" /> Northwest </label> <p/><p> <label> <input type = "radio" name = "choser" onclick = "moveIt('picture', 150, 300)" /> Northeast </label> </p><p> <label> <input type = "radio" name = "choser" onclick = "moveIt('picture', 300, 300)" /> Southeast </label> <p/><p> <label> <input type = "radio" name = "choser" onclick = "moveIt('picture', 300, 100)" /> Southwest </label>
43©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
</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>
// e62.js - The JavaScript file for the solution to// Exercise 6.2
/* 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 + "px"; dom.left = newLeft + "px"; }
Exercise 6.3
<!DOCTYPE html><!-- e63.html The XHTML part of a solution to Exercise 6.3 --><html lang = "en"> <head> <title> Exercise 6.3 </title>
<style type = "text/css">
44©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
/* A style for the paragraph of text */
.regtext {position: absolute; top: 200px; left: 100px; font-family: Times; font-size: 14pt; width: 330px}
</style>
<script type = "text/javascript" src = "e63.js" > </script> <meta charset = "utf-8" /> </head>
<body>
<h2> Background Image Visibility Control Buttons </h2> <form name = "visibilityControl"> <p> <label> <input type = "checkbox" name = "choser" onclick = "flipImage('northwest')" /> Northwest </label> <p/><p> <label> <input type = "checkbox" name = "choser" onclick = "flipImage('northeast')" /> Northeast </label> </p><p> <label> <input type = "checkbox" name = "choser" onclick = "flipImage('southeast')" /> Southeast </label> </p><p> <label> <input type = "checkbox" name = "choser" onclick = "flipImage('southwest')" /> Southwest </label> </p> </form>
<p id = "northwest" style = "background-image: url(c172.gif); visibility: hidden; position: absolute; left: 100px; top: 200px; width: 100px"> <br/><br/><br/><br/><br/> </p>
<p id = "northeast" style = "background-image: url(c172.gif); visibility: hidden; position: absolute; left: 300px; top: 200px; width: 100px"> <br/><br/><br/><br/><br/> </p>
<p id = "southeast" style = "background-image: url(c172.gif); visibility: hidden; position: absolute; left: 300px; top: 350px; width: 100px"> <br/><br/><br/><br/><br/> </p>
45©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<p id = "southwest" style = "background-image: url(c172.gif); visibility: hidden; position: absolute; left: 100px; top: 350px; 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>
// e63.js - The JavaScript part of a solution to// Exercise 6.3
/* 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"; }
Exercise 6.5
<!DOCTYPE html><!-- e65.html A solution to Exercise 6.5 --><html lang = "en">
46©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<head> <title> Exercise 6.5 </title> <style type = "text/css" > .planes {position: absolute; top: 100; left: 0; z-index: 0;" /> </style> <script type = "text/javascript" src = "e65.js" > </script> <meta charset = "utf-8" /> </head> <body> <p> <a href = "JAVASCRIPT:toTop('C172')"> 1 </a> </p><p> <a href = "JAVASCRIPT:toTop('cix')"> 2 </a> </p><p> <a href = "JAVASCRIPT:toTop('C182')"> 3 </a> </p><p> <img class = "planes" id = "C172" src = "c172.gif" alt = "(Picture of a C172)" /> <img class = "planes" id = "cix" src = "cix.gif" alt = "(Picture of a Citation airplane)" /> <img class = "planes" id = "C182" src = "c182.gif" alt = "(Picture of a C182)" /> </p><p></p> </body></html>
// e65.js - The JavaScript part of a solution to// Exercise 6.5
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;}
Chapter 7
47©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Exercise 7.1
<?xml version = "1.0" encoding = "utf-8"?>
<!-- cars.dtd - a document type definition for the cars.xml document A solution to Exercise 7.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 accessories radio CDATA #REQUIRED><!ATTLIST accessories air_conditioning CDATA #REQUIRED>
<!ATTLIST accessories power_windows CDATA #REQUIRED> <!ATTLIST accessories power_steering CDATA #REQUIRED> <!ATTLIST accessories power_brakes CDATA #REQUIRED>
<!ENTITY c "Chevrolet"><!ENTITY f "Ford"><!ENTITY d "Dodge"><!ENTITY h "Honda"><!ENTITY n "Nisson"><!ENTITY t "Toyota">
Exercise 7.2
<?xml version = "1.0" encoding = "utf-8"?>
<!-- cars.xml - A solution to Exercise 7.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>
48©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<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 7.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;}
49©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Exercise 7.5
<?xml version = "1.0" encoding = "utf-8"?><!-- xslcar.xsl A solution to Exercise 7.5 -->
<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 7.6
<?xml version = "1.0" encoding = "utf-8"?><!-- xslcars.xsl A solution to Exercise 7.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 />
50©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<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
<!DOCTYPE html><!-- e9_1.php
A solution to Exercise 9.1-->
<html lang = "en"><head> <title> e9_1.php </title> <meta charset = "utf-8" /> <?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>
51©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Exercise 9.3
<!DOCTYPE html><!-- e9_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 lang = "en"><head> <title> e9_3.php </title> <meta charset = "utf-8" /></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 />";
52©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
$sorted_keys = array_keys($tbl); sort($sorted_keys); foreach ($sorted_keys as $word) print "$tbl[$word] <br />";?></body></html>
Exercise 9.5
<!DOCTYPE html><!-- e9_5.php Use a function to find the first four-digit number in a given string.
--><html lang = "en"><head> <title> e9_5.php </title> <meta charset = "utf-8" /></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 false
return false;
} #** 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
53©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
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 9.6
<!DOCTYPE html><!-- e9_6.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 lang = "en"><head> <title> e9_6.php </title> <meta charset = "utf-8" /></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);
54©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
// 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>
Exercise 9.8
<!DOCTYPE html><!-- e98.html A solution to Exercise 9.8 --><html lang = "en"> <head> <title> Exercise 9.9 </title> <meta charset = "utf-8" /> </head> <body> <a href = "e98.php"> Please give me a greeting </a> </body></html>
55©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<!DOCTYPE html><!-- e98.php The php part of a solution to Exercise 9.8 --><html lang = "en"> <head> <title> Exercise 9.8 </title> <meta charset = "utf-8" /> </head> <body> <?php $greetings = array("Hello!", "Hej!", "Hallo!", "Hola!", "Bonjour!"); $sub = rand(0, 4); print "$greetings[$sub]"; ?> </body></html>
Chapter 10
Exercise 10.3
<!DOCTYPE html><!-- e103.html This is the XHTML part of a solution to Exercise 10.3. Uses Ajax and the name to fill in the customer's address, given his or her name --><html lang = "en"> <head> <title> Popcorn Sales Form (Ajax) </title> <style type = "text/css"> img {position: absolute; left: 400px; top: 50px;} </style> <script type = "text/JavaScript" src = "e103.js"> </script> <meta charset = "utf-8" /> </head> <body> <h2> Welcome to Millenium Gynmastics Booster Club Popcorn Sales </h2> <form action = "">
<!-- A borderless table of text widgets for name and address --> <table> <tr> <td> Buyer's Name: </td> <td> <input type = "text" name = "name" onblur = "getAddress(this.value)" size = "30" />
56©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
</td> </tr> <tr> <td> Street Address: </td> <td> <input type = "text" name = "address" id = "address" size = "30" /> </td> </tr> <tr> <td> Zip code: </td> <td> <input type = "text" name = "zip" size = "10" /> </td> </tr> <tr> <td> City </td> <td> <input type = "text" name = "city" size = "30" /> </td> </tr> <tr> <td> State </td> <td> <input type = "text" name = "state" size = "30" /> </td> </tr> </table> <img src = "popcorn.jpg" alt = "picture of popcorn" /> <p /> <!-- The submit and reset buttons --> <p> <input type = "submit" value = "Submit Order" /> <input type = "reset" value = "Clear Order Form" /> </p> </form> </body></html>
// e103.js// Ajax JavaScript code for the e103.html document
/********************************************************/// function getAddress// parameter: name// action: create the XMLHttpRequest object, register the// handler for onreadystatechange, prepare to send// the request (with open), and send the request,// along with the name, to the server// includes: the anonymous handler for onreadystatechange, // which is the receiver function, which gets the // response text, and puts it in the document
function getAddress(name) {
57©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
alert ("The value of name in getAddress is:" + name + "\n"); var xhr = new XMLHttpRequest();
// Register the embedded receiver function as the handler xhr.onreadystatechange = function () { if (xhr.readyState == 4) { var result = xhr.responseText;alert ("responseText is: " + result + "\n"); document.getElementById("address").value = result; } } xhr.open("GET", "getStreet.php?name=" + name, true); xhr.send(null);}
<?php// getStreet.php // Gets the form value from the "name" widget, looks up the // address for that name, and prints it for the// form $addresses = array("John Beagle" => "1301 East 12th Street", "Fred Magillicoti" => "12361 Bellview Road", "John Smith" => "127 North Main Street", "Mike Mutt" => "422 Dogtail Road", "Pussy Cat" => "8913 Alans Alley" ); header("Content-Type: text/plain"); $name = $_GET["name"]; if (array_key_exists($name, $addresses)) print $addresses[$name]; else print " ";?>
Exercise 10.5
<!DOCTYPE html><!-- e105.html Solution to Exercise 10.5 --><html lang = "en"> <head> <title> Popcorn Sales Form (Ajax-Dojo) </title> <style type = "text/css"> img {position: absolute; left: 400px; top: 50px;} </style> <script type = "text/javascript" src = "dojo/dojo.js"> </script> <script type = "text/javascript" src = "e105.js"> </script> <meta charset = "utf-8" /> </head>
58©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<body> <h2> Welcome to Millenium Gynmastics Booster Club Popcorn Sales </h2> <form action = "">
<!-- A borderless table of text widgets for name and address --> <table> <tr> <td> Buyer's Name: </td> <td> <input type = "text" name = "name" size = "30" /> </td> </tr> <tr> <td> Street Address: </td> <td> <input type = "text" name = "street" size = "30" /> </td> </tr> <tr> <td> Zip code: </td> <td> <input type = "text" name = "zip" size = "10" onblur = "getPlace(this.value)" /> </td> </tr> <tr> <td> City </td> <td> <input type = "text" name = "city" id = "city" size = "30" /> </td> </tr> <tr> <td> State </td> <td> <input type = "text" name = "state" id = "state" size = "30" /> </td> </tr> </table> <img src = "popcorn.jpg" alt = "picture of popcorn" /> <p /> <!-- The submit and reset buttons --> <p> <input type = "submit" value = "Submit Order" /> <input type = "reset" value = "Clear Order Form" /> </p> </form> </body></html>
// e105.js// Ajax JavaScript code for the e105.html document
59©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
/********************************************************/// function getPlace// parameter: zip code// action: call dojo.io.bind to do the Ajax request for// the city and state
function getPlace(zip) { dojo.io.bind({ url: "getCityState.php?zip=" + zip, load: function (type, data, evt) { var place = data.split(', '); if (dojo.byId("city").value == "") dojo.byId("city").value = place[0]; if (dojo.byId("state").value == "") dojo.byId("state").value = place[1]; }, error: function (type, data, evt) { alert("Error in request, returned data: " + data); }, method: "GET", mimetype: "text/plain" } );}
Chapter 11
Exercise 11.2
<%-- Document : index (of the greet5 (Exercise 11.2) project) Created on : Mar 14, 2009, 8:23:49 PM Author : bob Purpose : Display one of five different greetings on each call (Exercise 11.2)--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE html><html lang = "en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Exercise 11.2</title> </head> <body> <form action = "Greet5" method = "get"> <p> Press the button to get a greeting <input type = "submit" value = "Get greeting" /> </p> </form> </body></html>
60©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
/* Greet5 servlet (Exercise 11.2) */
import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
public class Greet5 extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String [] messages = {"Howdy!", "Hej!", "Hallo!", "Hola!", "Bonjour!"}; int sub; try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Greet5</title>"); out.println("</head>"); out.println("<body>"); sub = (int) (Math.random() * 5); out.println("<strong>" + messages[sub] + "</strong>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }
Exercise 11.4
<%-- Document : index - for the solution to Exercise 11.4 Created on : May 24, 2008, 8:37:33 PM Author : bob--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE html><html lang = "en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Exercise 11.4</title>
61©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
</head> <body> <form method="POST" action="Survey"> <h2> Welcome to the Consumer Electronics Purchasing Survey </h2> <p /> <h4> Your Gender: </h4> <p> <label> <input type="radio" name="gender" value="female" checked="checked" /> Female <br /> </label> <label> <input type="radio" name="gender" value="male" /> Male <br /> <br /> <br /> </label> </p> <p> <label> <input type="radio" name="vote" value="0" /> TV <br /> </label> <label> <input type="radio" name="vote" value="1" /> Digital Camera <br /> </label> <label> <input type="radio" name="vote" value="2" /> MP3 player <br /> </label> <label> <input type="radio" name="vote" value="3" /> DVD player/recorder <br /> </label> <label> <input type="radio" name="vote" value="4" /> Camcorder <br /> </label> <label> <input type="radio" name="vote" value="5" /> PDA <br /> </label> <label> <input type="radio" name="vote" value="6" checked="checked" /> Other <br /> <br /> </label> <input type = "submit" value = "Submit Vote" /> <input type = "reset" value = "Clear Vote Form" /> </p> </form> </body></html>
62©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
/* e114 - Servlet for Exercise 11.4 */
import java.io.*;import java.net.*;import javax.servlet.*;import javax.servlet.http.*;
public class Survey extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int votes[] = null; int index; int sumFemales, sumMales; int vote; File survdat = new File("survdat.ser"); String gender; String products[] = {" TV", "Digital Camera", "MP3 player", "DVD player/recorder", "Camcorder", "PDA", Other"};
// Set the content type for the response output and get a // writer response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter();
// Create the initial part of the response document out.println("<html>"); out.println("<head>"); out.println("<title>Return message</title>"); out.println("</head>"); out.println("<body>");
// Synchronize a block for the votes file access synchronized (this) {
// If the file already exists, read in its data try { if (survdat.exists()) { ObjectInputStream indat = new ObjectInputStream( new FileInputStream(survdat)); votes = (int[]) indat.readObject(); indat.close(); } // If the file does not exist (this is the first // vote), create the votes array else { votes = new int[15]; votes[14] = 0; } } catch (Exception e) { e.printStackTrace(); }
// Get the gender of the survey respondee gender = request.getParameter("gender");
63©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
// Increment the visits counter votes[14]++;
// Add the consumer electronics vote of the response to // the votes array vote = Integer.parseInt(request.getParameter("vote")); if (gender.equals("male")) { vote += votes.length / 2; } votes[vote]++; //Write updated votes array to disk ObjectOutputStream outdat = new ObjectOutputStream( new FileOutputStream(survdat)); outdat.writeObject(votes); outdat.flush(); outdat.close();
} //** end of the synchronized block
// Create the initial response information out.println( "<h3> Thank you for participating in the"); out.println(" Consumer Electronics Survey </h3>"); out.println("You are visitor number " + votes[14] + "<br />"); out.println("<h4> Current Survey Results: </h4>");
// Create the total votes return information for female // respondents out.println("<h5> For Female Respondents </h5>"); // First, sum the votes for females and males sumFemales = 0; sumMales = 0; for (index = 0; index < votes.length / 2; index++) { sumFemales += votes[index]; sumMales += votes[index + votes.length / 2]; } for (index = 0; index < votes.length / 2; index++) { out.print(products[index]); out.print(": "); if (sumFemales > 0) { out.print((100 * votes[index]) / sumFemales); out.println("%"); } else out.println(0); out.println("<br />"); }
// Create the total votes return information for male // respondents out.println("<h5> For Male Respondents </h5>"); for (index = votes.length / 2; index < votes.length; index++) {
64©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
out.print(products[index - votes.length / 2]); out.print(": "); if (sumMales > 0) { out.print((100 * votes[index]) / sumMales); out.println("%"); } else out.println(0); out.println("<br />"); } out.close(); }
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } }
Exercise 11.7
<%-- Document : index for Exercise 11.7 Created on : May 25, 2008, 9:17:57 PM Author : bob Presents a ballot to the user and calls the VoteCounter2 servlet for form handling--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE html><html lang = "en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title> Ballot </title> </head> <body> <form action="VoteCounter2" method="POST"> <h3> Please choose one candidate for dogcatcher </h3> <p> <input type="radio" name="vote1" value="Dogman" /> Daren Dogman <br /> <input type="radio" name="vote1" value="Taildragger" /> Timmy Taildragger <br /> <input type="radio" name="vote1" value="Dogpile" /> Don Dogpile <br /> </p> <h3> Please choose one candidate for catcatcher </h3> <p> <input type="radio" name="vote2" value="Catland" /> Kitty Catland <br />
65©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<input type="radio" name="vote2" value="El Gato" /> Al El Gato <br /> <input type="radio" name="vote2" value="Katnip" /> Kitten Katnip <br /> <input type="radio" name="vote2" value="Cat" /> Tommie Cat <br /> <input type="radio" name="vote2" value="Feline" /> Fred Feline <br /> </p><p> <input type = "submit" value = "Submit ballot" /> </p> </form> </body></html>
// VoteCounter2.java - Exercise 11.7// This servlet processes the ballot form, returning a // document asking for a new vote if no vote was made on the// ballot. For legitimate ballots, the vote is added to// the current totals, and those totals are presented to // the user in a return document.// A cookie is returned to the voter, recording the fact// that a vote was received. The servlet examines all votes// for cookies to ensure that there is no multiple voting.// The voting data file, votesdat2.dat, is stored on the Web// server.
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class VoteCounter2 extends HttpServlet {
Cookie cookies[] = null; int index; PrintWriter out; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie newCookie; int votes[] = null; int sumCatVotes; int sumDogVotes; String vote1; String vote2; File votesdat2 = new File("votesdat2.ser"); String dogCandidates[] = {"Daren Dogman", "Timmy Taildragger", "Don Dogpile"}; String catCandidates [] = {"Kitty Catland", "Al El Gato", "Kitten Katnip", "Tommie Cat", "Fred Feline"}; // Get cookies from the request cookies = request.getCookies();
// Check to see if there was a vote on the form vote1 = request.getParameter("vote1");
66©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
vote2 = request.getParameter("vote2"); if (vote1 == null || vote2 == null) { //** No legal vote
// Create the return document makeHeader(response); out.println( "You did not vote for both <br />"); out.println( "Please mark the ballot completely and resubmit"); } //** end of if (vote == null) ... else { //** There was a vote
// Check to see if this client voted before if (!votedBefore()) {
// No previous vote, so get the contents of the file // (if the file already exists)
// Synchronize block for file input/output synchronized (this) { if (votesdat2.exists()) { ObjectInputStream indat = new ObjectInputStream( new FileInputStream(votesdat2));
// We need the try/catch here because // readObject can throw ClassNotFoundException try { votes = (int[]) indat.readObject(); } catch (ClassNotFoundException problem) { problem.printStackTrace(); } } //** end of if(votesdat.exists() ... // If the file does not exist (this is the first // vote), create the votes array else { votes = new int[8]; } // Add the new vote to the votes array if (vote1.equals("Dogman")) votes[0]++; else if (vote1.equals("Taildragger")) votes[1]++; else votes[2]++; if (vote2.equals("Catland")) votes[3]++; else if (vote2.equals("El Gato")) votes[4]++; else if (vote2.equals("Katnip")) votes[5]++; else if (vote2.equals("Cat")) votes[6]++; else votes[7]++; // Write updated votes array to disk
67©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
ObjectOutputStream outdat = new ObjectOutputStream( new FileOutputStream(votesdat2)); outdat.writeObject(votes); outdat.flush(); outdat.close(); } //** end of synchronized block
// Attach a cookie to the response newCookie = new Cookie("iVoted", "true"); newCookie.setMaxAge(5); //** Set to 5 for testing response.addCookie(newCookie);
// Write a response message makeHeader(response); out.println("Your vote has been received"); out.println( "<br /><br /> Current Voting Percentages: <br />");
// Compute the total dog and cat votes sumCatVotes = 0; sumDogVotes = 0; for (index = 0; index < 3; index++) sumDogVotes += votes[index]; for (index = 3; index < 8; index++) sumCatVotes += votes[index];
// Create the dog votes percentages out.println("<h3> For Dogcatcher </h3>"); for (index = 0; index < 3; index++) { out.print(dogCandidates[index]); out.print(": "); if (sumDogVotes > 0) out.println( ((100 * votes[index]) / sumDogVotes) + "% <br />"); else out.println(0 + "% <br />"); } // Create the cat votes percentages out.println("<br /> <br /> <h3> For Catcatcher </h3>"); for (index = 3; index < 8; index++) { out.print(catCandidates[index - 3]); out.print(": "); if (sumCatVotes > 0) out.println(((100 * votes[index]) / sumCatVotes) + "% <br />"); else out.println(0 + "% <br />"); } } //** end of if (!votedBefore() ... else { // The client voted before
// Write a response message makeHeader(response); out.println( "Your vote is illegal - you have already voted!");
68©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
} // end of else clause - client voted before } // end of else (there was a vote)
// Finish response document and close the stream out.println("</body> </html>"); out.close();
} //** end of ProcessRequest
//----------------------------------------------------------------- // Method votedBefore - return true if the client voted before; // false otherwise boolean votedBefore() { if (cookies == null || cookies.length == 0) { return false; } else {
// Check the cookies to see if this user voted before for (index = 0; index < cookies.length; index++) { if (cookies[index].getName().equals("iVoted")) { return true; } } // end of for (index = 0; ... return false; } //** end of if (cookies == null ... } //** end of votedBefore
//----------------------------------------------------------------- // Method makeHeader - get the writer and produce the // response header void makeHeader(HttpServletResponse response) throws IOException {
// Set content type for response and get a writer response.setContentType("text/html"); out = response.getWriter();
// Write the response document head and the message out.println("<html><head>"); out.println( "<title> Return message </title></head><body>"); } //** end of makeHeader
// Method doPost - just calls processRequest protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }} //** end of VoteCounter2
Chapter 12
69©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
Exercise 12.1
<!-- e12_1.aspx A simple example of an ASP.NET document with controls. It uses textboxes to get the name and age of the client, which are then displayed. --> <%@ Page language="c#" %>
<html> <head> <title> E12_1 </title> </head> <body> <form id="Form1" runat = "server"> <p> Your name: <asp:textbox id = "name" runat = "server" /> <br /> Your age: <asp:textbox id = "age" runat = "server" /> <br /> <asp:RadioButton GroupName = "marital" runat = "server" id = "single" Text = "Single" /> <br /> <asp:RadioButton GroupName = "marital" runat = "server" id = "married" Text = "Married" /> <br /> <asp:RadioButton GroupName = "marital" runat = "server" id = "divorced" Text = "Divorced" /> <br /> <asp:RadioButton GroupName = "marital" runat = "server" id = "widowed" Text = "Widowed" /> <br /> <asp:button id = "submit" runat = "server" Text = "Submit" /> <br /> <% if (IsPostBack) { %> Hello <%= name.Text %> <br /> You are <%= age.Text %> years old <br /> <% if (single.Checked) {%> You are single <% } else if (married.Checked) {%> You are married <% } else if (divorced.Checked) {%> You are divorced <% } else if (widowed.Checked) { %> You are widowed <% } } %> </p>
70©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
</form> </body></html>
Exercise 12.3
<!-- e123.aspx A solution to Exercise 12.3. A modification of controls.aspx. Adds text box for the user's address and a drop-down list for the user's favorite category of music, which is populated in the code-behind file. --> <%@ Page Language="C#" AutoEventWireup="true" CodeFile="e123.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head id="Head1" runat="server"> <title>E123</title></head><body> <form id="form1" runat="server"> <div> Name: <asp:TextBox ID="name" runat="server"></asp:TextBox> <br /><br /> Address: <asp:TextBox ID="address" runat="server"></asp:TextBox> Favorite color: <asp:DropDownList ID="color" runat="server" AutoPostBack="true" OnSelectedIndexChanged="colorItemSelected"> </asp:DropDownList> <br /><br /> Favorite category of music: <asp:DropDownList ID="music" runat="server" AutoPostBack="true" OnSelectedIndexChanged="musicItemSelected"> </asp:DropDownList> <br /><br /> <asp:Label ID="colorMessage" runat="server" Text=""></asp:Label> <br /><br /> <asp:Label ID="musicMessage" runat="server" Text=""></asp:Label> </div> </form></body></html>
// e123.aspx.cs// The code-behind file for e123.aspx
using System;
71©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
using System.Web;using System.Web.UI;using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { color.Items.Add(new ListItem("blue")); color.Items.Add(new ListItem("red")); color.Items.Add(new ListItem("green")); color.Items.Add(new ListItem("yellow")); music.Items.Add(new ListItem("rock")); music.Items.Add(new ListItem("rap")); music.Items.Add(new ListItem("country")); music.Items.Add(new ListItem("classical")); music.Items.Add(new ListItem("jazz")); } }
protected void colorItemSelected(object sender, EventArgs e) { string newMsg = string.Format( "Hi {0}; your favorite color is {1}", name.Text, color.SelectedItem); colorMessage.Text = newMsg; } protected void musicItemSelected(object sender, EventArgs e) { string newMsg = string.Format( "Hello {0}; your favorite category of music is {1}", name.Text, music.SelectedItem); musicMessage.Text = newMsg; }}
Exercise 12.4
<!-- e124.aspx A solution to Exercise 12.4 --> <%@ Page language="c#" %>
<html> <head> <title> Exercise 12.4 </title> </head> <body> <form runat = "server"> <p> Your name: <asp:TextBox id = "name" runat = "server" /> <asp:RequiredFieldValidator
72©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
ControlToValidate = "name" Display = "Static" runat = "server" ErrorMessage = "Please enter your name"> </asp:RequiredFieldValidator> <br />
Your address: <asp:TextBox id = "address" runat = "server" /> <asp:RegularExpressionValidator ControlToValidate = "address" Display = "Static" runat = "server" ErrorMessage = "Address must begin with a number" ValidationExpression = "\d+ [A-Z][a-z]*"> </asp:RegularExpressionValidator> <br />
Your phone number: <asp:TextBox id = "phone" runat = "server" /> <asp:RegularExpressionValidator ControlToValidate = "phone" Display = "Static" runat = "server" ErrorMessage = "Phone number form must be ddd-ddd-dddd" ValidationExpression = "\d{3}-\d{3}-\d{4}"> </asp:RegularExpressionValidator> <br />
Your age: <asp:TextBox id = "age" runat = "server" /> <asp:RangeValidator ControlToValidate = "age" Display = "Static" runat = "server" MaximumValue = "110" MinimumValue = "10" Type = "Integer" ErrorMessage = "Age must be in the range of 10 to 110"> </asp:RangeValidator> <br />
Your Social Security number: <asp:TextBox id = "ssn" runat = "server" /> <asp:RegularExpressionValidator ControlToValidate = "ssn" Display = "Static" runat = "server" ErrorMessage = "Social security number must have the form: ddd-dd-dddd" ValidationExpression = "\d{3}-\d{2}-\d{4}"> </asp:RegularExpressionValidator> <br /> <input type = "submit" value = "Submit" /> </p> </form>
73©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
</body></html>
Chapter 13
Exercise 13.2
No changes to access_cars.php are required to handle UPDATE and INSERT SQL commands. The mysqli_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 = mysqli_query($db, $query);
To determine the number of rows that were affected by the INSERT command, the mysqli_affected_rows function is used (with the result as its parameter).
Exercise 13.3
// e13_3.java// This servlet receives an SQL query from its HTML document,// connects to the cars database, performs the query on the// database, and returns an HTML table of the results of the// query
import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.sql.*;
@WebServlet(name = "e13_3", urlPatterns = {"/e13_3"})public class e13_3 extends HttpServlet { private Connection myCon; private Statement myStmt; private PrintWriter out; // The processRequest method - does it all for this project protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ResultSet result; String command, colName, dat, junk; int numCols, index; ResultSetMetaData resultMd;
// Set the MIME type and get a writer
74©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
response.setContentType("text/html;charset=UTF-8"); out = response.getWriter(); // Create the document head and body opening out.println("<html>"); out.println("<head><title>JDBCServlet</title></head>"); out.println("<body>"); // Create the connection to the cars db try { myCon = DriverManager.getConnection ( "jdbc:mysql://localhost/cars", "root", ""); } catch (SQLException e) { out.println("getConnection failed"); } // Create the statement for SQL queries try { myStmt = myCon.createStatement(); } catch (Exception e) { out.println("createStatement failed"); } // Get the SQL request command command = request.getParameter("command"); command = command.trim(); out.print("<p><b>The command is: </b>" + command + "</p>");
// If the command is a query, use executeQuery on it if (command.substring(0, 6).equalsIgnoreCase("SELECT")) {
// Perform the query 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"); 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()) {
75©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
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) { out.println("executeQuery failed <br />"); } //** end of catch } //** end of the then clause of //** if(command.substring(0, 6).equalsIgnoreCase else { //** it was not a query try { myStmt.executeUpdate(command); } catch (Exception e) { out.println("executeUpdate failed <br />"); } } out.println("</body></html>"); } //** end of processRequest method @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); }}
Chapter 14
Exercise 14.1
# e141.rb - A solution to Exercise 14.1# Get inputputs "Please type the three input numbers"a = gets.to_ib = gets.to_i
76©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
c = gets.to_i
# Compute resultresult = 10 * a * b - ((c - 1) / 17.44)
# Display the resultputs "The result is: #{result}"
Exercise 14.3
# e143.rb - A solution to Exercise 14.3# Get inputputs "Please type the three names, on separate lines"name1 = getsname2 = getsname3 = gets
# Pass one - compare/interchange both pairsif name2 < name1 temp = name1 name1 = name2 name2 = tempend
if name3 < name2 temp = name2 name2 = name3 name3 = tempend
# Pass two - compare/interchange the first twoif name2 < name1 temp = name1 name1 = name2 name2 = tempend
# Display resultsputs "The names in order are: \n #{name1} #{name2} #{name3}"
Exercise 14.5
# e145.rb - A solution to Exercise 14.5# Create the two arrayspos_list = Array.newneg_list = Array.new
# Loop to read input and build the two new arrayswhile next_one = gets next_one = next_one.to_i
# If the number is positive, put it in the positive array if next_one > 0 pos_list.push(next_one)
77©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
elsif next_one < 0 neg_list.push(next_one) endend
# Display resulting arraysputs "The positive array is:"for value in pos_list puts valueend
puts "The negative array is:"for value in neg_list puts valueend
Chapter 15
Exercise 15.5
class AdderController < ApplicationController def the_form end
# result method - fetch data and compute the sum def result
# Fetch the form values @first = params[:first].to_i @second = params[:second].to_i
# Compute the sum @sum = @first + @second end
end
<!DOCTYPE html><!-- the_form.html.erb - the initial template for e155 --><html lang = "en"> <head> <title> The initial template for Exercise 15.5 </title> <meta charset = "utf-8" /> </head> <body> <h2> Please input two integers </h2> <form action = result method = "post"> <label> <input type = "text" name = "first" size = "5" /> First number </label> <br />
78©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<label> <input type = "text" name = "second" size = "5" /> Second number </label> <br /> <br /> <input type = "submit" value = "Submit data" /> <br /> <input type = "reset" value = "Clear form" /> </form> </body></html>
<!DOCTYPE html><!-- result.html.erb - the template for the result of e155 --><html lang = "en"> <head> <title> The result template for Exercise 15.5 </title> <meta charset = "utf-8" /> </head> <body> <p> The sum of your input is: <%= @sum %> </p> </body></html>
Exercise 15.6
# main_controller.rb - for the fbplayers application# Exercise 15.6class MainController < ApplicationController
# welcome method - the initial view def welcome end
# result method - fetches values for the result view def result @age1 = params[:age1] @age2 = params[:age2] @team = params[:team] @selected_players = Player.where( ["age >= ? and age <= ? and team = ?", @age1, @age2, @team]).all endend
<!-- welcome.html.erb - initial view for the fbplayers application (Exercise 15.6)
-->
<!-- The form to collect input from the user about their interests --> <form action = "result" method = "post" > <span class = "labels"> From age: </span>
79©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.
<input type = "text" size = "4" name = "age1" /> <span class = "labels"> To age: </span>
<input type = "text" size = "4" name = "age2" /> <span class = "labels"> Team: </span>
<input type = "text" size = "12" name = "team" /> <br />
<input type = "submit" value = "Submit request" /> <br /> <input type = "reset" value = "Reset form" /> <br /> </form>
<!-- result.html.erb - the result of the user request for information about players (Exercise 15.6) --> <p>
<!-- Display what the user asked for --> Players aged from <%= @age1 %> to <%= @age2 %> with the <%= @team %> team </p>
<!-- Display the results of the request in a table --> <table> <tr> <th> Player </th> <th> Age </th> </tr>
<!-- Put the cars in @selected_players in the table --> <% @selected_players.each do |player| %> <tr> <td> <%= player.name %> </td> <td> <%= player.age %> </td> </tr> <% end %> <!-- end of do loop --> </table>
80©2013 Pearson Education, Inc. Upper Saddle River, NJ. All Rights Reserved.