XML and JavaScript Lecture 10 - PowerPoint PPT Presentation

1 / 62
About This Presentation
Title:

XML and JavaScript Lecture 10

Description:

SAX vs. DOM. SAX -- Event Driven, Serial Access, Element by Element ... DOM -- Read in whole XML structure, CPU & memory intensive ... – PowerPoint PPT presentation

Number of Views:79
Avg rating:3.0/5.0
Slides: 63
Provided by: kelly113
Category:
Tags: javascript | xml | dom | lecture

less

Transcript and Presenter's Notes

Title: XML and JavaScript Lecture 10


1
XML and JavaScriptLecture 10
  • cs193i Internet Technologies
  • Summer 2004
  • Stanford University

2
Administrative Stuff
  • Lab 4 due August 9
  • HW 4 due August 11
  • Final exam
  • Friday, 8/13
  • Gates B03
  • 7-10pm

3
What is JSP?
  • Separate computation from presentation
  • Presentation JSP
  • Computation Servlet
  • Mostly HTML page, with extension .jsp
  • Include JSP tags to enable dynamic content
    creation
  • Translation JSP ? Servlet class
  • Compiled at request time

4
A JSP File
5
Expression Language
  • Makes syntax short and readable, like JavaScript
  • expression
  • Arithmetic
  • 1.2 2.3 ? 3.5
  • Comparisons
  • 4.0 gt 3 ? true
  • Implicit Objects
  • param.foo ? JSP 2.0
  • param"foo" ? JSP 2.0
  • Functions
  • myreverse(myreverse(param"foo")) ? JSP 2.0

6
EL Examples
  • ltinput namefirstName valuecustomer.firstNam
    egt
  • ltcout valueorder.amount 5/gt
  • order.amount 5
  • order'amount' 5

7
(No Transcript)
8
XML
  • XML ? Extensible Markup Language
  • Just a text file, with tags, attributes, free
    text... looks much like HTML

9
Purpose
  • Used to create special-purpose markup languages
  • Facilitates sharing of structured text and
    information across the Internet.

10
XML Describes Data
  • DTD -- formal description of the class of XML
    document your file adheres to (like file
    extension)
  • Buzzword DTD is one way to describe XML "Schema"
    (grammar). There are other ways...
  • XML Structure Facilitates Parsing of Data
  • Two Apps still have to agree on what the meaning
    of the "descriptive tags"

11
XML Nested Tags
  • Like a tree, each element is contained inside a
    parent element
  • Each element may have any number of attributes

ltbookgtlt/bookgt
ltchaptergtlt/chaptergt pages30
ltchaptergtlt/chaptergt
ltparagtlt/paragt
lt/brgt
lttitlegtlt/titlegt
ltfiguregtlt/figuregt

This is some text!
12
Apple Safari Bookmarks
13
Property List Editor
14
Apple Bookmarks
15
Document Data Type
16
XML Structure
  • Nested Tags
  • Here's some text ltredgtsurrounded ltimportantgtby
    tagslt/importantgtlt/redgt
  • Empty Tags
  • lttaggtlt/taggt ? lttag/gt
  • Attributes -- Variable Value Bindings in the Tag
  • ltdot x"72" y"13"/gt
  • Free Text
  • ltdot x"1" y"1"gtI'm free!!!lt/dotgt

17
Special Characters
  • lt lt
  • gt gt
  • amp
  • " quot
  • ' apos

18
Organization Strategies
  • XML Text -- blocks of free text with tags to mark
    sections
  • ltfoogtAnd here is some ltbgttextlt/bgtlt/foogt
  • XML Tree -- nested tags, only leaf-nodes have
    free text

19
XML Tree
  • ltpersongt
  • ltnamegt
  • ltfirstgtHanslt/firstgt
  • ltlastgtGruberlt/lastgt
  • lt/namegt
  • ltidgt123456lt/idgt
  • ltusernamegthanslt/usernamegt
  • lt/persongt

20
Sub-Tags vs. Attributes
  • Sub-Tags
  • ltdotgt
  • ltxgt13lt/xgt
  • ltygt57lt/ygt
  • lt/dotgt
  • Attributes
  • ltdot x"13" y"57"/gt

21
When to use Attributes
  • Whenever Possible
  • Sub-Data is short simple, and doesn't repeat
  • ltdot x"13" y"56"/gt
  • NOT
  • ltdots x1"13" y1"56" x2"14 y2"67 x3"56"
    y3"100" ... /gt

22
When to use Tags
  • ltparentgt
  • ltchildgt...lt/childgt
  • ltchildgt...lt/childgt
  • ltchildgt...lt/childgt
  • lt/parentgt
  • ltdotsgt
  • ltdot x"13" y"15"/gt
  • ltdot x"1" y"3"/gt
  • ...
  • lt/dotsgt
  • ltdescriptiongtThis is a super long description
    that should be put between tags, as opposed to in
    an attribute... lt/descriptiongt

23
XML Example - Dots
Meaning (1, 2) (3, 4) (6, 5) (7, 8) (9, 10)
  • lt?xml version"1.0" encoding"UTF-8"?gt
  • ltdotsgt
  • ltdot x"1" y"2" /gt
  • ltdot x"3" y"4" /gt
  • ltflipgt
  • ltdot x"5" y"6" /gt
  • ltflipgt
  • ltdot x"7" y"8" /gt
  • lt/flipgt
  • lt/flipgt
  • ltdot x"9" y"10" /gt
  • lt/dotsgt

24
XML and Java
  • http//java.sun.com/xml/index.jsp
  • Java API for XML...
  • Binding (JAXB) -- for working w/ Schemas
  • Processing (JAXP) -- for Parsing!

25
JAXP Parsing Strategies
  • SAX -- Simple API for XML
  • Simple Parser
  • DOM -- Document Object Model
  • Represent XML Doc as Tree of Nodes in Memory

http//java.sun.com/j2ee/1.4/docs/tutorial/doc/JAX
PIntro.html
26
SAX
  • Subclass DefaultHandler
  • Implement Notification Methods ("Callbacks")
  • startElement(...) // handles open tag lta_taggt
  • endElement(...) // handles close tag lt/a_taggt
  • characters(...) // handles stuff in between
  • Read in the XML File

http//sax.sourceforge.net/
27
mydots.xml
  • ltdotsgt
  • ltdot x"81" y"67" /gt
  • ltdot x"175" y"122" /gt
  • ltflipgt
  • ltdot x"175" y"122" /gt
  • ltdot x"209" y"71" /gt
  • lt/flipgt
  • ltdot x"209" y"71" /gt
  • ltflipgt
  • ltflipgtltdot x"133" y"877"gtMy Favorite
    Dot!lt/dotgtlt/flipgt
  • ltdot x"1" y"2"/gt
  • lt/flipgt
  • lt/dotsgt

28
SAX Example
SAXParserFactory factory SAXParserFactory.newIns
tance() SAXParser saxParser factory.newSAXParse
r() saxParser.parse( new BufferedInputStream(n
ew FileInputStream( new File(argv0))), new
XMLDotReader())
  • XMLDotReader Class
  • Maintains flip state in boolean
  • extends DefaultHandler
  • overrides startElement(...)
  • Check if dot tag or flip tag
  • Do stuff, accordingly
  • overrides endElement(...)
  • If flip tag... "unflip"

29
DOM
  • Get a DocumentBuilder
  • Read in an XML File,
  • get a Document object
  • Traverse the Document
  • object and do stuff
  • http//java.sun.com/j2ee/1.4/docs/tutorial/doc/JAX
    PDOM.htmlwp79996

30
DOM Example
// Step 1 create a DocumentBuilderFactory //
and setNamespaceAware DocumentBuilderFactory dbf
DocumentBuilderFactory.newInstance() dbf.setNa
mespaceAware(true) // Step 2 create a
DocumentBuilder DocumentBuilder db
dbf.newDocumentBuilder() // Step 3 parse the
input file to get a Document object Document doc
db.parse(new File(filename)) Node n (Node)
doc ... int type n.getNodeType() for (Node
child n.getFirstChild() child!null childchi
ld.getNextSibling()) ...
http//java.sun.com/developer/earlyAccess/xml/exam
ples/DOMEcho/DOMEcho.java
31
SAX vs. DOM
  • SAX -- Event Driven, Serial Access, Element by
    Element
  • Preferred for Server Side Apps
  • DOM -- Read in whole XML structure, CPU memory
    intensive
  • Ideal for interactive apps (Thick Clients)
    allows interactive editing of XML structure in
    memory

32
Other Java Parsers
  • There are other free parsers out there, that use
    either SAX or DOM strategies...
  • nanoxml
  • JDOM

33
XML Uses
  • Config Files
  • Apple Property List
  • Data Files
  • SVG
  • Messages
  • SOAP

34
Strengths and Weaknesses
  • Strengths
  • Just Text Compatible with Web/Internet
  • Protocols
  • Human Machine Readable
  • Represents most CS datastructures well
  • Strict Syntax ? Parsing Fast and Efficient
  • Weaknesses
  • Verbose/Redundant
  • Trouble modeling overlapping data structures (non
    hierarchical)

35
Five Minute Break
36
JavaScript
  • Invented by Netscape Communications
  • Cross Platform, Object-based, Scripting Language
  • ECMAScript (ECMA-262)

37
JavaScript
HTTP Request
HTTP Response
Client runs JavaScript
HTML file with embedded JavaScript
38
JavaScript
  • All Client Side
  • Can
  • Adjust HTML
  • Open Windows, Resize Windows
  • Animations, Play Sounds
  • Cannot
  • Access File System
  • Do Networking

39
JavaScript
  • Advantages
  • Better User Experience
  • (2X Latency)
  • Disadvantages
  • Thicker Client
  • Possible Abuse

40
JavaScript Basics
  • ltscriptgt section in HTML runs on document load
  • No type declarations
  • undefined if not given a value
  • Global variables by default
  • var makes them local

41
Generate Dynamic HTML
... ltBODYgt ...Regular HTML Here.... ltSCRIPT
TYPE"text/javascript"gt lt!-- BUILD HTML
HERE!!! //--gt lt/SCRIPTgt ...More Regular
HTML.... lt/BODYgt
42
JavaScript and Browser
  • document HTML document
  • document.name named element in document
  • document.images array of images
  • document.forms array of forms
  • Ways to access window, cookies, etc.

43
document.write(String)
ltHTMLgt ltHEADgtltTITLEgtHello!lt/TITLEgtlt/HEADgt ltBODYgt
ltH1gt First JavaScript Page lt/H1gt ltSCRIPT
TYPE"text/javascript"gt lt!-- document.write("ltH
R/gt") document.write("Hello WWW!") document.
write("ltHR/gt") //--gt lt/SCRIPTgt lt/BODYgt lt/HTMLgt
44
document.write(String)
45
document.write(String)
ltHTMLgt ltHEADgtltTITLEgtHello!lt/TITLEgt ltSCRIPT
TYPE"text/javascript"gt lt!-- function
referringPage() if (document.referrer.length
0) return("ltIgtnonelt/Igt") else
return(document.referrer) //--gt
lt/SCRIPTgt lt/HEADgt
46
ltBODYgt ltH1gt Extracting Info! lt/H1gt ltSCRIPT
TYPE"text/javascript"gt lt!-- document.writeln("
ltULgt") document.writeln("ltLIgt"
document.location) document.writeln("ltLIgt
referringPage()) document.writeln("ltLIgt"
navigator.appName) document.writeln("lt/ULgt")
//--gt lt/SCRIPTgt lt/BODYgt lt/HTMLgt
47
document.write(String)
48
Monitor User Events
  • ltinput type"button" value"Don't Click Me!"
    onClick"dontClick()"/gt
  • function dontClick()
  • alert("I told ya not to click!")

49
Monitor User Events
www.devguru.com
50
DOM
  • JavaScript is Object-Oriented
  • JavaScript Interacts with Document Object Model
    of Browser
  • DOM Not Totally Standardized

51
Objects
http//www.devguru.com
52
Arrays or Objects?
  • The Same!
  • a.foo ltgt a"foo" ltgt ax
  • a2 cannot be accessed as a.2

53
Global Functions
  • escape(string)
  • unescape(string)
  • Safe Strings
  • ABCDEFGHIJKLMNOPQRSTUVWXYZ
  • abcdefghijklmnopqrstuvwxyz
  • 1234567890
  • _at_ - _ . /
  • Unsafe Strings gt 20, 5c, etc...

54
Communicating with User
  • Alert window.alert("Hello!")
  • Confirm window.confirm("Delete files? D")
  • Status Bar window.status "Hi!"

55
lthtmlgt ltheadgt lttitlegtJS Demolt/titlegt
ltscript language"JavaScript"gt function
hello(greeting) var str greeting
"!!!" alert(str) count 0
function upCount() count
alert(count) function noFear() var
fear document.affirm.fear.value if
(!document.affirm.mockMode.checked)
alert("No " fear " to be seen around here!")
else var mock "Being
afraid of " fear " is stupid!"
window.status mock document.affirm.mock
.value mock lt/scriptgt lt/headgt
56
ltbodygt ltpgt ltbutton onClick"hello('hi
there')" gtSay Hellolt/buttongt ltbrgtltbutton
onClick"upCount()" gtCountlt/buttongt ltbrgtlta
onClick"alert('holy !')"gtoopslt/agt ltpgt
Thing you are afraid of... ltform nameaffirmgt
ltinput typetext namefeargt ltpgtltinput
typebutton onClick"noFear()" value"No Fear"gt
Mock modeltinput typecheckbox namemockModegt
ltpgtltinput typetext size40 namemockgt lt/formgt
lt/bodygt lt/htmlgt
57
Fear Example
58
Quotes Example
  • Text Box
  • ltform nameform1
  • onsubmit"setQuotes('form1') return false"gt
  • Search ltinput typetext nametarget gt
  • ltinput typesubmit valueSubmitgt
  • lt/formgt
  • Text Box
  • ltinput typetext nametarget
  • onKeyUp"setQuotes('form2')"gt

59
ltscript language"JavaScript"gt // We allocate a
global array and fill it with the quote
data. lines new Array() lines.push("Everybody'
s always telling me one thing and out
the other.") lines.push("Even a fish could stay
out of trouble if it would just learn to keep its
mouth shut.") lines.push("Beware the lollipop of
mediocrity -- lick it once and you suck
forever.") lines.push("We don't have time to
stop for gas -- we're already late.") lines.push(
"By doing just a little each day, I can gradually
let the task overwhelm me.") lines.push("Being
powerful is like being a lady. If you have
to tell people you are, you aren't.") lines.push(
"Never attribute to malice that which
can satisfactorily be explained by
incompetence.")
60
// Search for an element with the given id and
set its innerHTML to // the given text. function
setText(id, text) var node
document.getElementById(id) if (node !
null) node.innerHTML text
//node.childNodes0.data text //
alternative for some simple tags // Given
the name of a form, access the target field
within that // form and using its target text,
generate the quote list and put // it into the
result tag. function setQuotes(form_name)
// cute use instead of . to access the form
by name var target documentform_name.targe
t.value var contents "" target
target.toLowerCase() for (var i in lines)
if (linesi.toLowerCase().indexOf(target)!-
1) contents contents "ltligt"
linesi "\n"
setText("result", contents) lt/scriptgt
61
(No Transcript)
62
JavaScript Summary
  • Good For Simple Things
  • Save RT Latency
  • Bad when Abused
  • Popups!!!
  • Don't Always Rely on It
  • DOMs not standardized
Write a Comment
User Comments (0)
About PowerShow.com