SEBESTA WWW Source Code Listings Chapter 2: Pg 35-36 Our first document

Greetings from your Webmaster!

Greetings from your Webmaster!

pg 39-40 Headings

Aidan's Airplanes (h1)

The best in used airplanes (h2)

"We've got them by the hangarful" (h3)

We're the guys to see for a good used airplane (h4)

We offer great prices on great planes (h5)
No returns, no guarantees, no refunds, all sales are final! (h6)
pg 41 Blockquotes

Abraham Lincoln is generally regarded as one of the greatest presidents of the U.S. His most famous speech was delivered in Gettysburg, Pennsylvania, during the Civil War. This speech began with

"Fourscore and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.

Now we are engaged in a great civil war, testing whether that nation or any nation so conceived and so dedicated, can long endure."

Whatever one's opinion of Lincoln, no one can deny the enormous and lasting effect he had on the U.S.

pg 47-48 Images

Aidan's Airplanes

The best in used airplanes

"We've got them by the hangarful"

Special of the month

1960 Cessna 210
577 hours since major engine overhaul
1022 hours since prop overhaul

Picture of a Cessna 210
Buy this fine airplane today at a remarkably low price
Call 999-555-1111 today!

pg 50 A link

Aidan's Airplanes

The best in used airplanes

"We've got them by the hangarful"

Special of the month

1960 Cessna 210
Information on the Cessna 210

pg 53 Unordered list

Some Common Single-Engine Aircraft

pg 54 Ordered list

Cessna 210 Engine Starting Instructions

  1. Set mixture to rich
  2. Set propeller to high RPM
  3. Set ignition switch to "BOTH"
  4. Set auxiliary fuel pump switch to "LOW PRIME"
  5. When fuel pressure reaches 2 to 2.5 PSI, push starter button
pg 55-56 Nested lists

Aircraft Types

  1. General Aviation (piston-driven engines)
    1. Single-Engine Aircraft
      1. Tail wheel
      2. Tricycle

    2. Dual-Engine Aircraft
      1. Wing-mounted engines
      2. Push-pull fuselage-mounted engines

  2. Commercial Aviation (jet engines)
    1. Dual-Engine
      1. Wing-mounted engines
      2. Fuselage-mounted engines

    2. Tri-Engine
      1. Third engine in vertical stabilizer
      2. Third engine in fuselage
pg 57 Definition lists

Single-Engine Cessna Airplanes

152
Two-place trainer
172
Smaller four-place airplane
182
Larger four-place airplane
210
Six-place airplane - high performance
pg 59-60 A simple table
Fruit Juice Drinks
Apple Orange Screwdriver
Breakfast 0 1 0
Lunch 1 0 0
Dinner 0 0 1
pg 61-62 Rowspan and colspan
Fruit Juice Drinks and Meals
Fruit Juice Drinks
Apple Orange Screwdriver
Breakfast 0 1 0
Lunch 1 0 0
Dinner 0 0 1
pg 63-64 Alignment in cells
The align and valign attributes
Column Label Another One Still Another One
align Left Center Right

valign

Default Top Bottom
pg 65 Cell spacing and cell padding Table 1 (space = 10, pad = 30)

Small spacing, large padding




Table 2 (space = 30, pad = 10)

Large spacing, small padding
pg 69 Checkboxes

Grocery Checklist

Milk Bread Eggs

pg 70-71 Radio

Age Category

0-19 20-35 36-50 Over 50

pg 72 Menu

Grocery Menu - milk, bread, eggs, cheese

With size = 1 (the default)

pg 74 Textarea

Please provide your employment aspirations

pg 75-78 Popcorn Sales Form

Welcome to Millennium Gymnastics Booster Club Popcorn Sales

Buyer's Name:
Street Address:
City, State, Zip:

Product Name Price Quantity
Unpopped Popcorn (1 lb.) $3.00
Caramel Popcorn (2 lb. canister) $3.50
Caramel Nut Popcorn (2 lb. canister) $4.50
Toffey Nut Popcorn (2 lb. canister) $5.00

Payment Method:

Visa Master Card Discover Check

pg 81 Frames pg 82 Table of Contents Frame

Fruits

pg 83 General Information on Fruits

A fruit is the mature ovary in a flowering plant. Fruit is clasified by several characteristics, the most important being the number of ovaries included. If only a single ovary is included, it is called a simple fruit.

pg 84 Nested frames Chapter 3 Pg 100 Checkboxes

Your name:

pg 104-105 Font properties

If a job is worth doing, it's worth doing right.

Two wrongs don't make a right, but they certainly can get you in a lot of trouble.

Chapter 1 Introduction

1.1 The Basics of Computer Networks

pg 105-106 External style sheets

If a job is worth doing, it's worth doing right.

Two wrongs don't make a right, but they certainly can get you in a lot of trouble.

Chapter 1 Introduction

1.1 The Basics of Computer Networks

pg 106-107 /* styles.css - an external style sheet for use with fonts2.html */ p.big {font-size: 14pt; font-style: italic; font-family: 'Times New Roman'; } p.small {font: 10pt bold 'Courier New';} h2 {font-family: 'Times New Roman'; font-size: 24pt; font-weight: bold} h3 {font-family: 'Courier New'; font-size: 18pt} possible text decoration values --> Text decoration

This illustrates line-through

This illustrates overline

This illustrates underline

pg 110-111 Sequence types

Aircraft Types

  1. General Aviation (piston-driven engines)
    1. Single-Engine Aircraft
      1. Tail wheel
      2. Tricycle
    2. Dual-Engine Aircraft
      1. Wing-mounted engines
      2. Push-pull fuselage-mounted engines
  2. Commercial Aviation (jet engines)
    1. Dual-Engine
      1. Wing-mounted engines
      2. Fuselage-mounted engines
    2. Tri-Engine
      1. Third engine in vertical stabilizer
      2. Third engine in fuselage
pg 114-115 The float property

This is a picture of a Cessna 210. 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.

pg 117-118 Table borders
Fruit Juice Drinks
Apple Orange Screwdriver
Breakfast 0 0
Lunch 1 0 0
Dinner 0 0 1

Now is the time for all good Web programmers to learn to use style sheets.

pg 119-120 Table borders

Here is the first line.

Now is the time for all good Web programmers to learn to use style sheets.
[margin = 0.2in, padding = 0.2in]

Now is the time for all good Web programmers to learn to use style sheets.
[margin = 0.1in, padding = 0.3in]

Now is the time for all good Web programmers to learn to use style sheets.
[margin = 0.3in, padding = 0.1in]

Now is the time for all good Web programmers to learn to use style sheets.
[margin = 0.4in, no padding, no border]

Now is the time for all good Web programmers to learn to use style sheets.
[padding = 0.4in, no margin, no border]

Here is the last line.

pg 121-122 Background images

The Cessna 172 is the most common general aviation airplane in the world. It is an all-metal, single-engine piston, high-wing four-place monoplane. It has fixed-gear and is categorized as a non-high-performance aircraft. The current model is the 172R. The wingspan of the 172R is 36'1". Its fuel capacity is 56 gallons in two tanks, one in each wing. The takeoff weight is 2,450 pounds. Its maximum useful load is 837 pounds. The maximum speed of the 172R at sea level is 142 mph. The plane is powered by a 360 cubic inch gasoline engine that develops 160 horsepower. The climb rate of the 172R at sea level is 720 feet per minute.

Chapter 4 Pg 149 Real roots of a quadratic equation pg 153-154 A switch statement pg 155-157 Illustrates Date pg 161-162 Name list pg 164-165 Array of arrays pg 167-168 Parameters pg 171-172 Median Computation pg 179-180 Phone number tester pg 181-182 Debugging help Chapter 5 Pg 199-200 onLoad event handler

pg 202-203 Illustrate messages for radio buttons

Cessna single-engine airplane descriptions

Model 152
Model 172 (Skyhawk)
Model 182 (Skylane)
Model 210 (Centurian)

pg 204-206 Illustrate messages for radio buttons

Cessna single-engine airplane descriptions

Model 152
Model 172 (Skyhawk)
Model 182 (Skylane)
Model 210 (Centurian)

pg 207-209 The focus event

Coffee Order Form

Product Name Price Quantity
French Vanilla (1 lb.) $3.49
Hazlenut Cream (1 lb.) $3.95
Columbian (1 lb.) $4.59

pg 210-211

Password Input

Your password

Verify password

pg 213-215 Illustrate form input validation>

Customer Information

Name (last name, first name, middle initial)

Phone number (ddd-ddd-dddd)

pg 219-221 Illustrate form input validation with DOM 2>

Customer Information

Name (last name, first name, middle initial)

Phone number (ddd-ddd-dddd)

pg 222 Using navigator

Chapter 6 Pg 231-232 Absolute positioning

Apple is the common name for any tree of the genus Malus, of the family Rosaceae. Apple trees grow in any of the temperate areas of the world. Some apple blossoms are white, but most have stripes or tints of rose. Some apple blossoms are bright red. Apples have a firm and fleshy structure that grows from the blossom. The colors of apples range from green to very dark red. The wood of apple trees is fine-grained and hard. It is, therefore, good for furniture construction. Apple trees have been grown for many centuries. They are propagated by grafting because they do not reproduce themselves.

APPLES ARE GOOD FOR YOU

pg 233-234 Nested absolute positioning
Apple is the common name for any tree of the genus Malus, of the family Rosaceae. Apple trees grow in any of the temperate areas of the world. Some apple blossoms are white, but most have stripes or tints of rose. Some apple blossoms are bright red. Apples have a firm and fleshy structure that grows from the blossom. The colors of apples range from green to very dark red. The wood of apple trees is fine-grained and hard. It is, therefore, good for furniture construction. Apple trees have been grown for many centuries. They are propagated by grafting because they do not reproduce themselves. APPLES ARE GOOD FOR YOU
pg 235 Relative positioning

Apples are GOOD for you.

pg 237-238 Moving elements

x coordinate:
y coordinate:

(Picture of a nebula)
pg 239-240 Visibility control
(Picture of Saturn)


pg 241-242 Dynamic colors

This small page illustrates dynamic setting of the foreground and background colors for a document

Background color:
Foreground color:

pg 243 Dynamic fonts for links

The state of Washington produces many of our nation's apples.

pg 244-246 Dynamic values

Customer information

Name:
Email:

To create an account, provide the following:

User ID:
Password:


pg 247-248 Dynamic stacking of images

(Picture of a C172) (Picture of a Citation airplane) (Picture of a C182)

pg 251-252 Where is the cursor?

Within the client area:
x: y:

Relative to the origin of the screen coordinate system:
x: y:

(Picture of C172)

pg 253-254 Sense events anywhere onmouseup = "hideIt();">

















pg 255-257 Moving text

Jump in the lake!

// This is moveTextfuns.js - used with moveText.html var dom, x, y, finalx = 300, finaly = 300; // ************************************************* // // A function to initialize the x and y coordinates // of the current position of the text to be moved, // and then call the mover function function initText() { dom = document.getElementById('theText').style; /* Get the current position of the text */ var x = dom.left; var y = dom.top; /* Convert the string values of left and top to numbers by stripping off the units */ x = x.match(/\d+/); y = y.match(/\d+/); /* Call the function that moves it */ moveText(x, y); } /*** end of function initText */ // ************************************************* // // A function to move the text from its original // position to (finalx, finaly) function moveText(x, y) { /* If the x coordinates are not equal, move x toward finalx */ if (x != finalx) if (x > finalx) x--; else if (x < finalx) x++; /* If the y coordinates are not equal, move y toward finaly */ if (y != finaly) if (y > finaly) y--; else if (y < finaly) y++; /* As long as the text is not at the destination, call the mover with the current position */ if ((x != finalx) || (y != finaly)) { /* Put the units back on the coordinates before assigning them to the properties to cause the move */ dom.left = x + "px"; dom.top = y + "px"; /* Recursive call, after a 1-millisecond delay */ setTimeout("moveText(" + x + "," + y + ")", 1); } } /*** end of function moveText */ pg 258-262 Drag and drop

Roses are red
Violets are blue
candy cats cows glue is is meow mine moo new old say say so sticky sweet syrup too background-color: lightgrey;" onmousedown = "grabber(event);"> yours

Chapter 7 Pg 271 /* Wel.java An applet to illustrate the display of a string */ import java.applet.*; import javax.swing.*; import java.awt.*; // The Wel applet public class Wel extends JApplet { // Create a content pane and the panel Container messageArea = getContentPane(); MessagePanel myMessagePanel = new MessagePanel(); // The init method, which adds the panel to the applet public void init() { messageArea.add(myMessagePanel); } } // The panel class on which the message is painted class MessagePanel extends JPanel { public void paintComponent(Graphics grafObj) { super.paintComponent(grafObj); grafObj.drawString("Welcome to my home page!", 50, 50); } } pg 273 An applet to illustrate the display of a string in a specific font, font style, and font size */ import java.applet.*; import javax.swing.*; import java.awt.*; // The panel class on which the message will be painted class MessagePanel extends JPanel { Font myFont = new Font("TimesRoman", Font.ITALIC, 24); public void paintComponent(Graphics grafObj) { super.paintComponent(grafObj); grafObj.setFont(myFont); grafObj.drawString("Welcome to my first home page!", 50, 50); } } // The Wel2 applet public class Wel2 extends JApplet { // The init method - create the content pane, instantiate // the message panel and add it to the content pane public void init() { Container messageArea = getContentPane(); MessagePanel myMessagePanel = new MessagePanel(); messageArea.add(myMessagePanel); } } pg 274 Wel2

pg 276-277 /* Wel3.java An applet to illustrate parameters */ import java.applet.*; import javax.swing.*; import java.awt.*; // The panel class on which the message will be painted class MessagePanel2 extends JPanel { Font myFont = new Font("TimesRoman", Font.ITALIC, Wel3.mySize); public void paintComponent(Graphics grafObj) { super.paintComponent(grafObj); grafObj.setFont(myFont); grafObj.drawString("Welcome to my home page!", 50, 50); } } // The Wel3 applet public class Wel3 extends JApplet { static int mySize; public void init() { Container messageArea = getContentPane(); String pString; // Get the fontsize parameter pString = getParameter("size"); // If it's null, set the size to 30; otherwise, use the // parameter value if (pString == null) mySize = 30; else mySize = Integer.parseInt(pString); // Instantiate the panel with the message and add it to // the content pane MessagePanel2 myMessagePanel = new MessagePanel2(); messageArea.add(myMessagePanel); } } pg 277-278 Wel3

pg 279 /* Rectangles.java An applet to illustrate drawing rectangles */ import java.applet.*; import java.awt.*; import javax.swing.*; // The panel class for drawing class MyPanel extends JPanel { public void paintComponent(Graphics grafObj) { super.paintComponent(grafObj); grafObj.drawRect(10, 10, 80, 60); grafObj.fillRect(120, 10, 60, 80); grafObj.drawRoundRect(10, 120, 80, 60, 20, 30); grafObj.fillRoundRect(120, 120, 60, 80, 40, 40); } } // The Rectangles applet public class Rectangles extends JApplet { Container rectangleArea = getContentPane(); MyPanel newPanel = new MyPanel(); // The init method for the applet - adds the panel to // the content area of the applet public void init() { rectangleArea.add(newPanel); } } pg 281 /* Polygons.java An applet to illustrate drawing a polygon */ import java.applet.*; import java.awt.*; import javax.swing.*; // The panel for drawing class PolyPanel extends JPanel { public void paintComponent(Graphics grafObj) { int xCoordinates [] = {30, 50, 64, 64, 50, 30, 16, 16, 30}; int yCoordinates [] = {10, 10, 24, 44, 58, 58, 44, 24, 10}; super.paintComponent(grafObj); grafObj.drawPolygon(xCoordinates, yCoordinates, 9); } } // The Polygons applet public class Polygons extends JApplet { Container polyArea = getContentPane(); PolyPanel newPanel = new PolyPanel(); // The init method, which adds the panel to the applet public void init() { polyArea.add(newPanel); } } pg 285-287 /* Pizza.java An applet to illustrate some GUI components with a pizza order form */ import java.awt.*; import java.applet.*; import javax.swing.*; public class Pizza extends JApplet { Container contentPane = getContentPane(); public void init() { // Create a panel object and set its layout manager to put // the components in a column JPanel myPanel = new JPanel(); myPanel.setLayout(new GridLayout(20, 1, 10, 10)); myPanel.setBackground(Color.cyan); // Create a label for the form heading and add it to the panel Label myLabel = new Label("Pizza Order Form"); myPanel.add(myLabel); // Create a text field for the customer's name and // address and add them to the panel JLabel nameLabel = new JLabel("Name:"); JTextField myName = new JTextField(30); JLabel addrLabel = new JLabel("Address:"); JTextField myAddr = new JTextField(30); myPanel.add(nameLabel); myPanel.add(myName); myPanel.add(addrLabel); myPanel.add(myAddr); // Create radio buttons for pizza size and add them to the panel JLabel sizeLabel = new JLabel("Pizza Size"); ButtonGroup sizeGroup = new ButtonGroup(); JRadioButton s1 = new JRadioButton("small"); JRadioButton s2 = new JRadioButton("medium"); JRadioButton s3 = new JRadioButton("large", true); // Put the radio buttons in the button group sizeGroup.add(s1); sizeGroup.add(s2); sizeGroup.add(s3); // Put the radio buttons in the panel myPanel.add(sizeLabel); myPanel.add(s1); myPanel.add(s2); myPanel.add(s3); // Create checkboxes for toppings and add them to the panel Checkbox top1 = new Checkbox("sausage"); Checkbox top2 = new Checkbox("pepperoni"); Checkbox top3 = new Checkbox("extra cheese"); Checkbox top4 = new Checkbox("hamburger"); Checkbox top5 = new Checkbox("olives"); Checkbox top6 = new Checkbox("mushrooms"); myPanel.add(topLabel); myPanel.add(top1); myPanel.add(top2); myPanel.add(top3); myPanel.add(top4); myPanel.add(top5); myPanel.add(top6); // Now add the panel to the content pane contentPane.add(myPanel); } // End of init() } // End of the Pizza applet pg 290-292 /* RadioB.java An applet to illustrate event handling with interactive radio buttons that control the font style of a text field */ import java.awt.*; import java.awt.event.*; import java.applet.*; import javax.swing.*; public class RadioB extends JApplet implements ItemListener { // Make most of the variables class variables, because both init // and the event handler must see them private Container contentPane = getContentPane(); private JTextField text; private Font plainFont, boldFont, italicFont, boldItalicFont; private JRadioButton plain, bold, italic, boldItalic; private ButtonGroup radioButtons = new ButtonGroup(); private JPanel myPanel = new JPanel(); // The init method is where the document is initially built // Set the background color of the panel myPanel.setBackground(Color.cyan); // Create the fonts plainFont = new Font("Serif", Font.PLAIN, 16); boldFont = new Font("Serif", Font.BOLD, 16); italicFont = new Font("Serif", Font.ITALIC, 16); boldItalicFont = new Font("Serif", Font.BOLD + Font.ITALIC, 16); // Create the test text string, set its font, and add it to the // panel text = new JTextField("In what font style should I appear?", 30); myPanel.add(text); text.setFont(plainFont); // Create radio buttons for the fonts and add them to the panel plain = new JRadioButton("Plain", true); bold = new JRadioButton("Bold"); italic = new JRadioButton("Italic"); boldItalic = new JRadioButton("Bold Italic"); radioButtons.add(plain); radioButtons.add(bold); radioButtons.add(italic); radioButtons.add(boldItalic); // Register the event handlers to myPanel plain.addItemListener(this); bold.addItemListener(this); italic.addItemListener(this); boldItalic.addItemListener(this); // Now add the buttons to the panel myPanel.add(plain); myPanel.add(bold); myPanel.add(italic); myPanel.add(boldItalic); // Now add the panel to the content pane for the applet contentPane.add(myPanel); } // End of init() // The event handler public void itemStateChanged (ItemEvent e) { // Determine which button is on and set the font accordingly if (plain.isSelected()) text.setFont(plainFont); else if (bold.isSelected()) text.setFont(boldFont); else if (italic.isSelected()) text.setFont(italicFont); else if (boldItalic.isSelected()) text.setFont(boldItalicFont); } // End of itemStateChanged } // End of RadioB applet Chapter 8 Pg 309 pg 310-311 1977 &c; Skyhawk Light blue and white New paint, nearly new interior, 685 hours SMOH, full IFR King avionics 23,495 Skyway Aircraft Rapid City, South Dakota 1965 &p; Cherokee Gold 240 hours SMOH, dual NAVCOMs, DME, new Cleveland brakes, great shape John Seller St. Joseph, Missouri pg. 319-320 pg 320 Cessna Piper Beechcraft pg 325 ad { display: block; margin-top: 15px; color: blue;} year, make, model { color: red; font-size: 16pt;} color {display: block; margin-left: 20px; font-size: 12pt;} description {display: block; margin-left: 20px; font-size: 12pt;} seller { display: block; margin-left: 15px; font-size: 14pt;} location {display: block; margin-left: 40px; } city {font-size: 12pt;} state {font-size: 12pt;} pg 328 1977 Cessna Skyhawk Light blue and white pg 331-332 Style sheet for xslplane.xml

Airplane Description

Year:
Make:
Model:
Color:
pg 332-333 Style sheet for xslplane.xml

Airplane Description

Year:
Make:
Model:
Color:
pg 333-334 1977 Cessna Skyhawk Light blue and white 1975 Piper Apache White 1960 Cessna Centurian Yellow and white 1956 Piper Tripacer Blue pg 334

Airplane Descriptions

Year:
Make:
Model:
Color:

Chapter 9 Pg 353 # quadeval.pl – A simple Perl program # Input: Four numbers, representing the values of # a, b, c, and x # Output: The value of the expression # axx + bx + c # Get input print "Please input the value of a "; $a = ; print "Please input the value of b "; $b = ; print "Please input the value of c "; $c = ; print "Please input the value of x "; $x = ; # Compute and display the result $result = $a * $x * $x + $b * $x + $c; print "The value of the expression is: $result \n"; pg 364 # process_names.pl - A simple program to illustrate # the use of arrays # Input: A file, specified on the command line, of # lines of text, where each line is a person’s # name # Output: The input names, after all letters are converted # to uppercase, in alphabetical order $index = 0; # Loop to read the names and process them while($name = <>) { # Convert the name’s letters to uppercase and put it in # the names array $names[$index++] = uc($name); } # Display the sorted list of names print "\nThe sorted list of names is:\n\n\n"; foreach $name (sort @names) { print ("$name \n"); } pg 371-372 # tst_median.pl - a program to test a function that # computes the median of a given array # median - a function # Parameters: # A reference to an array of numbers # Return value: # The median of the array, where median is the # middle element of the sorted array, if the # length is odd; if the length is even, the median # is the average of the two middle elements of the # sorted array sub median { my $ref_list = $_[0]; # Compute the length of the passed array my $len = $#$ref_list + 1; # Sort the parameter array @list = sort {$a <=> $b} @$ref_list; # Compute the median if ($len % 2 == 1) { # length is odd return $list[$len / 2]; } else { # length is even return ($list[$len / 2] + $list[$len / 2 - 1]) / 2; } } # End of function median # Begin main program # Create two test arrays, one with odd length and one with # even length @list1 = (11, 36, 5, 20, 41, 6, 8, 0, 9); @list2 = (43, 77, 11, 29, 8, 51, 9, 18); # Call median on both arrays and display the results $med = median(\@list1); print "The median of the first array is: $med \n"; $med = median(\@list2); print "The median of the second array is: $med \n"; pg 375-376 # word_table.pl # Input: A file of text in which all words are separated by white- # space or punctuation, possibly followed by whitespace, # where the punctuation can be a comma, a semicolon, a # question mark an exclamation point, a period, or a colon. # The input file is specified on the command line # Output: A list of all unique words in the input file, # in alphabetical order # # # Main loop to get and process lines of input text while (<>) { # Split the line into words @line_words = split /[ .,;:!?]\s*/; # Loop to count the words (either increment or initialize to 1) foreach $word (@line_words) { if (exists $freq{$word}) { $freq{$word}++; } else { $freq{$word} = 1; } } } # Display the words and their frequencies print "\n Word \t\t Frequency \n\n"; foreach $word (sort keys %freq) { print " $word \t\t $freq{$word} \n"; } pg 380-382 # wages.pl - An example program to illustrate some of the # features of Perl # Input: A file of lines of employee data, where each line has # name:age:department code:salary # Output: 1. The names of all employees whose names end with "son" # 2. Percentage of employees under 40 years old # 3. Average salary of employees under 40 years old # 4. An alphabetical list of employees who are under 40 # years old and who have salaries more than $40,000 # Open the data file and display a header for employees # whose names end in 'son’ open(EMPLOYEES, "employees.txt") || die "Can’t open employees $!"; print "Names that end in 'son'\n\n"; # Loop to read and process the employee data while () { # Increment the number of employees and chop off the newline $total_employees++; chomp; # Split the input line into its four parts ($name, $age, $dept, $salary) = split(/:/); # If the name ends in 'son’, print the name if ($name =~ /son$/) { print "$name \n"; } # If the employee is under 40, count him or her and add his or her # salary to the sum of such salaries if ($age < 40) { $under_40++; $salary_sum += $salary; # If the salary was over 40,000, add the person and his or her # salary to the hash of such people if ($salary > 40000) { $sublist{$name} = $salary; } } } # If there was at least one employee, continue if ($total_employees > 0) { # If there was at least one under 40, continue if ($under_40 > 0) { # Compute and display the % of employees under 40 and their # average salaries $percent = 100 * $under_40 / $total_employees; print "\nPercent of employees under 40 is: $percent \n"; $avg = $salary_sum / $under_40; print "Average salary of employees under 40 is: $avg \n"; # If there was at least one under 40 who earned a salary > 40,000, # continue if (keys(%sublist)) { # Sort and display the names of the employees under 40 with # with salaries > 40,000 print "Sorted list of employees under 40", " with salaries > \$40,000 \n"; @sorted_names = sort (keys(%sublist)); print "\nName \t\t Salary\n"; foreach $name (@sorted_names) { print "$name \t \$$sublist{$name} \n"; } } else { print "There were no employees under 40 who earned"; print "over $40,000 \n"; } #** of if (keys(%sublist)) } else { print "There were no employees under 40 \n"; } #** of if ($under_40 > 0) } else { print "There were no employees\n"; } #** of if ($total_employees > 0) Chapter 10 Pg 393 XHTML to call the Perl CGI program, reply.cgi

This is our first Perl CGI example

Click here to run the CGI program, reply.cgi

pg 394 #!/usr/local/bin/perl -w # reply.cgi # This CGI program returns a greeting to the client print "Content-type: text/html \n\n", " \n", "\n", "\n", " reply.cgi example \n", "\n", "

Greetings from your Web server!

\n", ""; pg 401-403 Popcorn Sales Form

Welcome to Millenium Gynmastics Booster Club Popcorn Sales

Buyer's Name:
Street Address:
City, State, Zip:

Product Name Price Quantity
Unpopped Popcorn (1 lb.) $3.00
Caramel Popcorn (2 lb. cannister) $3.50
Caramel Nut Popcorn (2 lb. cannister) $4.50
Toffey Nut Popcorn (2 lb. cannister) $5.00

Payment Method:

Visa
Master Card
Discover
Check

pg 405-406 #!/usr/local/bin/perl # popcorn.cgi # A CGI program to process the popcorn sales form use CGI ":standard"; # Initialize total price and total number of purchased items $total_price = 0; $total_itemi = 0; # Produce the header part of the HTML return value print header; print start_html("CGI-Perl Popcorn Sales Form, using CGI.pm"); # Set local variables to the parameter values my($name, $street, $city, $payment) = (param("name"), param("street"), param("city"), param("payment")); my($unpop, $caramel, $caramelnut, $toffeynut) = (param("unpop"), param("caramel"), param("caramelnut"), param("toffeynut")); # Compute the number of items ordered and the total cost $total_price = 3.0 * $unpop + 3.5 * $caramel + 4.5 * $caramelnut + 5.0 * $toffeynut; $total_items = $unpop + $caramel + $caramelnut + $toffeynut; # Produce the result information for the browser and # finish the page print h3("Customer:"), "\n"; print "$name
\n", "$street
\n", "$city

\n"; print "Payment method: $payment

\n"; print h3("Items ordered:"), "\n"; if ($unpop > 0) {print "Unpopped popcorn: $unpop
\n";} if ($caramel > 0) {print "Caramel popcorn: $caramel
\n";} if ($caramelnut > 0) {print "Caramel nut popcorn: $caramelnut
\n";} if ($toffeynut > 0) {print "Toffey nut popcorn: $toffeynut
\n";} print "Thank you for your order

\n"; print "Your total bill is: \$ $total_price
\n"; print end_html; pg 408-409 Consumer Electronics Purchasing Survey

Welcome to the Consumer Electronics Purchasing Survey

Your Age Category:

10-25
26-40
41-60
Over 60

Your Gender:

Female
Male

Your Next Consumer Electronics Purchase will be:

Conventional TV
HDTV
VCR
CD player
Mini CD player/recorder
DVD player
Other


To see the results of the survey so far, click here

pg 411-413 #!/usr/local/bin/perl # conelec1.cgi # This CGI program processes the consumer electronics survey form # and updates the file that stores the survey data, survdat.dat use CGI ":standard"; use Fcntl qw(:DEFAULT :flock); # error - a function to produce an error message for the client # and exit in case of input/output errors sub error { print start_html(); print "Error - input/output error in conelec1.pl
"; print end_html(); exit(1); } # Begin the main program # Get the form values my($age, $gender, $vote) = (param("age"), param("gender"), # Produce the header for the reply page - do it here so error # messages appear on the page print header; # Set $index to the line index of the current vote $index = $age + $gender; # Open and lock the survey data file open(SURVDAT, "+); } # Split the line into its parts, increment the chosen device, and # put it back together again @file_votes = split / /, $file_lines[$index]; $file_votes[$vote]++; $file_lines[$index] = join(" ", @file_votes); # Rewind the file for writing seek(SURVDAT, 0, 0) or error(); # Write out the file data and close it (which also unlocks it) foreach $line (@file_lines) { print SURVDAT "$line\n"; } close(SURVDAT); # Build the web page to thank the survey participant print start_html("Thankyou"); print "Thank you for participating in our survey

\n"; print end_html; pg 416-418 #!/usr/local/bin/perl -w # conelec2.cgi - display the survey results # make_rows - a subprogram to make the rows of an output table sub make_rows { my $index = $_[0]; # Split the input lines for females into age arrays @age1 = split(/ /, $vote_data[$index]); @age2 = split(/ /, $vote_data[$index + 1]); @age3 = split(/ /, $vote_data[$index + 2]); @age4 = split(/ /, $vote_data[$index + 3]); # Add the row titles to the age arrays unshift(@age1, "10-25"); unshift(@age2, "26-40"); unshift(@age3, "41-60"); unshift(@age4, "Over 60"); # Create the column titles in HTML by giving their address to the th # function and storing the return value in the @rows array @rows = th(\@col_titles); # Now create the data rows with the td function # and add them to the row addresses array push(@rows, td(\@age1), td(\@age2), td(\@age3), td(\@age4)); } ##** end of the make_rows subprogram # error - a function to produce an error message for the client # and exit in case of open errors sub error { print start_html; print "Error - input/output error in conelec2.pl
"; print end_html; exit(1); } ##** end of the error subprogram use CGI qw(:standard); # Make the column titles array @col_titles = ("Age Group", "Conventional TV", "HDTV", "VCR", "CD player", "MiniCD player/recorder", "DIVD player", "Other"); print header; # Open and read the survey data file open(SURVDAT, "; # Create the beginning of the result Web page print start_html(“Survey Results”); print h2("Results of the Consumer Electronics Purchasing Survey"); print "
"; # Create the rows of the female survey results table make_rows(0); # Create the table for the female survey results # The address of the array of row addresses is passed to Tr print table({-border => "border"}, caption(h3(“Survey Data for Females”)), Tr(\@rows) ); # Create the rows for the male results table make_rows(4); # Create the table for the male survey results # The address of the array of row addresses is passed to Tr print "

"; print table({-border => "border"}, caption(h3("Survey Data for Males")), Tr(\@rows) ); print end_html; pg 421 # time_date.pl # Input: None # Output: The nine values returned by localtime # ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) = localtime; print "\$sec = $sec\n"; print "\$min = $min\n"; print "\$hour = $hour\n"; print "\$mday = $mday\n"; print "\$mon = $mon\n"; print "\$year = $year\n"; print "\$wday = $wday\n"; print "\$yday = $yday\n"; print "\$isdst = $isdst\n"; pg 422-423 #!/usr/bin/perl # day_cookie.pl # - A CGI-Perl program to use a cookie to remember the # day of the last login from a user and display it when run use CGI ":standard"; # Get the existing day cookie, if there was one @last_day = cookie('last_time'); # Get the current date and make the new cookie $day_of_week = (qw(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)) [(localtime)[6]]; $month = (qw(January February March April May June July August September October November December)) [(localtime)[4]]; $day_of_month = (localtime)[3]; @day_stuff = ($day_of_week, $day_of_month, $month); $day_cookie = cookie(-name => 'last_time', -value => \@day_stuff, -expires => '+5d'); # Produce the return document # First, put the cookie in the new header print header(-cookie => $day_cookie); print start_html('This is day_cookie.pl'); # If there was no day cookie, this is the first visit if (scalar(@last_day) == 0) { print "Welcome to you on your first visit to our site
"; } # Otherwise, welcome the user back and give the date of the # last visit else { ($day_of_week, $day_of_month, $month) = @last_day; print "Welcome back!
", "Your last visit was on ", "$day_of_week, $month $day_of_month
"; } print end_html; Chapter 11 Pg 433 Test greeting

Press the button to enact the servlet

pg 433-434 /* Greeting.java A servlet to illustrate a simple GET request */ import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Greeting extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter returnHTML; response.setContentType("text/html"); returnHTML = response.getWriter(); returnHTML.println(""); returnHTML.println("A simple GET servlet"); returnHTML.println(""); returnHTML.println( "

This is your servlet answering

"); returnHTML.println(""); returnHTML.close(); } } pg 435-436 Consumer Electronics Purchasing Survey

Welcome to the Consumer Electronics Purchasing Survey

Your Gender:

Female
Male


Your Next Consumer Electronics Purchase will be:

Conventional TV
HDTV
VCR
CD player
Mini CD player/recorder
DVD player
Other

pg 438-440 // Survey.java // This servlet processes the consumer electronics survey // form, updating the file that stores the survey data // and producing the current total votes in the survey. // The survey data file, survdat.dat, is stored on the Web server. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class Survey extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int votes[] = null; int index; int vote; File survdat = new File("survdat.dat"); String gender; String products[] = {"Conventional TV", "HDTV", "VCR", "CD Player", "Mini CD player/recorder", "DVD player", "Other"}; // Set the content type for the response output and get a writer response.setContentType( "text/html" ); PrintWriter servletOut = response.getWriter(); // Produce the head of the output document servletOut.println(""); servletOut.println( " Return message "); // 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[14]; } catch (Exception e) {e.printStackTrace();} // Get the gender of the survey respondee gender = request.getParameter("gender"); // Add the consumer electronics vote of the response to the // votes array vote = Integer.parseInt(request.getParameter("vote")); if (gender.equals("male")) vote += 7; 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 servletOut.println( "

Thank you for participating in the"); servletOut.println(" Consumer Electronics Survey

"); servletOut.println("

Current Survey Results:

"); // Create the total votes return information for female respondents servletOut.println("
For Female Respondents
"); for (index = 0; index < 7; index++) { servletOut.print(products[index]); servletOut.print(": "); servletOut.println(votes[index]); servletOut.println("
"); } // Create the total votes return information for male respondents servletOut.println("
For Male Respondents
"); for (index = 7; index < 14; index++) { servletOut.print(products[index - 7]); servletOut.print(": "); servletOut.println(votes[index]); servletOut.println("
"); } servletOut.close(); } } pg 443-444 Ballot

Please choose one candidate for dogcatcher

Daren Dogman
Timmy Taildragger
Don Dogpile

pg 445-449 // VoteCounter.java // This servlet processes the ballot form, returning a // page 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 page. // 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, votesdat.dat, is stored on the Web // server. import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class VoteCounter extends HttpServlet { Cookie cookies[] = null; int index; PrintWriter servletOut; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Cookie newCookie; int votes[] = null; String vote; File votesdat = new File("votesdat.dat"); String candidates[] = {"Daren Dogman", "Timmy Taildragger", "Don Dogpile"}; // Get cookies from the request cookies = request.getCookies(); // Check to see if there was a vote on the form vote = request.getParameter("vote"); if (vote == null) { // There was no vote // Create the return page makeHeader(response); servletOut.println( "You submitted a ballot with no vote marked
"); servletOut.println( "Please mark the ballot 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) // Syncronize block for file input/output synchronized(this) { if (votesdat.exists()) { ObjectInputStream indat = new ObjectInputStream( new FileInputStream(votesdat)); // 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[3]; // Add the new vote to the votes array if (vote.equals("Dogman")) votes[0]++; else if (vote.equals("Taildragger")) votes[1]++; else votes[2]++; else { // The client voted before // Write a response message makeHeader(response); servletOut.println( "Your vote is illegal - you have already voted!"); } // end of else clause - client voted before } // end of else (there was a vote) // Finish response document and close the stream servletOut.println(" "); servletOut.close(); } // end of