0% found this document useful (0 votes)
272 views

XML Javascript

This document discusses JavaScript and XML. It begins with administrative announcements about assignments and exams. It then provides an overview of JSP, expression language, and examples of using EL to output dynamic content. It discusses XML structure, tags, attributes, and organization strategies. It covers parsing XML with SAX and DOM in Java and provides examples. It compares SAX and DOM and lists other Java parsers. Finally, it discusses JavaScript basics, using it to dynamically generate HTML, and accessing the browser document and window objects.

Uploaded by

anon-506495
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
272 views

XML Javascript

This document discusses JavaScript and XML. It begins with administrative announcements about assignments and exams. It then provides an overview of JSP, expression language, and examples of using EL to output dynamic content. It discusses XML structure, tags, attributes, and organization strategies. It covers parsing XML with SAX and DOM in Java and provides examples. It compares SAX and DOM and lists other Java parsers. Finally, it discusses JavaScript basics, using it to dynamically generate HTML, and accessing the browser document and window objects.

Uploaded by

anon-506495
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 62

XML and JavaScript

Lecture 10

cs193i – Internet Technologies


Summer 2004
Stanford University
Administrative Stuff
 Lab #4 due August 9
 HW #4 due August 11
 Final exam
 Friday, 8/13
 Gates B03

 7-10pm
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

A JSP File
Expression Language
 Makes syntax short and readable, like
JavaScript
 ${expression}
 Arithmetic
 ${1.2 + 2.3} → 3.5
 Comparisons
 ${4.0 >= 3} → true
 Implicit Objects
 ${param.foo} → JSP 2.0
 ${param["foo"]} → JSP 2.0
 Functions
 ${my:reverse(my:reverse(param["foo"]))} →
JSP 2.0
EL Examples
 <input name=“firstName”
value=“${customer.firstName}”>
 <c:out value=“${order.amount + 5}”/>
 ${order.amount + 5}
 ${order['amount'] + 5}
XML
 XML → Extensible Markup Language
 Just a text file, with tags, attributes,
free text... looks much like HTML
Purpose
 Used to create special-purpose
markup languages
 Facilitates sharing of structured text
and information across the Internet.
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"
XML Nested Tags
 Like a tree, each element is contained
inside a parent element
 Each element may have any number of
attributes
<book>…</book>

<chapter>…</chapter> <chapter>…</chapter> pages=“30”

<title>…</title> … <para>…</para> </br> <figure>…</figure>

This is some text!


Apple Safari Bookmarks
Property List Editor
Apple Bookmarks
Document Data Type
XML Structure
 Nested Tags
 Here's some text <red>surrounded
<important>by
tags</important></red>
 Empty Tags
 <tag></tag> → <tag/>
 Attributes -- Variable Value Bindings
in the Tag
 <dot x="72" y="13"/>
 Free Text
 <dot x="1" y="1">I'm free!!!</dot>
Special Characters
 < &lt;
 > &gt;
 & &amp;
 " &quot;
 ' &apos;
Organization Strategies
 XML Text -- blocks of free text with
tags to mark sections
<foo>And here is some
<b>text</b></foo>
 XML Tree -- nested tags, only leaf-
nodes have free text
XML Tree
<person>
<name>
<first>Hans</first>
<last>Gruber</last>
</name>
<id>123456</id>
<username>hans</username>
</person>
Sub-Tags vs. Attributes
 Sub-Tags
<dot>
<x>13</x>
<y>57</y>
</dot>
 Attributes
<dot x="13" y="57"/>
When to use Attributes
 Whenever Possible
 Sub-Data is short & simple, and
doesn't repeat
<dot x="13" y="56"/>
 NOT:
<dots x1="13" y1="56" x2="14“ y2="67
x3="56" y3="100" ... />
When to use Tags
 <parent>
<child>...</child>
<child>...</child>
<child>...</child>
</parent>
 <dots>
<dot x="13" y="15"/>
<dot x="1" y="3"/>
...
</dots>
 <description>This is a super long description that
should be put between tags, as opposed to in an
attribute... </description>
XML Example - Dots
<?xml version="1.0" encoding="UTF-8"?>
Meaning
<dots>
<dot x="1" y="2" /> (1, 2)
(3, 4)
<dot x="3" y="4" />
<flip>
<dot x="5" y="6" /> (6, 5)
<flip>
(7, 8)
<dot x="7" y="8" />
</flip>
</flip>
<dot x="9" y="10" /> (9, 10)
</dots>
XML and Java
 http://java.sun.com/xml/index.jsp
 Java API for XML...
 Binding (JAXB) -- for working w/
Schemas
 Processing (JAXP) -- for Parsing!
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/JAXPIntro.html
SAX
 Subclass
DefaultHandler
 Implement Notification
Methods ("Callbacks")
 startElement(...) //
handles open tag
<a_tag>
 endElement(...) //
http://sax.sourceforge.net/
handles close tag
</a_tag>
 characters(...) //
handles stuff in
mydots.xml
<dots>
<dot x="81" y="67" />
<dot x="175" y="122" />
<flip>
<dot x="175" y="122" />
<dot x="209" y="71" />
</flip>
<dot x="209" y="71" />
<flip>
<flip><dot x="133" y="877">My Favorite
Dot!</dot></flip>
<dot x="1" y="2"/>
</flip>
</dots>
SAX Example
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(
new BufferedInputStream(new FileInputStream(
new File(argv[0]))), 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"
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/JAXPDOM.html#wp79996
DOM Example
// Step 1: create a DocumentBuilderFactory
// and setNamespaceAware
DocumentBuilderFactory dbf =
DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(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;
child=child.getNextSibling()) {
...
}
ttp://java.sun.com/developer/earlyAccess/xml/examples/DOMEcho/DOMEcho.jav
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
Other Java Parsers
 There are other free parsers out
there, that use either SAX or DOM
strategies...
 “nanoxml”
 “JDOM”
XML Uses
 Config Files
 Apple Property List
 Data Files
 SVG
 Messages
 SOAP
Strengths and
Weaknesses
Strengths Weaknesses
 Just Text:  Verbose/Redundan
Compatible with t
Web/Internet  Trouble modeling
 Protocols overlapping data
 Human + Machine structures (non
Readable hierarchical)
 Represents most
CS datastructures
well
 Strict Syntax →
Parsing Fast and
Five Minute
Break
JavaScript
 Invented by Netscape
Communications
 Cross Platform, Object-based,
Scripting Language
 ECMAScript (ECMA-262)
JavaScript

HTTP Request

HTTP Response
Client runs
JavaScript HTML file with
embedded JavaScript
JavaScript
 All Client Side
 Can
 Adjust HTML
 Open Windows, Resize Windows

 Animations, Play Sounds

 Cannot
 Access File System
 Do Networking
JavaScript
 Advantages
 Better User Experience
(2X Latency)
 Disadvantages
 Thicker Client
 Possible Abuse
JavaScript Basics
 <script> section in HTML runs on
document load
 No type declarations
 undefined if not given a value
 Global variables by default
 var makes them local
Generate Dynamic HTML
...
<BODY>
...Regular HTML Here....

<SCRIPT TYPE="text/javascript">
<!--
BUILD HTML HERE!!!
//-->
</SCRIPT>

...More Regular HTML....


</BODY>
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.
document.write(“String”
<HTML>
)
<HEAD><TITLE>Hello!</TITLE></HEAD>
<BODY>
<H1> First JavaScript Page </H1>
<SCRIPT TYPE="text/javascript">
<!--
document.write("<HR/>");
document.write("Hello WWW!");
document.write("<HR/>");
//-->
</SCRIPT>
</BODY>
</HTML>
document.write(“String”
)
document.write(“String”
<HTML>
)
<HEAD><TITLE>Hello!</TITLE>
<SCRIPT TYPE="text/javascript">
<!--
function referringPage() {
if (document.referrer.length == 0) {
return("<I>none</I>");
} else {
return(document.referrer);
}
}
//-->
</SCRIPT>
</HEAD>
<BODY>
<H1> Extracting Info! </H1>
<SCRIPT TYPE="text/javascript">
<!--
document.writeln("<UL>");
document.writeln("<LI>"
+ document.location);
document.writeln("<LI>“
+ referringPage());
document.writeln("<LI>"
+ navigator.appName);
document.writeln("</UL>");
//-->
</SCRIPT>
</BODY>
</HTML>
document.write(“String”
)
Monitor User Events
 <input type="button" value="Don't
Click Me!" onClick="dontClick()"/>
 function dontClick() {
alert("I told ya not to click!");
}
Monitor User Events

www.devguru.com
DOM
 JavaScript is Object-Oriented
 JavaScript Interacts with Document
Object Model of Browser
 DOM Not Totally Standardized
Objects

http://www.devguru.com
Arrays or Objects?
 The Same!
 a.foo <=> a["foo"] <=> a[x]
 a[2] cannot be accessed as a.2
Global Functions
 escape(string)
 unescape(string)
 Safe Strings
ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz
1234567890
@*-_+./
 Unsafe Strings => %20, %5c, etc...
Communicating with
User
 Alert window.alert("Hello!");
 Confirm window.confirm("Delete files?
=D")
 Status Bar window.status = "Hi!";
<html>
<head>
<title>JS Demo</title>
<script language="JavaScript">
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;
}
}
</script>
</head>
<body>
<p>
<button onClick="hello('hi there');" >Say Hello</button>
<br><button onClick="upCount();" >Count</button>
<br><a onClick="alert('holy ####!')">oops</a>
<p>
Thing you are afraid of...
<form name=affirm>
<input type=text name=fear>
<p><input type=button onClick="noFear();" value="No Fear">
Mock mode:<input type=checkbox name=mockMode>
<p><input type=text size=40 name=mock>
</form>
</body>
</html>
Fear Example
Quotes Example
 Text Box
<form name=form1
onsubmit="setQuotes('form1'); return false;">
Search: <input type=text name=target >
<input type=submit value=Submit>
</form>

 Text Box
<input type=text name=target
onKeyUp="setQuotes('form2');">
<script language="JavaScript">

// 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.");
// 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.childNodes[0].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 = document[form_name].target.value;
var contents = "";
target = target.toLowerCase();
for (var i in lines) {
if (lines[i].toLowerCase().indexOf(target)!=-1) {
contents = contents + "<li>" + lines[i] + "\n";
}
}
setText("result", contents);
}
</script>
JavaScript Summary
 Good For Simple Things
 Save RT Latency
 Bad when Abused
 Popups!!!
 Don't Always Rely on It
 DOMs not standardized

You might also like