Transcript Chapter 1

7.1 JavaScript Execution Environment
- The JavaScript Window object represents the
window in which the browser displays documents
- The Window object provides the largest enclosing
referencing environment for scripts
- Its properties are visible to all scripts in the
document (they are the globals)
- Other Window properties:
- document - a reference to the Document object
that the window displays
- frames - an array of references to the frames of
the document
- forms - an array of references to the forms of the
document
- Each Form object has an elements array, which
has references to the form’s elements
- Form elements are usually referenced by
name, but this is a problem for radio buttons
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
1
7.2 The Document Object Model
- Under development by w3c since the mid-90s
- DOM 2 is the latest approved standard
- The DOM is an abstract model that defines the
interface between HTML documents and
application programs
- It is an OO model - document elements are objects
- A language that supports the DOM must have a
binding to the DOM constructs
- In the JavaScript binding, HTML elements are
represented as objects and element attributes are
represented as properties
e.g., <input type = "text" name = "address">
would be represented as an object with two
properties, type and name, with the values
"text" and "address"
- The property names in JavaScript are usually just
lowercase versions of the corresponding HTML
attribute names
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
2
7.3 Events and Event Handling
- In event-driven programming, code is executed as
a result of a user or browser action
- An event is a notification that something specific
has occurred, either with the browser or an action
of the browser user
- An event handler is a script that is implicitly
executed in response to the appearance of an event
- Because events are JavaScript objects, their names
are case sensitive - all are in lowercase only
- Event handlers can be specified in two ways:
1. An HTML tag can have an attribute that is
associated with a specific event and the handler
code, in the form of a string literal, is assigned
to the attribute
2. The handler can be implemented as a function
and the function’s name is assigned to the object
property associated with the event at the HTML
element
- Don’t use document.write in an event handler,
because the output may go on top of the display
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
3
7.4 Events, Attributes, and Tags
Event
Tag Attribute
abort
blur
change
click
error
focus
load
mouseout
mouseover
reset
resize
select
submit
unload
onAbort
onBlur
onChange
onClick
onError
onFocus
onLoad
onMouseOut
onMouseOver
onReset
onResize
onSelect
onSubmit
onUnload
- The same attribute can appear in several different
tags
e.g., The onClick attribute can be in <a> and
<input>
--> SHOW Tables 7.1 and 7.2
- Specifying a handler by assigning the attribute:
onClick = "alert('Mouse click!');"
onClick = "myHandler();"
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
4
7.5 Using the load and unload Events
- These events are triggered when the loading or
unloading of a document is completed
<!-- This is ch7_1.html -->
<html>
<head>
<title> onLoad and onUnload event handlers
</title>
<script language = "JavaScript">
// The onload event handler
function load_hello () {
alert("Your page has been loaded - hello!");
}
// The onunload event handler
function unload_goodbye () {
alert("Your page is now unloaded - goodbye!");
}
</script>
<head>
<body onLoad = "load_hello();"
onUnload = "unload_goodbye();">
</body>
</html>
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
5
7.6 Event Handlers for Button Events
- Radio buttons
<input type = "radio" name = "button_group"
value = "blue" onClick = "handler()">
- Can’t use the element’s name to identify it,
because all buttons in the group have the same
name
- Must use the DOM address of the element, e.g.,
var radioElement = document.myForm.elements;
- Now we have the name of the array of elements
of the form
for (var index = 0;
index < radioElement.length; index++) {
if (radioElement[index].checked) {
element = radioElement[index].value;
break;
}
}
- NOTE: There is no error checking in this code
- Now, we can use a switch on element, as in
switch(element) { ...
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
6
7.6 Event Handlers for Button Events
(continued)
--> SHOW ch7_2.html
- Event handlers can be specified by assigning them
to properties of the JavaScript objects associated
with the HTML elements
- The property names are lowercase versions of the
attribute names
- If the event handler is a function, just assign its
name to the property, as in
document.myForm.elements[0].onclick =
myHandler;
- This sets the handler for the first element in the
form
-This would need to follow both the handler
function and the HTML form
- If this is done for a radio button group, each
element of the elements array must be assigned
--> SHOW ch7_2x.html
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
7
7.6 Event Handlers for Button Events
(continued)
- Disadvantage of specifying handlers by assigning
them to event properties is that there is no way to
use parameters
- The advantage of specifying handlers by assigning
them to event properties are:
1. It is good to keep HTML and JavaScript separate
2. The handler could be changed during use
7.7 Checking Form Input
- A good use of JavaScript, because it finds errors
in form input before it is sent to the server for
processing
- Things that must be done:
1. Detect the error and produce an alert message
2. Put the element in focus (the focus function)
3. Select the element (the select function)
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
8
7.7 Checking Form Input (continued)
- The focus function puts the element in focus, which
puts the cursor in the element
document.myForm.phone.focus();
- The select function highlights the text in the
element
- To keep the form active after the event handler is
finished, have it return false
- Example – comparing passwords
- If a password will be used later, the user is asked
to type it in twice
- The program must verify that the second typing
of the password is the same as the first
- The form just has two password input boxes to
get the passwords and Reset and Submit buttons
- The event handler is triggered by the Submit
button
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
9
7. Checking Form Input (continued)
- Handler actions:
1. If no password has been typed in the first
box, focus on that box and return false
2. If the two passwords are not the same, focus
and select the first box and return false
if they are the same, return true
--> SHOW ch7_3.html & its output
- Another Example – Checking the format of a name
and phone number
- The event handler will be triggered by the change
event of the text boxes for the name and phone
number
- If an error is found in either, an alert message is
produced and both focus and select are called on
the text box element
- Another event handler is used to produce a
thank you alert message when the input is ok
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
10
7.8 The navigator object
- Indicates which browser is being used
- Two useful properties
1. The appName property has the browser’s name
2. The appVersion property has the version #
- Microsoft has chosen to set the appVersion of IE5
to 4 (?)
7.9 Event Propagation
- As with exception handling, it is valuable to be
able to propagate events, so that one handler can
deal with events from more than one source
- The DOM 2 model of event propagation bubbles
events upward in the hierarchy, toward the
document or window level
- There are two categories of events – those that
bubble and those that don’t
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
11
7.9 Event Propagation (continued)
- Events that are allowed to bubble can be handled
at the element level, but they also bubble upward
unless told not to with stopPropagation
- IE5 and NN6 support bubbling, but NN4 does not
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
12
Chapter 8
Sebesta:
Programming the
World Wide Web
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
13
8.1 Browser Support for Dynamic
Documents
- IE5 supports most of CSS and dynamic HTML
standards
- IE5 also supports some non-standard things, such
as advanced visual effects
- NN4 supports Netscape JSS and layers, but few of
the standard things (except CSS-P)
- NN6 support for standards is similar to that of IE5
- A dynamic HTML document is one whose tag
attributes, tag contents, or element style
properties can be changed after the document
has been and is still being displayed by a browser
- To make changes in a document, a script must be
able to address the elements of the document
using the DOM addresses of those elements
- NN4 uses a non-standard DOM structure, which
makes the few changes it can make more difficult
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
14
8.1 Browser Support for Dynamic
Documents (continued)
- The standard DOM allows base element addresses
to be gotten through their names, but the NN4
DOM does not support this
- Example:
<body>
<form id = "myForm" >
<input type = "button" id = "onButton">
…
</form>
</body>
- The standard DOM address of the button can be
gotten with the getElementById method, as in
document.getElementById("onButton").style
- For NN4, the whole path must be included, as in
document.myForm.onButton
- To build scripts that work for both NN4 and the
standard, you must determine whether NN4 is being
used and set the DOM address accordingly
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
15
8.1 Browser Support for Dynamic
Documents (continued)
- The script can determine the browser using the
navigator object
if ((navigator.appName == "Netscape" &&
(parseInt(navigator.appVersion) == 4))
dom = document.myForm.onButton;
else
dom =
document.getElementById("onButton").style;
- HTML elements are sometimes referenced through
a value of a variable or a function parameter, rather
than through its id
- In these cases, the DOM address must be built for
NN4 with eval and string catenation, as in
function changer(elemId) {
if ((navigator.appName == "Netscape") &&
(parseInt(navigator.appVersion) == 4))
dom = eval('document.' + elemId);
else
dom =
document.getElementById(elemId).style;
...
}
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
16
8.2 Element Positioning
- This is CSS-P, not DHTML
- Without CSS-P, the only ability to position elements
in the display of a document is with tables
- CSS-P is completely supported by IE5 and NN6,
and partially by NN4
- The position of any element can be dictated by
the three style properties: position, left, and top
- The three possible values of position are
absolute, relative, and static
- Absolute Positioning
<p style = "position: absolute; left: 50px;
top: 100 px;">
--> SHOW absPos.html and Figure 8.1
- If an element is nested inside another element
and is absolutely positioned, the top and left
properties are relative to the enclosing element
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
17
8.2 Element Positioning (continued)
--> SHOW absPos2.html and Figure 8.2
- Relative Positioning
- If no top and left properties are specified, the
element is placed exactly where it would have
been placed if no position property were given
- But it can be moved later
- If top and left properties are given, they are
offsets from where it would have placed without
the position property being specified
- If negative values are given for top and left, the
displacement is upward and to the left
--> SHOW relPos.html Figure 8.3
- Static Positioning
- The default value if position is not specified
- Neither top nor left can be initially set, nor can
they be changed later
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
18
8.3 Moving Elements
- If position is set to either absolute or relative, the
element can be moved after it is displayed
- Just change the top and left property values with
a script
--> SHOW mover.html & Figures 8.4 and 8.5
8.4 Element Visibility
- The visibility property of an element controls
whether it is displayed
- The standard values are visible and hidden
- The NN4 values, show and hide, are used
internally, though NN4 recognizes the std. values
- Suppose we want to toggle between hidden and
visible, and the element’s DOM address is dom
if (dom.visibility == "visible" ||
dom.visibility == "show")
dom.visibility = "hidden";
else
dom.visibility = "visible";
--> SHOW showHide.html
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
19
8.5 Dynamic Colors and Fonts
- Supported by IE5 and NN6
- Background color is controlled by the
backgroundColor property
- Foreground color is controlled by the color
property
- Can use a function to change these two properties
- Let the user input colors through text buttons
- Have the text button elements call the function
with the element address and the new color
Background color:
<input type = "text" size = "10"
name = "background"
onchange = "setColor('background',
this.value)">
- The actual parameter this.value works because
at the time of the call, this is a reference to the
text button
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
20
8.5 Dynamic Colors and Fonts
(continued)
function setColor(where, newColor) {
if (where == "background")
document.body.style.backgroundColor =
newColor;
else
document.body.style.color = newColor;
}
--> SHOW dynColors.html
- Changing fonts
- Can change the font properties of a link by using
the mouseover and mouseout events to trigger a
script that makes the changes
- In this case, we can put the script in the HTML
onmouseover = "this.style.color = 'blue';
this.style.font = 'italic 16pt Times';"
onmouseout = "this.style.color = 'black';
this.style.font = 'normal 16pt Times';”
--> SHOW dynLink.html and Figures 8.6 & 8.7
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
21
8.6 Dynamic Content
- The content of an HTML element is addressed with
the value property of its associated JavaScript
object
--> SHOW dynValue.html and Figure 8.8
8.7 Stacking Elements
- The top and left properties determine the position
of an element on the display screen, which is a
two-dimensional device
- We can create the appearance of a third dimension
by having overlapping elements, one of which
covers the others (like windows)
- This is done with the z-index property, which
determines which element is in front and which
are covered by the front element
- The JavaScript variable associated with the
z-index property is zIndex
- Element stacking is supported by IE5, NN6, & NN4
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
22
8.7. Stacking Elements (continued)
- The stacking order can be changed dynamically
- Make the elements anchors, so they respond to
mouse clicking
- The href attribute can be set to call a JavaScript
function by assigning it the call, with
'JAVASCRIPT' attached to the call code
<a href = "JAVASCRIPT:fun()">
- The function must change the zIndex value of
the element
- A call to the function from an element sets the
zIndex value of the new top element to 10 and
the zIndex value of the old top element to 0
- It also sets the current top to the new top
--> SHOW stacking.html and Figures 8.9, 8.10, & 8.11
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
23
Chapter 9
Sebesta:
Programming the
World Wide Web
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
24
9.1 Introduction
- Applets are relatively small Java programs whose
execution is triggered by a browser
- The purpose of an applet is to provide processing
capability and interactivity for HTML documents
- The ‘standard’ operations of applets are provided
by the parent class, Applet
public class class_name extends Applet { … }
- The Applet class descends directly from Panel,
which descends directly from Component
- The use of applets has been restrained by the lack
of support for Swing
- Specifically, the JVM that comes with NN4 does
not support Swing, so NN4 users cannot execute
applets that use it
- Use of applets is still widespread, and there is
heavy use in intranets, where all browsers can
be required to support the latest JVM
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
25
9.1 Introduction (continued)
- Applets are an alternative to CGI and embedded
scripts
- Comparisons:
- CGI is faster than applets and JavaScript, but it is
run on the server
- JavaScript is easier to learn and use than Java,
but less expressive
- Java is faster than JavaScript
- Java graphics are powerful, even with just AWT
(JavaScript has none)
- JavaScript does not require the additional
download from the server that is required for
applets
- Java may become more of a server-side tool, in
the form of servlets, than a client-side tool
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
26
9.2 Primary Applet Activities
- Browser actions:
a. Download and instantiate the applet class
b. Call the applet’s init method
c. Call the applet’s start method
- This starts the execution of the applet
- When the user takes a link from the document
that has the applet, the browser calls the
applet’s stop method
- When the browser is stopped by the user, the
browser calls the applet’s destroy method
- Every applet must override at least one of the three
methods, init, start, or paint
(paint is inherited from Component)
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
27
9.3 The paint Method
- Always called by the browser (not the applet itself)
- Takes one parameter, of class Graphics, which is
defined in java.awt
- The parameter object is created by the browser
- The protocol is:
public void paint(Graphics grafObj) { … }
- The simplest use of paint is to display text, using
the drawString method
- Three parameters: a String literal, the x
coordinate of the left end of the string, and the
y coordinate of the base of the string
(the coordinates are given in pixels)
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
28
9.3 The paint Method (continued)
/* welcomeMessage.java
An applet to illustrate the display of
a string
*/
import java.applet.Applet;
import java.awt.*;
public class welcomeMessage extends Applet {
public void paint(Graphics grafObj) {
grafObj.drawString(
"Welcome to my home page!", 50, 50);
}
}
- Font Control
- The Font class, defined in java.awt.Font, has
three variables that specify the font name, style,
and size of the font used by drawString
The size parameter is in points
- The styles are PLAIN, BOLD, and ITALIC
- To change the font, create a Font object with
the desired parameters and set it with the
setFont method of Graphics, which takes a
Font parameter
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
29
9.3 The paint Method (continued)
/* welcomeMessage_2.java
An applet to illustrate the display of a
string in specific font, font style, and
font size
*/
import java.applet.Applet;
import java.awt.*;
public class welcomeMessage_2 extends Applet {
Font myFont = new Font("TimesRoman",
Font.ITALIC, 24);
public void paint(Graphics grafObj) {
grafObj.setFont(myFont);
grafObj.drawString(
"Welcome to my home page!", 50, 50);
}
}
9.4 The <object> Tag
- Used to specify an applet in an HTML document
- Creates a space in the document display for
applet output (like <img> does)
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
30
9.4 The <object> Tag (continued)
<object codetype = "application/java"
code = "applet_class_file"
width = "applet display width"
height = "applet display height">
</object>
- The display width and height are in pixels
- The applet_class_file is the compiled version
<!-- ch9_2.html
To test the applet, welcomeMessage_2
-->
<html>
<head>
<title> Test welcomeMessage_2 </title>
</head>
<body>
<object codetype = "application/java"
code = "welcomeMessage_2.class"
width = "500"
height = "100">
</object>
</body>
</html>
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
31
9.4 The <object> Tag (continued)
9.5 Applet Parameters
- Applets can be sent parameters through HTML,
using the <param> tag and its two attributes, name
and value
- Parameter values are strings
- e.g., <param name = "fruit"
value = "apple">
- The applet gets the parameter values with
getParameter, which takes a string parameter,
which is the name of the parameter
String myFruit = getParameter("fruit");
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
32
9.5 Applet Parameters (continued)
- If no parameter with the given name has been
specified in the HTML document, getParameter
returns null
- By checking the return value against null, a
default value can be set
- If the parameter value is not really a string (although
parameters are all sent as strings), the value
returned from getParameter must be converted, as
in
String pString = getParameter("size");
if (pString == null)
mySize = 24;
else
mySize = Integer.parseInt(pString);
- The best place to put the code to get parameter
values is in init
- Parameters are stored in instance variables
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
33
9.5 Applet Parameters (continued)
<body>
<object codetype = "application/java"
code = "welcomeMessage_3.class"
width = "500"
height = "100">
<param name = "size"
value = "35">
</object>
</body>
9.6 Simple Graphics (AWT)
- Coordinate system: (0, 0) is at the upper left corner
- The methods that draw graphic figures are called
through the Graphics object (the parameter to
paint)
- Lines are drawn with drawLine(x1, y1, x2, y2)
- Draws a line from (x1, y1) to (x2, y2)
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
34
9.6 Simple Graphics (AWT) (continued)
- Rectangles are drawn with drawRect and fillRect
- Both take four parameters, the coordinates of the
upper left corner of the rectangle and the width
and height of the rectangle (width and height are
in pixels)
- Rectangles with rounded corners can be drawn
with drawRoundRect and fillRoundRect
- These two take two more parameters, which
specify the numbers of horizontal pixels and
vertical pixels in the rounding
/* rectangles.java */
import java.applet.Applet;
import java.awt.*;
public class rectangles extends Applet {
public void paint(Graphics 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);
}
}
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
35
9.6 Simple Graphics (AWT) (continued)
- 3D rectangles can be created with a 5th
parameter, true (not pushed) or false (pushed)
- Polygons are drawn with drawPolygon, which
takes three parameters, two arrays of coordinates
of edge endpoints, and the number of edges
public void paint(Graphics grafObj) {
int xCoordinates [] = {30, 50, 64, 64,
50, 30, 16, 16, 30};
int yCoordinates [] = {10, 10, 24, 44,
58, 58, 44, 24, 10};
grafObj.drawPolygon(xCoordinates,
yCoordinates, 9);
}
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
36
9.6 Simple Graphics (AWT) (continued)
- drawPolygon can also take a single parameter,
which is a Polygon object, whose constructor
takes the same three parameters as drawPolygon
- Ovals are like rectangles (same parameters)
9.7 Color
- The Color class has predefined objects for
common colors
Color.white, Color.black, Color.gray,
Color.red, Color.green, Color.blue,
Color.yellow, Color.magenta, Color.cyan,
Color.pink, Color.orange
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
37
9.7 Color (continued)
- An object for any color can be created with the
Color constructor, as in
Color myColor = new Color(x, y, z);
- The color of the Graphics object can be set with
setColor, as in
grafObj.setColor(Color.cyan);
- The foreground and background colors of the
applet display are set with methods from Panel
9.8 Interactive Applets
- Applet extends Panel, which extends Component
- The Component class includes GUI components
as subclasses
- Panel objects are used to enclose GUI components
- The Applet class is itself a GUI component
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
38
9.8 Interactive Applets (continued)
- Labels
- Label objects are static strings
Label labl1 = new Label("Click this button");
- Plain buttons
Button myButton = new Button(
"Click here for fun");
- Checkboxes
Checkbox box1 = new Checkbox("Beer");
Checkbox box2 = new Checkbox("Pretzels");
- Radio buttons – just checkboxes in a
CheckboxGroup
pop = new CheckboxGroup();
Checkbox box1 = new Checkbox("Coke", pop,
true);
Checkbox box2 = new Checkbox("Pepsi", pop,
false);
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
39
9.8 Interactive Applets (continued)
- Text boxes
TextField myName = new TextField(30);
- A Panel object is needed to contain components
Panel myPanel = new Panel();
myPanel.setBackground(Color.yellow);
myPanel.setForeground(Color.blue);
myPanel.add(box1);
- Layout Managers
- Default is FlowLayout – just like a browser
- GridLayout is like HTML document panels
Panel buttonPanel = new Panel();
buttonPanel.setLayout(
new GridLayout(3, 2, 10, 10));
- Three rows of two components each, with 10
pixels between the components
--> SHOW Pizza.java
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
40
9.8 Interactive Applets (continued)
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
41
9.8 Interactive Applets (continued)
- The Java Event Model
- Related to the JavaScript event model
- Event handlers are called event listeners
- Connection of an event to a listener is through
event listener registration
- Done with a method of the class that
implements the listener interface
- The panel object that holds the components
can be the event listener for those components
- Event generators send messages (call methods)
to registered event listeners when events occur
- Event handling methods must conform to a
standard protocol, which comes from an
interface
- We only consider the “semantic” events
(there are also “low-level” events)
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
42
9.8 Interactive Applets (continued)
- Semantic Events
ActionEvent
click a button, select from a menu
or list, or type the enter button in
a text field
AdjustmentEvent
adjust a scroll bar
ItemEvent
select a checkbox or list item
TextEvent
change the contents of a text field
or text area
- For these four events, we have the following
interfaces and handler methods:
Interface
Handler method
ActionListener
AdjustmentListener
ItemListener
TextListener
actionPerformed
adjustmentValueChanged
itemStateChanged
textValueChanged
- The methods to register the listener is the interface
name with “add” prepended
- e.g.,
button1.addActionListener(myPanel);
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
43
9.8 Interactive Applets (continued)
- Event handlers get an event object as a parameter,
through which information about the event can be
gotten with methods, such as getState
- e.g., button1.getState() returns true if the
button is on, false otherwise
- When an event handler has just a few lines, it can
be implemented as an instance of an anonymous
nested class
- Example: a button that sets a font
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e) {
text.setFont(newFont);
}
});
--> SHOW RadioB.java
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
44
9.9 Concurrency in Java
- Our only interest in concurrency here is to
illustrate how threads can be used to create
animation in an applet
- A thread of control is a sequence of program
points reached as execution flows through the
program
- A nonconcurrent program has a single thread of
control; a concurrent program has more than one
- Java supports lightweight concurrency through its
threads
- The concurrent program units in Java are methods
named run, whose code can be in concurrent
execution with other run methods and with main
- There are two ways to implement threads, as a
subclass of Thread and by implementing the
interface Runnable
- The Thread class
- Two essential methods, run and start
- run is the concurrent method
- start tells the run method to begin execution
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
45
9.9 Concurrency in Java (continued)
- All Java programs run in threads
- For applications, when execution is to begin, a
thread is created for main and its start method is
called
- For applets, when the browser finds one, it
creates a thread and calls the applet
--> SHOW Names.java, output, delayer, and output
- Thread States
- New - created, but start hasn’t been called
- Runnable or ready - ready to run, but is not
currently running
- In the ready queue
- Running - actually has the processor
- Blocked - was running, but is not now, because
it was interrupted (i/o, end of time slot, gave up
its time slot, etc.)
- Dead - either its stop was called or its run method
completed its execution
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
46
9.9 Concurrency in Java (continued)
- Thread methods
- yield is a request from the running thread to give
up the processor; a static method
- sleep(time) - blocks the thread for at least as
many milliseconds as the parameter specifies;
also a static method
- sleep can throw InterruptedException, which
must be caught
- stop - now deprecated, because of safety
problems
- Now we override it and just set the thread
reference to null (destroys the thread)
- An example - an animated digital clock
- An applet must implement Runnable, its start
and stop methods, and the repaint method of
Graphics
- repaint is called after the applet display has
changed
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
47
9.9 Concurrency in Java (continued)
- Our applet is named Clock
- Its start method creates a new Thread object,
sending this to the constructor. This sets the new
Thread object’s target to the Clock object, which
forces the thread to get its run method from the
Clock object
- After creating the Thread object, start is called to
start its execution
- The run method sets a variable to the currently
executing thread, and then loops as long as the
thread is clockThread
- The loop gets the new time with a new Date
object and repaints the display every second
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
48
Chapter 10
Sebesta:
Programming the
World Wide Web
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
49
10.1 Introduction
- SGML is a meta-markup language
- Developed in the early 1980s; ISO std. In 1986
- HTML was developed using SGML in the early
1990s - specifically for Web documents
- Two problems with HTML:
1. Fixed set of tags and attributes
- User cannot invent new tags or attributes
- So, the given tags must fit every kind of
document, and the tags cannot connote
any particular meaning
2. There are no restrictions on arrangement or
order of tag appearance in a document
- One solution to the first of these problems:
Let users define their own tags (with assigned
meanings)
(i.e., design their own “HTML”s using SGML)
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
50
10.1 Introduction (continued)
- Problem with using SGML:
- It’s too large and complex to use, and it is very
difficult to build a parser for it
- A better solution: Define a lite version of SGML
- That’s what the eXtensible Markup Language is
- XML is not a replacement for HTML
- HTML is a markup language used to describe the
layout of any kind of information
- XML is a meta-markup language that can be used
to define markup languages that can define the
meaning of specific kinds of information
- XML is a very simple and universal way of storing
and transferring data of any kind
- All documents described with an XML-derived
markup language can be parsed with a single
parser
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
51
10.1 Introduction (continued)
- We will refer to an XML-based markup language as a
tag set
- Strictly speaking, a tag set is an XML application, but
that terminology can be confusing
- IE5 has an XML parser (although it is based on an
early XML standard)
- NN4 does not support XML, but NN6 does
10.2 The Syntax of XML
- XML documents have data elements, markup
declarations (instructions for the XML parser), and
processing instructions (for the application program
that is processing the data in the document)
- All XML documents begin with an XML declaration:
<?xml version = "1.0"?>
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
52
10.2 The Syntax of XML (continued)
- XML names:
- Must begin with a letter or an underscore
- They can include digits, hyphens, and periods
- There is no length limitation
- They are case sensitive (unlike HTML names)
- Syntax rules for XML: (similar to those for XHTML)
- Every element that has content must have a
closing tag
- Tags must be properly nested
- All attribute values must be quoted
- An XML document that follows all of these rules is
well formed
- Attributes are not used in XML the way they are in
HTML
- In XML, you often define a new nested tag to
provide more info about the content of a tag
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
53
10.2 The Syntax of XML (continued)
- Nested tags are better than attributes, because
attributes cannot describe structure and the
structural complexity may grow
<!-- A tag with one attribute -->
<patient name = "Maggie Dee Magpie">
...
</patient>
<!-- A tag with one nested tag -->
<patient>
<name> Maggie Dee Magpie </name>
...
</patient>
<!-- A tag with one nested tag, which contains
three nested tags -->
<patient>
<name>
<first> Maggie </first>
<middle> Dee </middle>
<last> Magpie </last>
</name>
...
</patient>
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
54
10.3 XML Document Structure
- An XML document often uses two auxiliary files:
- A Data Type Definition (rules about structure)
- A style or presentation specification
- An XML document has a single root element
- An XML document consists of one or more entities
- Entities range from a single special character to
a book chapter
- An XML document has one document entity
- All other entities are referenced in the
document entity
- Reasons for entity structure:
1. Large documents are easier to manage
2. Repeated entities need not be literally repeated
3. Binary entities can only be referenced in the
document entities (XML is all text!)
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
55
10.3 XML Document Structure (continued)
- When the XML parser encounters a reference to
a non-binary entity, the entity is merged in
- Entity names:
- Do not have a length limitation
- Must begin with a letter, a dash, or a colon
- Can include letters, digits, periods, dashes,
underscores, or colons
- A reference to an entity has the form:
&entity_name;
- One common use of entities is for special
characters that may be used for markup delimiters
- These are predefined:
<
>
&
"
'
&lt;
&gt;
&amp;
&quot;
&apos;
- The user can only define entities in a DTD
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
56
10.4 Data Type Definitions
- A DTD is a set of structural rules called
declarations
- These rules specify how and where a set of
elements can appear in a document
- Not all XML documents have or need a DTD
- The DTD for a document can be internal or
external
- All of the declarations of a DTD are enclosed in the
block of a DOCTYPE markup declaration
- DTD declarations have the form:
<!keyword … >
- There are four possible declaration keywords:
ELEMENT, ATTLIST, ENTITY, and NOTATION
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
57
10.4 Data Type Definitions (continued)
- Declaring Elements
- Element declarations are similar to BNF
- An element declaration specifies the element’s
structure
- If the element is a leaf node of the document tree,
its structure is in terms of characters
- If it is an internal node, its structure is a list of
children elements (either leaf or internal nodes)
- General form:
<!ELEMENT element_name (list of child names)>
e.g.,
<!ELEMENT memo (from, to, date, re, body)>
memo
from
Chapter 7
to
date
re
body
© 2001 by Addison Wesley Longman, Inc.
58
10.4 Data Type Definitions (continued)
- Declaring Elements (continued)
- Child elements can have modifiers, +, *, ?
e.g.,
<!ELEMENT person
(parent+, age, spouse?, sibling*)>
- Leaf nodes specify data types, most often
PCDATA, which is an acronym for parsable
character data
- Data type could also be EMPTY (no content)
and ANY (can have any content)
- Example of a leaf declaration:
<!ELEMENT name (#PCDATA)>
- Declaring Attributes
- General form:
<!ATTLIST el_name at_name at_type [default]>
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
59
10.4 Data Type Definitions (continued)
- Declaring Attributes (continued)
- Attribute types: there are many possible, but we
will consider only CDATA
- Default values:
a value
#FIXED value (every element will have
this value),
#REQUIRED (every instance of the element must
have a value specified), or
#IMPLIED (no default value and need not specify
a value)
- e.g.,
<!ATTLIST
<!ATTLIST
<!ATTLIST
<!ATTLIST
car
car
car
car
doors CDATA "4">
engine_type CDATA #REQUIRED>
price CDATA #IMPLIED>
make CDATA #FIXED "Ford">
<car doors = "2" engine_type = "V8">
...
</car>
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
60
10.4 Data Type Definitions (continued)
- Declaring Entities
- Two kinds:
- A general entity can be referenced anywhere in
the content of an XML document
- A parameter entity can be referenced only in
a markup declaration
- If several predefined entities must appear near
each other in a document, it is better to avoid
using entity references
- Character data section
<![CDATA[ content ]]>
e.g., instead of
Start &gt; &gt; &gt; &gt; HERE
&lt; &lt; &lt; &lt;
use
<![CDATA[Start >>>> HERE <<<<]]>
- If the CDATA content has an entity reference,
it is taken literally
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
61
10.4 Data Type Definitions (continued)
- Declaring Entities (continued)
- General form of declaration:
<!ENTITY [%] entity_name "entity_value">
e.g., <!ENTITY jfk "John Fitzgerald Kennedy">
- A reference: &jfk;
- If the entity value is longer than a line, define it
in a separate file (an external text entity)
<!ENTITY entity_name SYSTEM "file_location">
--> SHOW planes.dtd
- XML Parsers
- Always check for well formedness
- Some check for validity, relative to a given DTD
- Called validating XML parsers
- You can download a validating XML parser from:
http://xml.apache.org/xerces-j/index.html
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
62
10.4 Data Type Definitions (continued)
- Internal DTDs
<!DOCTYPE root_name [
…
]>
- External DTDs
<!DOCTYPE XML_doc_root_name SYSTEM
“DTD_file_name”>
--> SHOW planes.xml
- Problems with DTDs:
1. Syntax is different from XML - cannot be parsed
with an XML parser
2. Do not allow specification of a particular kind of
data
- XML Schema are a solution to these problems
- We don’t cover them because the popular
browsers don’t support them, yet
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
63
10.5 Namespaces
- A markup vocabulary is the collection of all of the
element types and attribute names of a markup
language (a tag set)
- An XML document may define its own tag set and
also use that of another tag set - CONFLICTS!
- An XML namespace is a collection of names used
in XML documents as element types and attribute
names
- The name of an XML namespace has the form of
a URI
- A namespace declaration has the form:
<element_name xmlns[:prefix] = URI>
- The prefix is a short name for the namespace,
which is attached to names from the
namespace in the XML document
<gmcars xmlns:gm = "http://www.gm.com/names">
- In the document, you can use <gm:pontiac>
- Purposes of the prefix:
1. Shorthand
2. URI includes characters that are illegal in XML
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
64
10.5 Namespaces (continued)
- Can declare two namespaces on one element
<gmcars xmlns:gm = "http://www.gm.com/names"
xmlns:html = "http://www.w3.org/TR/REC-html40">
- The gmcars element can now use gm names and
html names
- One namespace can be made the default by
leaving the prefix out of the declaration
6. Displaying Raw XML Documents
- There is no presentation information in an XML
document
- An XML browser should have a default style sheet
for an XML document that does not specify one
- You get a stylized listing of the XML
--> SHOW Figure 10.2
--> SHOW Figure 10.3
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
65
10.7 Displaying XML Documents with
CSS
- A CSS style sheet for an XML document is just a
list of its tags and associated styles
- The connection of an XML document and its style
sheet is made through an xml-stylesheet
processing instruction
<?xml-stylesheet type = "text/css"
href = "mydoc.css"?>
--> SHOW planes.css and Figure 10.4
10.8 XML Transformations and Style
Sheets
- XSL began as a standard for presentations of XML
documents
- Split into two parts:
- XSLT - Transformations
- XSL-FO - Formatting objects
- XSLT uses style sheets to specify
transformations
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
66
10.8 XML Transformations and Style
Sheets (continued)
- An XSLT processor merges an XML document into
an XSLT style sheet
- This merging is a template-driven process
- An XSLT style sheet can specify page layout,
page orientation, writing direction, margins, page
numbering, etc.
- The processing instruction we used for connecting
a CSS style sheet to an XML document is used to
connect an XSLT style sheet to an XML document
<?xml:stylesheet type = "text/xsl"
href = "XSL style sheet"?>
- An example:
<?xml version = "1.0"?>
<!-- xslplane.xml -->
<?xml:stylesheet type = "text/xsl"
href = "xslplane.xsl" ?>
<plane>
<year> 1977 </year>
<make> Cessna </make>
<model> Skyhawk </model>
<color> Light blue and white </color>
</plane>
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
67
10.8 XML Transformations and Style
Sheets (continued)
- An XSLT style sheet is an XML document with a
single element, stylesheet, which defines
namespaces
<xsl:stylesheet xmlns:xsl =
"http://www.w3.org/1999/XSL/Format">
- For IE5, you must use the earlier namespace,
http://www.w3.org/TR/WD-xsl
- If a style sheet matches the root element of the
XML document, it is matched with the template:
<xsl:template match = "/">
- A template can match any element, just by naming
it (in place of /)
- XSLT elements include two different kinds of
elements, those with content and those for which
the content will be merged from the XML doc
- Elements with content often represent HTML
elements
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
68
10.8 XML Transformations and Style
Sheets (continued)
<span style = "font-size: 14">
Happy Easter! </span>
- XSLT elements that represent HTML elements are
simply copied to the merged document
- The XSLT value-of element
- Has no content
- Uses a select attribute to specify part of the XML
data to be merged into the XSLT document
<xsl:value-of select = ”CAR/ENGINE" />
- The value of select can be any branch of the
document tree
--> SHOW xslplane.xsl and Figure 10.5
- The XSLT for-each element
- Used when an XML document has a sequence of
the same elements
--> SHOW xslplanes.xml
--> SHOW xslplanes.xsl & Figure 10.6
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
69
Chapter 11
Sebesta:
Programming the
World Wide Web
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
70
11.1 Web Server Operation
- Client-server systems
- When two computers are connected, either could
be the client
- The client initiates the communication, which the
server accepts
- Generally, clients are human consumers of
information, while servers are machine suppliers
- Client/server systems have an efficient division of
work
- All communications between Web clients and
servers use HTTP
- When a Web server starts, it tell its OS it is ready to
accept communications through a specific port,
usually 8080
- All current Web servers are descendents of the first
two (CERN and NCSA)
- Most servers are Apache running under UNIX
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
71
11.2 General Server Characteristics
- Web servers have two separate directories
- The document root is the root directory of all
servable documents (well, not really all)
e.g. Suppose the site name is www.bloomers.com
and the document root is named topdocs,
and it is stored in the /admin/web directory
So, /admin/web/topdocs is the document
directory address
If a request URL is
http://www.bloomers.com/bulbs/tulips.html
the server will search for the file named
/admin/web/topdocs/bulbs/tulips.html
- The server can have virtual document trees
- Sometimes a different disk, possibly on a
different machine, is used after the original
disk is filled
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
72
11.2 General Server Characteristics
(continued)
- The server root is the root directory for all of the
code that implements the server
- The server root usually has four files
- One is the code for the server itself
- Three others are subdirectories
- conf - for configuration information
- logs - to store what has happened
- cgi-bin - for executable scripts
- Contemporary servers provide many services:
- Virtual hosts - multiple sites on the same system
- Proxy servers - to serve documents from the
document roots of other sites
- Besides HTTP, support for FTP, Gopher, News,
email
- Support for database access
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
73
11.3 Apache under UNIX
- Apache is available for other platforms, but it is
most commonly used under UNIX
- Apache is now a large and complex system
- The configuration file is named httpd.conf
- The directives in the configuration file control the
operation of the server
- Configuration file format:
- Comments begin with a #
- Blank lines are ignored
- Non-blank lines that do not begin with # must
begin with a directive name, which may take
parameters, separated by white space
- When Apache begins, it reads the configuration
files and sets its parameters according to what it
reads
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
74
11.3 Apache under UNIX (continued)
- Changes to configuration files affect Apache only if
it is forced to reset
- Use the following UNIX commands to force
Apache to reset:
cd /usr/local/etc/httpd/logs
kill -HUP `cat httpd.pid`
- This creates a hangup signal
- It works because Apache write its process id
(pid) into httpd.pid when it starts
- Directives
- ServerName - default is what is returned by the
hostname command, but it may be only the first
part
ServerName
Chapter 7
www.bloomers.com
© 2001 by Addison Wesley Longman, Inc.
75
11.3 Apache under UNIX (continued)
- ServerRoot - to set the server root address
- Default is /usr/local/etc/httpd
- If it is stored elsewhere, tell Apache with:
ServerRoot
/usr/local/httpd
- ServerAdmin - email address of the site admin
ServerAdmin
[email protected]
- DocumentRoot - set the document root address
- Default is /usr/local/etc/httpd/htdocs
- If it is elsewhere, tell Apache with:
DocumentRoot
Chapter 7
/local/webdocs
© 2001 by Addison Wesley Longman, Inc.
76
11.3 Apache under UNIX (continued)
- Alias - to specify a virtual document tree
- Takes two parameters, virtual path for URLs and
the actual path
- Example:
Alias
/bushes
/usr/local/plants/bushes
- Now,
http://www.bloomers.com/bushes/roses.html
will be mapped to
/usr/local/plants/bushes/roses.html
- ScriptAlias - to create a secure place for CGI
scripts
- Creates a virtual directory
ScriptAlias
Chapter 7
/cgi-bin/
/usr/local/etc/httpd/cgi-bin/
© 2001 by Addison Wesley Longman, Inc.
77
11.3 Apache under UNIX (continued)
- Redirect - to redirect requests to another system
e.g., To move the bushes directory to
www.bloomers2.com
Redirect /bushes
http://www.bloomers2.com/local/web/bushes
- DirectoryIndex - URL-specified directories
- When a request includes a URL that ends with
a slash, Apache searches for a document to
return, called the welcome page
- Default welcome page is index.html
- If there is no index.html, Apache may try to
build a directory listing for the home
directory (unless automatic directory listings
are turned off)
- To avoid this, provide more than one
welcome page names
DirectoryIndex
Chapter 7
index.html
contents.html
© 2001 by Addison Wesley Longman, Inc.
78
11.3 Apache under UNIX (continued)
- UserDir - to specify whether local users can or
cannot add or delete documents; default is:
UserDir
public_html
- Now, if user bob stores stuff.html in his
public_html directory, the URL
http://site-name/~bob/stuff.html
will work
- To make a subdirectory of public_html
available, include it in the parameter
UserDir
public_html/special_stuff
- To disallow additions and deletions:
UserDir
disabled
- Logs
- Access logs record all accesses (time, date, HTTP
command, URL, status, etc.)
- Error logs have the form:
[date/time] The error message
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
79
11.4 Overview of Servlets
- A servlet is a compiled Java class
- Servlets are executed on the server system under
the control of the Web server
- Servlets are managed by the servlet container, or
servlet engine
- Servlets are called through HTML
- Servlets receive requests and return responses,
both of which are supported by the HTTP protocol
- When the Web server receives a request that is for
a servlet, the request is passed to the servlet
container
- The container makes sure the servlet is loaded
and calls it
- The servlet call has two parameter objects, one
with the request and one for the response
- When the servlet is finished, the container
reinitializes itself and returns control to the Web
server
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
80
11.4 Overview of Servlets (continued)
- Servlets are used 1) as alternatives to CGI, and
2) as alternatives to Apache modules
- Servlet Advantages:
- Can be faster than CGI, because they are run in
the server process
- Have direct access to Java APIs
- Because they continue to run (unlike CGI
programs), they can save state information
- Have the usual benefits of being written in Java
(platform independence, ease of programming)
11.5 Servlet Details
- All servlets are classes that either implement the
Servlet interface or extend a class that implements
the Servlet interface
- The Servlet interface provides the interfaces for
the methods that manage servlets and their
interactions with clients
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
81
11.5 Servlet Details (continued)
- The Servlet interface declares three methods that
are called by the servlet container (the life-cycle
methods)
- init - initializes the servlet and prepares it to
respond to client requests
- service - controls how the servlet responds to
requests
- destroy - takes the servlet out of service
- The Servlet interface declares two methods that
are used by the servlet:
- getServletConfig - to get initialization and
startup parameters for itself
- getServletInfo - to allow the servlet to return
info about itself (author, version #, etc.) to
clients
- Most user-written servlet classes are extensions
to HttpServlet (which is an extension of
GenericServlet, which implements the Servlet
Interface)
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
82
11.5 Servlet Details (continued)
- Two other necessary interfaces:
- ServletResponse – to encapsulate the
communications, client to server
- ServletRequest – to encapsulate the
communications, server to client
- Provides servlet access to
ServletOutputStream
- HttpServlet – an abstract class
- Extends GenericServlet
- Implements java.io.Serializable
- Every subclass of HttpServlet MUST override at
least one of the methods of HttpServlet
doGet*
doPost*
doPut*
doDelete*
init
destroy
getServletInfo
* Called by the server
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
83
11.5 Servlet Details (continued)
- The protocol of doGet is:
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, java.io.IOException
- ServletException is thrown if the GET request
could not be handled
- The protocol of doPost is the similar
- Servlet output – HTML
1. Use the setContentType method of the response
object to set the content type to text/html
response.setContentType("text/html");
2. Create a PrintWriter object with the getWriter
method of the response object
PrintWriter servletOut =
response.getWriter();
- Example – Respond to a GET request with no data
Show ch11_1.html and Greeting.java
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
84
11.6 A Survey Example
--> Show ch11_2.html (consumer electronics survey
form) and Figure 11.3
- The servlet:
- To accumulate voting totals, it must write a file
on the server
- The file will be read and written as an object
(the array of vote totals) using
ObjectInputStream
- An object of this class is created with its
constructor, passing an object of class
FileInputStream, whose constructor is called
with the file variable name as a parameter
ObjectInputStream indat =
new ObjectInputStream(
new FileInputStream(File_variable_name));
- On input, the contents of the file will be cast to
integer array
- For output, the file is written as a single object
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
85
11.6 A Survey Example (continued)
- The servlet must access the form data from the
client
- This is done with the getParameter method of the
request object, passing a literal string with the
name of the form element
e.g., if the form has an element named zip
zip = request.getParameter("zip");
- If an element has no value and its value is
requested by getParameter, the returned value
is null
- If a form value is not a string, the returned string
must be parsed to get the value
- e.g., suppose the value is an integer literal
- A string that contains an integer literal can
be converted to an integer with the parseInt
method of the wrapper class for int, Integer
price = Integer.parseInt(
request.getParameter("price"));
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
86
11.6 A Survey Example (continued)
- The file structure is an array of 14 integers, 7 votes
for females and 7 votes for males
- Servlet actions:
If the votes data array exists
read the votes array from the data file
else
create the votes array
Get the gender form value
Get the form value for the new vote and convert it
to an integer
Add the vote to the votes array
Write the votes array to the votes file
Produce the return HTML document that shows the
current results of the survey
- Every voter will get the current totals
--> Show the servlet, Survey.java
--> Show the results of running Survey
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
87
11.7 Storing Information about Clients
- A session is the collection of all of the requests
made by a particular browser from the time the
browser is started until the user exits the browser
- The HTTP protocol is stateless
- But, there are several reasons why it is useful for
the server to relate a request to a session
- Shopping carts for many different simultaneous
customers
- Customer profiling for advertising
- Customized interfaces for specific clients
- Approaches to storing client information:
- Store it on the server – too much to store!
- Store it on the client machine - this works
- Cookies
- A cookie is an object sent by the server to the
client
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
88
11.7 Storing Information about Clients
(continued)
- Every HTTP communication between the browser
and the server includes information in its header
about the message
- At the time a cookie is created, it is given a
lifetime
- Every time the browser sends a request to the
server that created the cookie, while the cookie
is still alive, the cookie is included
- A browser can be set to reject all cookies
- A cookie object has data members and methods
- Data members to store lifetime, name, and a
value (the cookies’ value)
- Methods: setComment, setMaxAge, setValue,
getMaxAge, getName, and getValue
- Cookies are created with the Cookie constructor
Cookie newCookie =
new Cookie(gender, vote);
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
89
11.7 Storing Information about Clients
(continued)
- By default, a cookie’s lifetime is the current
session
- If you want it to be longer, use setMaxAge
- A cookie is attached to the response with
addCookie
- Order in which the response must be built:
1. Add cookies
2. Set content type
3. Get response output stream
4. Place info in the response
- The browser does nothing with cookies, other
than storing them and passing them back
- A servlet gets a cookie from the browser with
the getCookies method
Cookie the Cookies [];
…
theCookies = request.getCookies();
- A Vote Counting Example
 Show ch11_3.html
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
90
11.7 Storing Information about Clients
(continued)
- Vote counting servlet activities:
- See if a vote was cast
- Make sure the voter hasn’t voted before
- Tally real votes and give the client the totals
- Store votes in a file
Show the VoteCounter algorithm
-> Show VoteCounter
-> Show VoteCounter output (Figure 11.6)
- Session Tracking
- An alternative to cookies
- Use the HttpSession object, which can store a
list of names and values
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
91
11.7 Storing Information about Clients
(continued)
- Create a Session object
- Put value in the session object with putValue
mySession.putValue("iVoted", "true");
- A session can be killed with the invalidate
method
- A value can be removed with removeValue
- A value can be gotten with getValue(name)
- All names of values can be gotten with
getValueNames
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
92
Chapter 12
Sebesta:
Programming the
World Wide Web
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
93
12.1 Relational Databases
- A database is a collection of data organized to
allow relatively easy access for retrievals,
additions, and deletions
- A relational database is a collection of tables of
data, each of which has one special column that
stores the primary keys of the table
- An Example Relational Database:
- A relational database for used Corvettes that are
for sale
- Could just put all data in a single table, whose
primary key would be a simple sequence number
- The table could have information about various
equipment the cars could have
- However, it is better to put the equipment in a
different table and use a cross-reference table
to relate cars to equipment
- Use a separate table for state names, with only
references in the main table
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
94
12.1 Relational Databases (continued)
- Logical model
Corvettes
States
Corvettes_
Equipment
Equipment
- Implementation
Vette_id
1
2
3
4
5
6
7
8
9
10
Body_style
coupe
hatchback
convertible
hatchback
hatchback
hardtop
coupe
convertible
hardtop
hatchback
Miles
18.0
58.0
13.5
19.0
25.0
15.0
55.0
17.0
17.0
50.0
Year
1997
1996
2001
1995
1991
2000
1979
1999
2000
1995
State
4
7
1
2
5
2
10
5
5
7
Figure 12.2 The Corvettes table
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
95
12.1 Relational Databases (continued)
State_id
1
2
3
4
5
6
7
8
9
10
State
Alabama
Alaska
Arizona
Arkansas
California
Colorado
Connecticut
Delaware
Florida
Georgia
Figure 12.3 The States table
Equip_id
1
2
3
4
5
6
Equip
Automatic
4-speed
5-speed
6-speed
CD
leather
Figure 12.4 The Equipment table
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
96
12.1 Relational Databases (continued)
Vette_id
1
1
1
2
2
2
3
3
4
4
5
5
6
7
7
8
8
8
9
9
9
10
10
Equip
1
5
6
1
5
6
1
6
2
6
1
6
2
4
6
4
5
6
4
5
6
1
5
Figure 12.5 The Corvettes_Equipment
cross-reference table
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
97
12.2 Intro to SQL
- A standard language to create, query, and modify
databases
- Supported by all major database vendors
- More similar to structured English than a
programming language
- We cover only five basic commands: CREATE
TABLE, SELECT, INSERT, UPDATE, and DELETE
- SQL reserved words are case insensitive
- The CREATE TABLE command:
CREATE TABLE table_name (
column_name1 data_type constraints,
…
column_namen data_type constraints)
- There are many different data types
(INTEGER, FLOAT, CHAR(length), …)
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
98
12.2 Intro to SQL (continued)
- There are several constraints possible
e.g., NOT NULL, PRIMARY KEY
CREATE TABLE States (
State_id INTEGER PRIMARY KEY
State CHAR(20))
NOT NULL,
- The SELECT Command
- Used to specify queries
- Three clauses: SELECT, FROM, and WHERE
- General form:
SELECT column names
FROM table names
WHERE condition
SELECT Body_style FROM Corvettes
WHERE Year > 1994
- An asterisk for the column names means all
columns
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
99
12.2 Intro to SQL (continued)
- The INSERT Command
- General form:
INSERT INTO table_name (col_name1, … col_namen)
VALUES (value1, …, valuen)
- The correspondence between column names and
values is positional
INSERT INTO Corvettes(Vette_id,
Body_style, Miles, Year, State)
VALUES (37, 'convertible', 25.5, 1986, 17)
- The UPDATE Command
- To change one or more values of a row in a table
- General form:
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
100
12.2 Intro to SQL (continued)
UPDATE table_name
SET col_name1 = value1,
…
col_namen = valuen
WHERE col_name = value
- The WHERE clause is the primary key of the row
to be updated
- Example:
UPDATE Corvettes
SET Year = 1996
WHERE Vette_id = 17
- The DELETE Command
- Example:
DELETE FROM Corvettes
WHERE Vette_id = 27
- The WHERE clause could specify more than one
row of the table
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
101
12.2 Intro to SQL (continued)
- Joins
- If you want all cars that have CD players, you
need information from two tables, Corvettes and
Equipment
- SELECT can build a temporary table with info
from two tables, from which the desired results
can be obtained - this is called a join of the two
tables
- A SELECT that does a join operation specifies two
tables in its FROM clause and also has a
compound WHERE clause
- For our example, we must have three WHERE
conditions
1. Vette_ids from Corvettes and
Corvettes_Equipment must match
2. Equip from Corvette_Equipment must match
the Equip_id from Equipment
3. The Equip from Equipment must be CD
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
102
12.2 Intro to SQL (continued)
SELECT Corvettes.Vette_id,
Corvettes.Body_style, Corvettes.Miles,
Corvettes.Year, Corvettes.State,
Equipment.Equip
FROM Corvettes, Equipment
WHERE Corvettes.Vette_id =
Corvettes_Equipment.Vette_id
AND Corvettes_Equipment.Equip =
Equipment.Equip_id
AND Equipment.Equip = 'CD'
This query produces
VETTE_ID BODY_STYLE
MILES YEAR
STATE EQUIP.
1
2
8
9
10
18.0
58.0
17.0
17.0
50.0
4
7
5
5
7
coupe
hatchback
convertible
hardtop
hatchback
Chapter 7
1997
1996
1999
2000
1995
© 2001 by Addison Wesley Longman, Inc.
CD
CD
CD
CD
CD
103
12.3 Architectures for Database Access
- Client-Server Database Architectures
- Usual database client tasks:
- Provide a way for users to submit queries
- Run applications that use the results of queries
- Display results of queries
- Database server task:
- Implement a data manipulation language, which
can directly access and update the database
- A two-tier system has clients that are connected
directly to the server
- Potential problems with a two-tier system:
- Because the relative power of clients has grown
considerably, we could shift processing to the
client, but then maintaining data integrity is
difficult
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
104
12.3 Architectures for Database Access
(continued)
- One solution to the problems of two-tier systems
is to add a component in the middle - create a
three-tier system
- For Web-based database access, the middle tier
can run applications (client just gets results)
Client
Middle tier
JDBC
Database
server
- Database Access with Embedded SQL
- SQL commands are embedded in programs
written in a host programming language, whose
compiler is extended to accept some form of
SQL commands
- Advantage:
- One package has computational support of the
programming language, as well as database
access with SQL
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
105
12.3 Architectures for Database Access
(continued)
- Disadvantage (of embedded SQL):
- Portability among database systems
- Microsoft Access Architecture
- A tool to access any common database structure
- Use either the Jet database engine, or go through
the Other Database Connectivity (ODBC)
standard
- ODBC is an API for a set of objects and
methods that are an interface to different
databases
- Database vendors provide ODBC drivers for
their products – the drivers implement the
ODBC objects and methods
- An application can include SQL statements
that work for any database for which a driver
is available
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
106
12.3 Architectures for Database Access
(continued)
- The Java JDBC Architecture:
- Related to both embedded languages and to
ODBC
- JDBC is a standard protocol that can be
implemented as a driver for any database system
- JDBC allows SQL to be embedded in Java
applications, applets, and servlets
- JDBC has the advantage of portability over
embedded SQL
- A JDBC application will work with any database
system for which there is a JDBC driver
12.4 Approaches to Using JDBC
- SQL commands are issued against a database
system through JDBC methods
- JDBC interfaces are in the java.sql package
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
107
12.4 Approaches to Using JDBC
(continued)
- The classes that implement the JDBC interfaces
serve as the client
- Configurations for using JDBC:
1. The JDBC-ODBC bridge converts JDBC
database interactions to ODBC database
interactions
- Not meant for commercial applications
2. If the target database has a JDBC driver, a
two-tier configuration can be used
- The application talks to the JDBC driver, which
talks to the database server
- Disadvantage: Every database needs its own
driver, and every driver that the client may use
must be installed on the client machine
3. Use a third-tier computer to run middleware
- Client runs as a client of the middleware
server, which talks to the database server
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
108
12.4 Approaches to Using JDBC
(continued)
3. Use a third-tier computer to run middleware
(continued)
- Advantages:
a. The middleware supports all databases, so
even though vendors may implement JDBC
interfaces differently (extensions), the
application on the client is database
independent
b. The client never needs to connect directly
to the database server, which allows
applets to be used for JDBC database
access
12.5 Java JDBC Applications
- We use the PointBase system, from
www.pointbase.com
- Connecting the application to the driver
- The getConnection method of DriverManager,
which select the correct driver from those that
are registered
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
109
12.5 Java JDBC Applications (continued)
- The general form of a reference to a database for
the connection operation is:
jdbc:subprotocol_name:more_info
- The “subprotocol” specifies the driver
- For the JDBC-ODBC bridge, it is odbc
- For the PointBase, it is pointbase
- The “more info” part depends on the specific
database being used
- If the database is local, it is just the name of
the database
- Otherwise, it is the URL of the database
- Two ways to register a database driver:
1. The general way is to have the system
property jdbc.drivers maintain a list of
registered drivers
- Add one with
jdbc.drivers = com.pointbase.jdbc.jbdcDriver;
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
110
12.5 Java JDBC Applications (continued)
2. Manual registration, using the forName method
of the Class class, passing the name of the
driver
Class.forName(
"com.pointbase.jdbc.jdbcDriver");
- The actual connection is made by creating a
Connection object with the getConnection
method of the DriverManager class
DriverManager.getConnection(database_address,
database_user_id, password)
- If the application owner owns the database,
public can be used for both the user id and the
password
myCon = DriverManager.getConnection(
"jdbc:pointbase:vette", "public", "public");
- SQL commands through JDBC
- First, you need a Statement object
Statement myStmt = myCon.createStatement();
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
111
12.5 Java JDBC Applications (continued)
- SQL commands are String objects
final String sql_com = "UPDATE Corvettes " +
"Year = 1991 WHERE Vette_id = 7");
- Categories of SQL commands
- Action - INSERT, UPDATE, DELETE,
CREATE TABLE, and DROP TABLE
- Query - SELECT
- The action commands are executed with the
executeUpdate method of Statement
myStmt.executeUpdate(sql_com);
- Returns the number of affected rows
- A SELECT is executed by sending it as the actual
parameter to the executeQuery method of
Statement
- The executeQuery method returns an object of
class ResultSet
- Get rows from ResultSet with next iterator
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
112
12.5 Java JDBC Applications (continued)
ResultSet result;
final String sql_com =
"SELECT * FROM Corvettes WHERE Year <= 1990"
result = myStmt.executeQuery(sql_com);
while(result.next()) {
// access and process the current element
}
- Information is extracted from the ResultSet object
with an access method, for which there is one for
each data type
e.g., If an extracted row is
3, "convertible", 13.5, 2001, 1
String style;
style = result.getString("Body_style");
or
style = result.getString(2);
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
113
12.5 Java JDBC Applications (continued)
1993-2001 Corvettes For Sale
Vette_id
Body_style
Miles
Year
State
1
2
3
6
8
9
10
coupe
hatchback
convertible
hardtop
convertible
hardtop
hatchback
18.0
58.0
13.5
15.0
17.0
17.0
50.0
1997
1996
2001
2000
1999
2000
1995
4
7
1
2
5
5
7
- Metadata - to get table and column names from a
database
- Two kinds of metadata:
1. Metadata that describes the database
(tables and columns)
2. Metadata that describes a ResultSet object
- A Connection method, getMetaData, creates an
object of class DatabaseMetaData
DatabaseMetaData dbmd = myCon.getMetaData();
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
114
12.5 Java JDBC Applications (continued)
- The getTables method of DatabaseMetaData takes
four parameters, only one of which is necessary
(the string, "TABLE")
String tbl[] = {"TABLE"};
DatabaseMetaData dbmd = myCon.getMetaData();
result = dbmd.getTables(
null, null, null, tbl);
System.out.println(
"The tables in the database are: \n\n");
while (result.next()) {
System.out.println(result.getString(3));
}
- Output from this:
The tables in this database are:
CORVETTES
CORVETTES_EQUIPMENT
EQUIPMENT
STATES
- Metadata about query results has a different
structure than general database metadata
- ResultSetMetaData object
Chapter 7
© 2001 by Addison Wesley Longman, Inc.
115
12.5 Java JDBC Applications (continued)
ResultSetMetaData resultMd =
result.getMetaData();
- We can get the number of columns, their names,
types, and sizes from the resultMd object, using
its methods
- getColumnCount returns the number of columns
- getColumnLable(i) returns the column names
// Create an object for the metadata
ResultSetMetaData resultMd =
result.getMetaData();
// Loop to fetch and display the column names
for (int i = 1; i" <= resultMd.getColumnCount();
i++) {
String columnName =
resultMd.getColumnLabel(i);
System.out.print(columnName + "\t");
}
System.out.println("\n");
Output:
Vette_id
Body_style
Chapter 7
Miles
Year
State
© 2001 by Addison Wesley Longman, Inc.
116