7.1 JavaScript Execution Environment - PowerPoint PPT Presentation

About This Presentation
Title:

7.1 JavaScript Execution Environment

Description:

Title: Chapter 1 Author: Computer Science Department Last modified by: michael hirsch Created Date: 10/4/1995 10:44:44 AM Document presentation format – PowerPoint PPT presentation

Number of Views:430
Avg rating:3.0/5.0
Slides: 117
Provided by: ComputerSc203
Category:

less

Transcript and Presenter's Notes

Title: 7.1 JavaScript Execution Environment


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 forms elements - Form elements
are usually referenced by name, but
this is a problem for radio buttons
2
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., ltinput type "text"
name "address"gt 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
3
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 functions name is assigned to the
object property associated with the event
at the HTML element - Dont use
document.write in an event handler, because
the output may go on top of the display
4
7.4 Events, Attributes, and Tags
Event Tag Attribute
abort onAbort blur
onBlur change onChange click
onClick error onError
focus onFocus load
onLoad mouseout onMouseOut
mouseover onMouseOver reset
onReset resize onResize
select onSelect submit
onSubmit unload onUnload - The
same attribute can appear in several different
tags e.g., The onClick attribute can be in
ltagt and ltinputgt --gt SHOW Tables 7.1
and 7.2 - Specifying a handler by assigning the
attribute onClick "alert('Mouse click!')"
onClick "myHandler()"
5
7.5 Using the load and unload Events - These
events are triggered when the loading or
unloading of a document is completed lt!-- This
is ch7_1.html --gt lthtmlgt ltheadgt lttitlegt onLoad
and onUnload event handlers lt/titlegt ltscript
language "JavaScript"gt // 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!") lt/scriptgt ltheadgt ltbody onLoad
"load_hello()" onUnload
"unload_goodbye()"gt lt/bodygt lt/htmlgt
6
  • 7.6 Event Handlers for Button Events
  • - Radio buttons
  • ltinput type "radio" name "button_group"
  • value "blue" onClick "handler()"gt
  • - Cant use the elements 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


7
7.6 Event Handlers for Button Events
(continued) --gt 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.elements0.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 --gt SHOW
ch7_2x.html
8
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)
9
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
10
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 --gt 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
11
  • 7.8 The navigator object
  • - Indicates which browser is being used
  • - Two useful properties
  • 1. The appName property has the browsers 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

12
  • 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


13
Chapter 8
  • Sebesta
  • Programming the
  • World Wide Web

14
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
15
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 ltbodygt ltform id
"myForm" gt ltinput type "button" id
"onButton"gt lt/formgt lt/bodygt
- The standard DOM address of the button can
be gotten with the getElementById method,
as in document.getElementById("onButto
n").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
16
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
...
17
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
ltp style "position absolute left
50px top 100 px"gt --gt 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
18
8.2 Element Positioning (continued) --gt 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 --gt
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
19
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 --gt 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
elements DOM address is dom if
(dom.visibility "visible"
dom.visibility "show") dom.visibility
"hidden" else dom.visibility
"visible" --gt SHOW showHide.html

20
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 ltinput type "text" size
"10" name "background"
onchange "setColor('background',
this.value)"gt - The
actual parameter this.value works because
at the time of the call, this is a reference to
the text button
21
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
--gt 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' --gt SHOW dynLink.html and Figures 8.6
8.7
22
8.6 Dynamic Content - The content of an HTML
element is addressed with the value property
of its associated JavaScript object --gt 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
23
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 lta href "JAVASCRIPTfun()"gt
- 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 --gt SHOW stacking.html and
Figures 8.9, 8.10, 8.11
24
Chapter 9
  • Sebesta
  • Programming the
  • World Wide Web

25
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
26
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
27
9.2 Primary Applet Activities - Browser
actions a. Download and instantiate the
applet class b. Call the applets init
method c. Call the applets 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 applets stop
method - When the browser is stopped
by the user, the browser calls the
applets destroy method - Every applet must
override at least one of the three methods,
init, start, or paint (paint is inherited
from Component)
28
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)
29
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
30
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(myF
ont) grafObj.drawString(
"Welcome to my home page!", 50, 50)
9.4 The ltobjectgt Tag - Used to specify an
applet in an HTML document - Creates a space in
the document display for applet output (like
ltimggt does)

31
9.4 The ltobjectgt Tag (continued) ltobject
codetype "application/java" code
"applet_class_file" width "applet
display width" height "applet
display height"gt lt/objectgt - The display
width and height are in pixels - The
applet_class_file is the compiled version lt!--
ch9_2.html To test the applet,
welcomeMessage_2 --gt lthtmlgt ltheadgt
lttitlegt Test welcomeMessage_2 lt/titlegt lt/headgt
ltbodygt ltobject codetype "application/java"
code "welcomeMessage_2.class"
width "500" height "100"gt
lt/objectgt lt/bodygt lt/htmlgt
32
9.4 The ltobjectgt Tag (continued)
9.5 Applet Parameters - Applets can be sent
parameters through HTML, using the ltparamgt
tag and its two attributes, name and value
- Parameter values are strings - e.g.,
ltparam name "fruit" value "apple"gt - The
applet gets the parameter values with
getParameter, which takes a string parameter,
which is the name of the parameter
String myFruit getParameter("fruit")
33
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
34
9.5 Applet Parameters (continued) ltbodygt
ltobject codetype "application/java"
code "welcomeMessage_3.class" width
"500" height "100"gt ltparam name
"size" value "35"gt lt/objectgt
lt/bodygt 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)
35
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.fillRoundRe
ct(120, 120, 60, 80,
40, 40)
36
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)
37
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
38
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.c
yan) - 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
39
  • 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")

40
  • 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

41
9.8 Interactive Applets (continued)
42
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)
43
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 ActionListene
r actionPerformed AdjustmentListener adjustmentVa
lueChanged ItemListener itemStateChanged TextList
ener textValueChanged - The methods to
register the listener is the interface name
with add prepended - e.g.,
button1.addActionListener(myPanel)
44
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) ) --gt SHOW
RadioB.java
45
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
46
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 --gt SHOW Names.java, output, delayer, and
output - Thread States - New - created, but
start hasnt 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
47
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
48
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
objects 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
49
Chapter 10
  • Sebesta
  • Programming the
  • World Wide Web

50
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
HTMLs using SGML)
51
10.1 Introduction (continued) - Problem with
using SGML - Its 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 - Thats 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
52
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
lt?xml version "1.0"?gt
53
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
54
10.2 The Syntax of XML (continued) -
Nested tags are better than attributes, because
attributes cannot describe structure and
the structural complexity may grow lt!-- A
tag with one attribute --gt ltpatient name
"Maggie Dee Magpie"gt ... lt/patientgt lt!-- A
tag with one nested tag --gt ltpatientgt ltnamegt
Maggie Dee Magpie lt/namegt ... lt/patientgt lt!--
A tag with one nested tag, which contains
three nested tags --gt ltpatientgt ltnamegt
ltfirstgt Maggie lt/firstgt ltmiddlegt Dee
lt/middlegt ltlastgt Magpie lt/lastgt lt/namegt
... lt/patientgt
55
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!)

56
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 lt gt
gt amp "
quot ' apos - The user can
only define entities in a DTD
57
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 lt!keyword
gt - There are four possible declaration
keywords ELEMENT, ATTLIST, ENTITY, and
NOTATION
58
10.4 Data Type Definitions (continued) -
Declaring Elements - Element declarations
are similar to BNF - An element declaration
specifies the elements 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 lt!ELEMENT element_name (list of
child names)gt e.g., lt!ELEMENT memo
(from, to, date, re, body)gt memo fro
m to date re body
59
10.4 Data Type Definitions (continued) -
Declaring Elements (continued) - Child
elements can have modifiers, , , ?
e.g., lt!ELEMENT person
(parent, age, spouse?, sibling)gt - 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 lt!ELEMENT name
(PCDATA)gt - Declaring Attributes -
General form lt!ATTLIST el_name at_name
at_type defaultgt
60
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., lt!ATTLIST car doors
CDATA "4"gt lt!ATTLIST car engine_type CDATA
REQUIREDgt lt!ATTLIST car price CDATA IMPLIEDgt
lt!ATTLIST car make CDATA FIXED "Ford"gt ltcar
doors "2" engine_type "V8"gt ... lt/cargt
61
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 lt!CDATA content gt
e.g., instead of Start gt
gt gt gt HERE
lt lt lt lt use
lt!CDATAStart gtgtgtgt HERE ltltltltgt - If
the CDATA content has an entity reference,
it is taken literally
62
10.4 Data Type Definitions (continued) -
Declaring Entities (continued) - General
form of declaration lt!ENTITY
entity_name "entity_value"gt e.g.,
lt!ENTITY jfk "John Fitzgerald Kennedy"gt
- A reference jfk - If the entity value
is longer than a line, define it in a
separate file (an external text entity)
lt!ENTITY entity_name SYSTEM "file_location"gt --gt
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
63
10.4 Data Type Definitions (continued) -
Internal DTDs lt!DOCTYPE root_name
gt - External DTDs lt!DOCTYPE
XML_doc_root_name SYSTEM

DTD_file_namegt --gt 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 dont cover them because the popular
browsers dont support them, yet
64
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
ltelement_name xmlnsprefix URIgt -
The prefix is a short name for the namespace,
which is attached to names from the
namespace in the XML document ltgmcars
xmlnsgm "http//www.gm.com/names"gt -
In the document, you can use ltgmpontiacgt -
Purposes of the prefix 1. Shorthand
2. URI includes characters that are illegal in XML
65
10.5 Namespaces (continued) - Can declare two
namespaces on one element ltgmcars xmlnsgm
"http//www.gm.com/names" xmlnshtml
"http//www.w3.org/TR/REC-html40"gt - 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 --gt SHOW Figure 10.2 --gt SHOW
Figure 10.3
66
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 lt?xml-stylesheet
type "text/css" href
"mydoc.css"?gt --gt 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
67
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 lt?xmlstylesheet type
"text/xsl" href "XSL style
sheet"?gt - An example lt?xml version
"1.0"?gt lt!-- xslplane.xml --gt
lt?xmlstylesheet type "text/xsl"
href "xslplane.xsl" ?gt ltplanegt
ltyeargt 1977 lt/yeargt ltmakegt Cessna lt/makegt
ltmodelgt Skyhawk lt/modelgt ltcolorgt Light
blue and white lt/colorgt lt/planegt
68
10.8 XML Transformations and Style Sheets
(continued) - An XSLT style sheet is an XML
document with a single element, stylesheet,
which defines namespaces ltxslstylesheet
xmlnsxsl "http//www.w3.org/1999/XSL
/Format"gt - 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 ltxsltemplate match "/"gt -
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
69
10.8 XML Transformations and Style Sheets
(continued) ltspan style "font-size 14"gt
Happy Easter! lt/spangt -
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 ltxslvalue-of select
CAR/ENGINE" /gt - The value of select can be
any branch of the document tree --gt SHOW
xslplane.xsl and Figure 10.5 - The XSLT
for-each element - Used when an XML document
has a sequence of the same elements --gt
SHOW xslplanes.xml --gt SHOW xslplanes.xsl
Figure 10.6
70
Chapter 11
  • Sebesta
  • Programming the
  • World Wide Web

71
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
72
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/tu
lips.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
73
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
74
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
75
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
www.bloomers.com
76
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 webguy_at_www.bloomers.com
- DocumentRoot - set the document root address
- Default is /usr/local/etc/httpd/htdo
cs - If it is elsewhere, tell Apache
with DocumentRoot
/local/webdocs

77
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/bush
es/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
/cgi-bin/ /usr/local/etc/httpd
/cgi-bin/

78
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/we
b/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 index.html
contents.html
79
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
80
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
81
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
82
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)
83
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
84
  • 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

85
11.6 A Survey Example --gt 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
86
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"))
87
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 --gt Show the servlet,
Survey.java --gt Show the results of running
Survey
88
11.7 Storing
Write a Comment
User Comments (0)
About PowerShow.com