Title: XML and JavaScript Lecture 10
1XML and JavaScriptLecture 10
- cs193i Internet Technologies
- Summer 2004
- Stanford University
2Administrative Stuff
- Lab 4 due August 9
- HW 4 due August 11
- Final exam
- Friday, 8/13
- Gates B03
- 7-10pm
3What 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
4A JSP File
5Expression 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
6EL Examples
- ltinput namefirstName valuecustomer.firstNam
egt - ltcout valueorder.amount 5/gt
- order.amount 5
- order'amount' 5
7(No Transcript)
8XML
- XML ? Extensible Markup Language
- Just a text file, with tags, attributes, free
text... looks much like HTML
9Purpose
- Used to create special-purpose markup languages
- Facilitates sharing of structured text and
information across the Internet.
10XML 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"
11XML 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!
12Apple Safari Bookmarks
13Property List Editor
14Apple Bookmarks
15Document Data Type
16XML 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
17Special Characters
- lt lt
- gt gt
- amp
- " quot
- ' apos
18Organization 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
19XML Tree
- ltpersongt
- ltnamegt
- ltfirstgtHanslt/firstgt
- ltlastgtGruberlt/lastgt
- lt/namegt
- ltidgt123456lt/idgt
- ltusernamegthanslt/usernamegt
- lt/persongt
20Sub-Tags vs. Attributes
- Sub-Tags
- ltdotgt
- ltxgt13lt/xgt
- ltygt57lt/ygt
- lt/dotgt
- Attributes
- ltdot x"13" y"57"/gt
21When 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
22When 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
23XML 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
24XML and Java
- http//java.sun.com/xml/index.jsp
- Java API for XML...
- Binding (JAXB) -- for working w/ Schemas
- Processing (JAXP) -- for Parsing!
25JAXP 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
26SAX
- 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/
27mydots.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
28SAX 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"
29DOM
- 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
30DOM 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
31SAX 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
32Other Java Parsers
- There are other free parsers out there, that use
either SAX or DOM strategies... - nanoxml
- JDOM
33XML Uses
- Config Files
- Apple Property List
- Data Files
- SVG
- Messages
- SOAP
34Strengths 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)
35Five Minute Break
36JavaScript
- Invented by Netscape Communications
- Cross Platform, Object-based, Scripting Language
- ECMAScript (ECMA-262)
37JavaScript
HTTP Request
HTTP Response
Client runs JavaScript
HTML file with embedded JavaScript
38JavaScript
- All Client Side
- Can
- Adjust HTML
- Open Windows, Resize Windows
- Animations, Play Sounds
- Cannot
- Access File System
- Do Networking
39JavaScript
- Advantages
- Better User Experience
- (2X Latency)
- Disadvantages
- Thicker Client
- Possible Abuse
40JavaScript 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
41Generate Dynamic HTML
... ltBODYgt ...Regular HTML Here.... ltSCRIPT
TYPE"text/javascript"gt lt!-- BUILD HTML
HERE!!! //--gt lt/SCRIPTgt ...More Regular
HTML.... lt/BODYgt
42JavaScript 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.
43document.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
44document.write(String)
45document.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
46ltBODYgt 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
47document.write(String)
48Monitor User Events
- ltinput type"button" value"Don't Click Me!"
onClick"dontClick()"/gt - function dontClick()
- alert("I told ya not to click!")
-
49Monitor User Events
www.devguru.com
50DOM
- JavaScript is Object-Oriented
- JavaScript Interacts with Document Object Model
of Browser - DOM Not Totally Standardized
51Objects
http//www.devguru.com
52Arrays or Objects?
- The Same!
- a.foo ltgt a"foo" ltgt ax
- a2 cannot be accessed as a.2
53Global Functions
- escape(string)
- unescape(string)
- Safe Strings
- ABCDEFGHIJKLMNOPQRSTUVWXYZ
- abcdefghijklmnopqrstuvwxyz
- 1234567890
- _at_ - _ . /
- Unsafe Strings gt 20, 5c, etc...
54Communicating with User
- Alert window.alert("Hello!")
- Confirm window.confirm("Delete files? D")
- Status Bar window.status "Hi!"
55lthtmlgt 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
57Fear Example
58Quotes 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
59ltscript 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)
62JavaScript Summary
- Good For Simple Things
- Save RT Latency
- Bad when Abused
- Popups!!!
- Don't Always Rely on It
- DOMs not standardized