Ajax: The Basics Part I

huddleclergymanΛογισμικό & κατασκευή λογ/κού

2 Ιουλ 2012 (πριν από 5 χρόνια και 4 μήνες)

591 εμφανίσεις

© 2010 Marty Hall
Ajax:The Basics
Ajax:

The

Basics
Part I
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/ajax.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
© 2010 Marty Hall
For live Ajax & GWT training, see training
t htt//l t/
courses

a
t htt
p:
//
courses.coreserv
l
e
t
s.com
/
.
Taught by the author of Core Servlets and JSP,
More
Servlets and JSP
and this tutorial Available at
More
Servlets and JSP
,
and this tutorial
.
Available at
public venues, or customized versions can be held
on-site at your
organization.
C d l d d t ht b M t H ll
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.

C
ourses
d
eve
l
ope
d
an
d

t
aug
ht

b
y
M
ar
t
y
H
a
ll
– Java 6, servlets/JSP (intermediate and advanced), Struts, JSF 1.x, JSF 2.0, Ajax, GWT 2.0 (with GXT), custom mix of topics
– Ajax courses can concentrate on 1 library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, Google Closure) or survey several
• Courses developed and taught by coreservlets.com experts (edited by Marty)
– Spring, Hibernate/JPA, EJB3, Web Services, Ruby/Rails
Contact hall@coreservlets.com for details
Topics in This Section
• Ajax motivation
• The basic Ajax process
• The need for anonymous functions
• Using dynamic content and JSP
• Using dynamic content and servlets
• Displaying HTML results
5
© 2010 Marty Hall
Motivation
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Why Web Apps?
• Downsides to browser-based apps
– GUI is poor
• HTML is OK for static documents, but lousy for programs

Communication is inefficient

Communication

is

inefficient
• HTTP is poor protocol for the way we now use Web apps
• So why does everyone want Web apps?
– Universal access
• Everyone already has a
browser installed
browser

installed
• Any computer on the network
can access content
Automatic

updates


Automatic

updates
• Content comes from server,
so is never out of date
7
Why Ajax?
• Solve three key problems of Web apps
Coarse
grained pdates

Coarse
-
grained
u
pdates
– Synchronous: you are frozen while waiting for result
– Extremely limited options for widgets (GUI elements)
Still b b d

Still

b
rowser
b
ase
d
– Ajax is about “what is the best you can do with what everyone
already has in their browser?”
• “Real” browser-based active content
– Failed: Java Applets
• Not universally supported; can’t interact with the HTML

Serious alternative: Flash/Flex
• Not preinstalled on all PCs;
not available for iPhone/iPad
N
d
l

N
ewer an
d

l
ess proven
• Microsoft Silverlight
• JavaFX
8
From Bill Amend and foxtrot.com. © Universal Press Syndicate.
Traditional Web Apps
vs Ajax Apps
vs
.
Ajax

Apps
• Traditional Web Apps:
I f t L U d t
• Ajax Apps:
F t S ll U d t
I
n
f
requen
t L
ar
g
e
U
p
d
a
t
es
F
requen
t S
ma
ll U
p
d
a
t
es
Web Page 1.
Blah, blah, blah, blah. Yadda,
y
adda,
y
adda. Blah, blah, blah, blah.
Web Page.
Blah, blah, blah, blah. Yadda,
yadda
,
yadda
.Blah,blah,blah,blah.
y
y
Yadda, yadda, yadda. Blah, blah,
blah, blah. Yadda, yadda, yadda.
Blah, blah, blah, blah. Yadda,
yadda, yadda. Blah, blah, blah, blah.
Yadda, yadda, yadda. Blah, blah,
blah, blah. Yadda, yadda, yadda.
yadda
,

yadda
.

Blah,

blah,

blah,

blah.

Yadda, yadda, yadda. Blah, blah,
blah, blah. Yadda, yadda, yadda.
Blah, blah, blah, blah. Yadda,
yadda, yadda. Blah, blah, blah, blah.
Yadda, yadda, yadda. Blah, blah,
blah, blah. Yadda, yadda, yadda.
Web Pa
g
e 2.
g
Blah, blah, blah, blah. Yadda,
yadda, yadda. Blah, blah, blah, blah.
Yadda, yadda, yadda. Blah, blah,
blah, blah. Yadda, yadda, yadda.
Blah, blah, blah, blah. Yadda,
yadda, yadda. Blah, blah, blah, blah.
Yadda, yadda, yadda. Blah, blah,
b
lah
,
blah. Yadda
,

y
adda
,

y
adda.
Server
Server
9
,
,
y
,
y
Google Home Page
(formerly Google Suggest)
(formerly

Google

Suggest)
10
More Ajax Examples
• http://maps.google.com/

http://blo
g
.
g
rimpoteuthis.or
g
/2005/02/
mapping-google.html (analysis of Ajax approach)

http://demo nextapp com/InteractiveTest/ia

http://demo
.
nextapp
.
com/InteractiveTest/ia
• http://demo.backbase.com/explorer/

http://java samples infragistics com/NetAdvantage/JSF/

http://java
.
samples
.
infragistics
.
com/NetAdvantage/JSF/
2007.2/featurebrowser/fbhome.jsp

http://www.laszlosystems.com/demos/
http://www.laszlosystems.com/demos/
• http://www.smartclient.com/index.jsp#_Welcome

http://www.simplica.com/ajax/example/
http://www.simplica.com/ajax/example/
ajax_example.htm?ap=ga3
11
Ajax Jobs
Indeed.com compiles data from multiple jobs sites
12
© 2010 Marty Hall
The Basic Process
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
The Basic Ajax Process
• JavaScript
D fi bj t f di HTTP t

D
e
fi
ne an o
bj
ec
t

f
or sen
di
n
g

HTTP
reques
t
s
– Initiate request
• Get request object

Designate an anonymous response handler function

Designate

an

anonymous

response

handler

function
– Supply as onreadystatechange attribute of request
• Initiate a GET or POST request

Send data
Send

data
– Handle response
• Wait for readyState of 4 and HTTP status of 200
• Extract return text with res
p
onseText or res
p
onseXML
p
p
• Do something with result
• HTML

Load JavaScript
Load

JavaScript
– Designate control that initiates request
– Give ids to input elements and to output placeholder region
14
Define a Request Object
Version for Firefox, Netscape 5+,
Opera
Safari Mozilla

Chrome
function getRequestObject() {
if (window.XMLHttpRequest) {
return(new
XMLHttpRequest
());
Opera
,

Safari
,
Mozilla
,

Chrome
,

Internet Explorer 7, and IE 8.
return(new

XMLHttpRequest
());
} else if (window.ActiveXObject) {
return(new ActiveXObject("Microsoft.XMLHTTP"));
} else {
}

else

{
return(null);
}
}
}
Version for Internet Explorer 5.5 and 6
15
Fails on older and nonstandard browsers. You don’t want
to do “throw new Error(…)” here because this is for very
old browsers, and Error came only in JavaScript 1.5.
Initiate Request
function sendRequest() {
var
request =
getRequestObject
();
Code to call when server responds
var
request

=

getRequestObject
();
request.onreadystatechange =
function() { handleResponse(request) };
request open
(
"
GET
""
message
-
data html
"
true);
request
.
open
( GET
,
message
data
.
html
,
true);
request.send(null);
}
URL of server
-
side resource Must be on same
URL of server
side resource
.
Must be on same
server that page was loaded from.
Don't ait for response
POST data
( l ll f GET t )
Don't
w
ait for response
(Send request asynchronously)
(
a
l
wa
y
s

nu
ll f
or
GET
reques
t
s
)
16
Handle Response
function handleResponse(request) {
if (
request readyState
== 4) {
if

(
request
.
readyState
==

4)

{
alert(request.responseText);
}
}
4 means response from server is complete
}
(
handler
g
ets invoked multiple times

ignore the first ones)
Text of server response
Text of server response
Pop up dialog box
17
First-class Functions in JavaScript
• JavaScript lets you pass functions around
function doSomethingWithResponse() { code }
request.onreadystatechange = doSomethingWithResponse;
– This is somewhat similar to function pointers in C/C++
• Java does not permit this
• JavaScript allows anonymous functions
var re
q
uest =
g
etRe
q
uestOb
j
ect
();
q
g q j
();
request.onreadystatechange =
function() { code-that-uses-request-variable };
– Java has anonymous classes, but no anonymous functions
– C and C++ have nothing like anonymous functions.
Anonymous functions (also called closures) are widely

Anonymous

functions

(also

called

closures)

are

widely

used in Lisp, Ruby, Scheme, C# (as of 2.0), Python,
Visual Basic, ML, PHP (as of 5.3), Clojure, Go, & others.
18
First-Class Functions: Examples
function square(x) { return(x * x); }
f ti t i l ( ) { t ( * 3) }
f
unc
ti
on
t
r
i
p
l
e
(
x
)

{
re
t
urn
(
x
*

3)
;
}
function doOperation(f, x) { return(f(x)); }
doOperation(square, 5);  25
doOperation
(triple 10);


摯佰敲慴楯d
⡴物灬(

㄰⤻



v
慲 晵湣瑩潮猠㴠孳煵慲攬⁴物灬敝f
晵湣瑩潮獛そ⠱〩㬠f  100
functions[1](20);  60
19
Anonymous Functions:
Examples
Examples
function square(x) { return(x * x); }
square(10);  100
(function(x) { return(x * x); })(10);  100
function makeMultiplier(n) {
return(function(x) { return(x * n); });
}
var factor = 5
;
;
var f = makeMultiplier(factor);
f(3);


昨㌩f



晡捴潲‽‵〰f
昨㌩㬠f  15
20
Common but Incorrect Approach
(Global Request Variable)
(Global

Request

Variable)
var request;
function getRequestObject() { ... }
function sendRequest() {
request = getRequestObject();
request.onreadystatechange = handleResponse;
request.open("GET", "...", true);
request send
(null);
request
.
send
(null);
}
function handleRes
p
onse
()
{
p
()
{
if (request.readyState == 4) {
alert(request.responseText);
}
– This is the approach shown in Foundations of Ajax, Ajax in
Practice, Ajax in Action, JavaScript the Definitive Guide, Pro
JavaScript Techniques, and jQuery in Action.
21
Problem with Common Approach:
Race Conditions!
Race

Conditions!
• Scenario
T h l b h fi lli f i 1 d h d lli

T
wo x
h
tm
l

b
uttons, t
h
e
fi
rst ca
lli
n
g

f
unct
i
on
1
an
d
t
h
e secon
d
ca
lli
n
g

function2
– function1 takes 5 seconds to get result from server

function2 takes 1 second to
g
et result from serve
r
• Problem

Su
pp
ose user
p
resses button1
,
then one second later
p
resses button2.
pp p,p
• When function1 looks for request.responseText, it gets the
response text of function 2!
• The function you supply to onreadystatechange must take zero
arguments, so you cannot use a normal (named) function.
• Solution

Use an anon
y
mous function with a local co
py
of the re
q
uest ob
j
ect
y
py q j
embedded inside the code.
22
Corrected Approach
(Local Request Variable)
(Local

Request

Variable)
function getRequestObject() { ... }
function sendRequest() {
var re
q
uest =
g
etRe
q
uestOb
j
ect();
q
g q j
request.onreadystatechange =
function() { handleResponse(request); };
request open
(
"
GET
"""
true);
request
.
open
( GET
, ...,
true);
request.send(null);
}
function handleResponse(request) {
...
...
}
23
Complete JavaScript Code
(show
-
message js)
(show
message
.
js)
function getRequestObject() {
if (window.XMLHttpRequest) {
return(new XMLHttpRequest());
} else if (window.ActiveXObject) {
return(new ActiveXObject("Microsoft.XMLHTTP"));
} else {
t ( ll)
re
t
urn
(
nu
ll)
;
}
}
function
sendRequest
() {
function

sendRequest
()

{
var request = getRequestObject();
request.onreadystatechange =
function() { handleResponse(request); };
request open
(
"
GET
""
message
-
data html
"
true);
request
.
open
( GET
,
message
data
.
html
,
true);
request.send(null);
}
function
handleResponse
(request) {
function

handleResponse
(request)

{
if (request.readyState == 4) {
alert(request.responseText);
}
}
24
HTML Code
• Use xhtml, not HTML 4
I d i l i i h DOM

I
n or
d
er to man
i
pu
l
ate
i
t w
i
t
h

DOM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">...</html>
• Due to IE bug, do not use XML header before the DOCTYPE
Load the JavaScript file

Load

the

JavaScript

file
<script src="relative-url-of-JavaScript-file"
type="text/javascript"></script>
• Use separate </script> end tag
• Desi
g
nate control to initiate re
q
uest
g q
<input type="button" value="button label"
onclick="mainFunction()"/>
25
Internet Explorer XHTML Bugs
• Can’t handle XML header
– XML documents in general are supposed to start with
XML header:
• <
?xml version
="
1 0
"
encoding
="
UTF
-
8
"
?
>
Omit this!
?xml

version 1
.
0

encoding UTF
8?
<!D O C T Y P E h t m l ...>
<html xmlns="http://www.w3.org/1999/xhtml">...</html>

XHTML specification recommends using it
XHTML

specification

recommends

using

it
– But... Internet Explorer will switch to quirks-mode (from
standards-mode) if DOCTYPE is not first line.
• Many recent style sheet formats will be ignored
• So omit XML header

Needs separate end tags in some places
Needs

separate

end

tags

in

some

places
– Scripts will not load if you use <script .../>
instead of <script...></script>
26
Don’t do this.
Do this instead.
HTML Code
(show
-
message html)
(show
message
.
html)
<!DOCTYPE html PUBLIC "..."
"
http://www.w3.org/TR/xhtml1/DTD/xhtml1
-
transitional.dtd
"
>
http://www.w3.org/TR/xhtml1/DTD/xhtml1
transitional.dtd >
<html xmlns="http://www.w3.org/1999/xhtml">
<head><title>Ajax: Simple Message</title>
<
script src="sho
w
-message.js"
type="text/javascript"></script>
</head>
<body>
<
center
>
<table border="1" bgcolor="gray">
<tr><th><big>Ajax: Simple Message</big></th></tr>
</table>
</table>
<p/>
<input type="button" value="Show Message"
onclick
=
"
sendRequest
()
"
/>
onclick
=
sendRequest
()/>
</center></body></html>
27
HTML Code (message-data.html)
Some random message
• Note: executing this example

Since main page uses relative URL and the HTML here has no dynamic
Since

main

page

uses

relative

URL

and

the

HTML

here

has

no

dynamic

content, you can run this example directly from the disk without using a
server. But later examples require dynamic content, so all examples will be
shown running on Tomcat.
28
The Basic Process: Results
29
Ajax Testing
• JavaScript is notoriously inconsistent
Y h th t th lib i ill i t d l t (P t t

Y
ou
h
ope
th
a
t

th
e
lib
rar
i
es we w
ill

i
n
t
ro
d
uce
l
a
t
er
(P
ro
t
o
t
ype,
jQuery, etc.) take this into account, and hide the browser
differences. Nevertheless, you should test.

Test on multiple browsers

Test

on

multiple

browsers
– If you field an internal application, test on all officially
sanctioned browsers on all supported operating systems.
If fi ld t l li ti t t b

If
you
fi
e
ld
an ex
t
erna
l
app
li
ca
ti
on,
t
es
t
on as many
b
rowsers
as possible. Preferably: IE 6, IE 7, IE 8, a recent Firefox
implementation, and Chrome. Safari and Opera can’t hurt, but
are less used
are

less

used
.
• Test regularly on IE and Firefox. Test on Chrome and a wider
set of browsers before deploying.
• Browser market share:
htt//
3 h l/b/b t t
htt
p:
//
www.w
3
sc
h
oo
l
s.com
/b
rowsers
/b
rowsers_s
t
a
t
s.asp
• Access stats on coreservlets.com (August 2010)
– IE: 42.4%, Firefox: 41.1%, Chrome: 12.8%, Safari: 1.4%, Opera: 1.3%
30
© 2010 Marty Hall
Dynamic Content from
Dynamic

Content

from

JSP
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
First Example: Design Deficiencies
• Content was the same on each request
– Could have just hardcoded the alert value in JavaScript
– Instead, invoke a JSP page on the server
Resource address hardcoded in JavaScript

Resource

address

hardcoded

in

JavaScript
– Prevents functions from applying to multiple situations

Instead make generic function and pass address to it
Instead
,
make

generic

function

and

pass

address

to

it
• JavaScript file was in same folder as HTML
– Makes it hard to reuse the JavaScri
p
t in different
p
a
g
es
p p g
– Instead, make a special directory for JavaScript
• No style sheet was used
– Less for JavaScript to work with when manipulating page
– Use CSS for normal reasons as well as for JavaScript
32
Steps
• JavaScript
Define an object for sending HTTP requests

Define

an

object

for

sending

HTTP

requests
– Initiate request
• Get request object

Designate an anonymous response handler function

Designate

an

anonymous

response

handler

function
– Supply as onreadystatechange attribute of request
• Initiate a GET or POST request to a JSP page
– Get the address from a variable instead of hardcoding it
• Send data
– Handle response
• Wait for readyState of 4 and HTTP status of 200
E t t t t t ith
T t
XML

E
x
t
rac
t
re
t
urn
t
ex
t
w
ith
response
T
ex
t
or response
XML
• Do something with result
• HTML
L d J S i
f li d di U l h

L
oa
d

J
ava
S
cr
i
pt
f
rom centra
li
ze
d

di
rector
y
.
U
se st
yl
e s
h
eet.
– Designate control that initiates request
– Give id to output placeholder region
33
Define a Request Object
function getRequestObject() {
if (window.XMLHttpRequest) {
return(new
XMLHttpRequest
());
return(new

XMLHttpRequest
());
} else if (window.ActiveXObject) {
return(new ActiveXObject("Microsoft.XMLHTTP"));
} l {
}
e
l
se
{
return(null);
}
}
No changes from previous example.
This code stays the same for entire section.
34
Initiate Request
function ajaxAlert(address) {
var
request =
getRequestObject
();
var
request

=

getRequestObject
();
request.onreadystatechange =
function() { showResponseAlert(request); };
request.open("GET", address, true);
request.send(null);
}
Relative URL of server-side resource.
(In this example, we will pass in the address of a JSP page.)
35
Handle Response
function showResponseAlert(request) {
if ((
request readyState
== 4) &&
if

((
request
.
readyState
==

4)

&&
(request.status == 200)) {
alert(request.responseText);
}
}
Server response came back with no errors
(HTTP status code 200).
36
Complete JavaScript Code
(Part of
ajax
-
utils js
)
(Part

of

ajax
utils
.
js
)
function getRequestObject() {
if (window.XMLHttpRequest) {
t (
tt t
())
re
t
urn
(
new XMLH
tt
pReques
t
())
;
} else if (window.ActiveXObject) {
return(new ActiveXObject("Microsoft.XMLHTTP"));
} else {
return(null);
return(null);

}
}
function a
j
axAlert
(
address
)

{
j
( ) {
var request = getRequestObject();
request.onreadystatechange =
function() { showResponseAlert(request); }
request.open("GET", address, true);
request.send(null);
}
function showResponseAlert(request) {
if ((
request readyState
== 4) &&
if

((
request
.
readyState
==

4)

&&
(request.status == 200)) {
alert(request.responseText);
}
}
37
HTML Code
• Load JavaScript from central location
<script src="./scripts/ajax-utils.js"
type="text/javascript"></script>

Pass JSP address to main function

Pass

JSP

address

to

main

function
<input type="button" value="Show Server Time"
onclick='a
j
axAlert
(
"show-time.
j
s
p
"
)
'/>
j
(
j p
)
• Use style sheet
<link rel="stylesheet"
Note single quotes (because of
d bl t i id
)
href="./css
/
styles.css"
type="text/css"/>
d
ou
bl
e

quo
t
es
i
ns
id
e

parens
)
.
38
HTML Code
<!DOCTYPE html PUBLIC "...">
<html xmlns=
"
http://www w3 org/1999/xhtml
"
>
<html

xmlns= http://www
.
w3
.
org/1999/xhtml >
...
<link rel="stylesheet"
href="./css/styles.css"
type=
"
text/css
"
/>
type= text/css/>
<script src="./scripts/ajax-utils.js"
type="text/javascript"></script>...
<body>...
<body>...
<fieldset>
<legend>Data from JSP, Result Shown in Alert Box
<
/le
g
end>
g
<form action="#">
<input type="button" value="Show Server Time"
onclick='ajaxAlert("sho
w
-time.jsp")'/>
</form>
</fieldset>
...
39
JSP Code (show-time.jsp)
<%= new java.util.Date() %>

Note:executing this example
Note:

executing

this

example
– You must run from Tomcat, not directly from the disk
• Otherwise JSP cannot execute
• And also status code is -1, not 200
40
Message from JSP: Results
41
© 2010 Marty Hall
Dynamic Content from
Dynamic

Content

from

Servlet
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
JSP Example: Design Deficiencies
• Caching problems
– The URL stays the same but the output changes
– So if browser caches page, you get the wrong time

Much more likely with IE than with other browsers

Much

more

likely

with

IE

than

with

other

browsers
– Solution:
send Cache-Control and Pragma headers
• Date was not formatted
– Just used the toString method of Date
– Solution:
use String.format (ala sprintf) and %t controls
• JSP is wrong technology
– JSP is best for lots of HTML and little or no logic/Java
B t h l i b t HTML

B
u
t
now we
h
ave
l
og
i
c
b
u
t
no
HTML
– Solution:
use a servlet
43
Steps
• JavaScript
D fi bj t f di HTTP t

D
e
fi
ne an o
bj
ec
t

f
or sen
di
n
g

HTTP
reques
t
s
– Initiate request
• Get request object

Designate an anonymous response handler function

Designate

an

anonymous

response

handler

function
– Supply as onreadystatechange attribute of request
• Initiate a GET or POST request to a servlet

Send data
Send

data
– Handle response
• Wait for readyState of 4 and HTTP status of 200
• Extract return text with res
p
onseText or res
p
onseXML
p
p
• Do something with result
• HTML

Load JavaScript fromcentralized directory Use style sheet
Load

JavaScript

from

centralized

directory
.
Use

style

sheet
.
– Designate control that initiates request
– Give id to output placeholder region
44
Define a Request Object, Initiate
Request Handle Response
Request
,
Handle

Response
function getRequestObject() {
if (window.XMLHttpRequest) {
t (
XMLHtt R t
())
re
t
urn
(
new
XMLHtt
p
R
eques
t
())
;
} else if (window.ActiveXObject) {
return(new ActiveXObject("Microsoft.XMLHTTP"));
} else {
return(null);
return(null);

}
}
function ajaxAlert(address) {
bj
()
No changes from previous example.
Only address changes, and address
comes from the HTML page.
var request = getRequestO
bj
ect
()
;
request.onreadystatechange =
function() { showResponseAlert(request); }
request.open("GET", address, true);
request send
(null);
request
.
send
(null);
}
function showResponseAlert(request) {
if ((request.readyState == 4) &&
(request.status == 200)) {
alert(request.responseText);
}
}
45
HTML Code
...
<link
rel
="
stylesheet
"
<link

rel
stylesheet
href="./css/styles.css"
type="text/css"/>
<
scri
p
t src="./scri
p
ts/a
j
ax-utils.
j
s"
p
p j
j
type="text/javascript"></script>
...
<fieldset>
Address of servlet from @WebServlet
(servlets 3.0) or from url-pattern of servlet-
mapping in web.xml (servlets 2.5 and earlier).
<
legend
>
Data from Servlet, Result Shown in Alert Box
</legend>
<
i t t"b tt"l"Sh S Ti"
<
i
npu
t

t
ype=
"b
u
tt
on
"
va
l
ue=
"Sh
ow
S
erver
Ti
me
"
onclick='ajaxAlert("show-time")'/>
</fieldset>
...
46
Servlet Code
package coreservlets;
import
import
...
public class ShowTime extends HttpServlet {
p
ublic void doGet
(
Htt
p
ServletRe
q
uest re
q
uest
,
p ( p q q,
HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Pragma", "no-cache");
PrintWriter out = response.getWriter();
Date currentTime = new Date();
St i
St
r
i
ng message =
String.format("It is now %tr on %tD.",
currentTime, currentTime);
out print(message);
out
.
print(message);
}
}
47
web.xml
...
<servlet>
<servlet>
<servlet-name>ShowTime</servlet-name>
<servlet-class>coreservlets.ShowTime</servlet-class>
</servlet>
</servlet>
<servlet-mapping>
<servlet-name>ShowTime</servlet-name>
< l
tt >
/h
ti
</l
tt >
<
ur
l
-pa
tt
ern
>
/
s
h
o
w
-
ti
me
</
ur
l
-pa
tt
ern
>
</servlet-mapping>
...
In Tomcat 7 or other servers that support servlets 3.0, you can use
@WebServlet(
"
/show
-
time
"
) above the servlet class definition and
48
@WebServlet(/show
-
time ) above the servlet class definition
,
and
omit web.xml entirely.
Message from Servlet: Results
49
© 2010 Marty Hall
Building HTML Output
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
ShowTime Servlet Example:
Design Deficiencies
Design

Deficiencies
• Results always shown in dialog (alert) box
– Alerts usually reserved for errors or warnings
– Users prefer normal results inside page
Solution:
use Dynamic HTML to update page with result

Solution:
use

Dynamic

HTML

to

update

page

with

result

• HTML plus CSS styles represented in the DOM
– DOM stands for "Document Object Model", an XML view of page
» Note that Firebug has an outstanding DOM explorer. See next lecture.
• JavaScript can insert elements into the DOM
– Find an element with given id
someElement
document getElementById(id);
»
someElement
=
document
.
getElementById(id);
– Insert HTML inside
» someElement.innerHTML = "<h1>blah</h1>";

JavaScript can also read the DOM
JavaScript

can

also

read

the

DOM
– E.g., look up textfield values (see upcoming example)
» document.getElementById(id).value
51
Dynamically Inserting Text
• HTML
di
id"l
l h ld"
/di

<
di
v
id
=
"
resu
l
ts-
pl
ace
h
o
ld
er
"
><
/di
v>
• JavaScript

resultRe
g
ion =
g
document.getElementById("results-placeholder");
– resultRegion.innerHTML = "<h2>Wow!</h2>";
• For the innerHTML text
,

y
ou usuall
y
use re
q
uest.res
p
onseText
,y y
q p
or some string derived from request.responseText
• Result after running code

<
div id
="
results
-
placeholder
"><
h2
>
Wow!
<
/h2
><
/div
>
div

id results
placeholder h2 Wow!/h2/div
•"View source" won't show this, but Firebug will.
• Warning
M k h t i t lt i l l
ht l

M
a
k
e sure w
h
a
t

y
ou
i
nser
t
resu
lt
s
i
n
l
e
g
a
l
x
ht
m
l
• You can't insert block-level elements into inline elements
• Use correct case for the inserted text
52
Summary of New Features
• HTML
– Define initially blank div element
<
div id
="
resultText
"><
/div
>
div

id resultText/div
• JavaScript response handler
– Supply an id (resultRegion), find element with that id,
and insert response text into innerHTML property
document.getElementById(resultRegion).innerHTML =
request.responseText;
53
Steps
• JavaScript
D fi bj t f di HTTP t

D
e
fi
ne an o
bj
ec
t

f
or sen
di
n
g

HTTP
reques
t
s
– Initiate request
• Get request object

Designate an anonymous response handler function

Designate

an

anonymous

response

handler

function
– Supply as onreadystatechange attribute of request
• Initiate a GET or POST request to a servlet

Send data
Send

data
– Handle response
• Wait for readyState of 4 and HTTP status of 200
• Extract return text with res
p
onseText or res
p
onseXML
p
p
• Use innerHTML to insert result into designated element
• HTML

Load JavaScript fromcentralized directory.Use style sheet.
Load

JavaScript

from

centralized

directory.

Use

style

sheet.
– Designate control that initiates request
– Give id to output placeholder region
54
Define a Request Object
function getRequestObject() {
if (window.XMLHttpRequest) {
return(new
XMLHttpRequest
());
return(new

XMLHttpRequest
());
} else if (window.ActiveXObject) {
return(new ActiveXObject("Microsoft.XMLHTTP"));
} l {
}
e
l
se
{
return(null);
}
}
No changes from previous examples
55
Initiate Request
function ajaxResult(address, resultRegion) {
var request
=
getRequestObject();
var

request

getRequestObject();
request.onreadystatechange =
function() { showResponseText(request,
resultRe
g
ion
)
;
}
;
g
) }
request.open("GET", address, true);
request.send(null);
}
56
Handle Response
function showResponseText(request, resultRegion) {
if ((request readyState == 4) &&
if

((request
.
readyState

==

4)

&&
(request.status == 200)) {
htmlInsert(resultRegion, request.responseText);
}
}
}
function
htmlInsert
(id,
htmlData
) {
function

htmlInsert
(id,

htmlData
)

{
document.getElementById(id).innerHTML = htmlData;
}
57
HTML Code
...
<link
rel
="
stylesheet
"
<link

rel
stylesheet
href="./css/styles.css"
type="text/css"/>
<script src="./scripts/ajax-utils.js"
type="text/javascript"></script
>
...
<fieldset>
<legend>Data from Servlet Result Shown in HTML</legend>
<legend>Data

from

Servlet
,
Result

Shown

in

HTML</legend>
<input type="button" value="Show Server Time"
onclick='ajaxResult("show-time","timeResult1")'/>
<
div id="timeResult1" class="a
j
axResult"></div
>
j
</fieldset>
...
58
Style Sheet Code (css/styles.css)
.ajaxResult { color: #440000;
font
weight:bold;
font
-
weight:

bold;
font-size: 18px;
font-family: Arial, Helvetica, sans-serif;
}
}
• Note
– Don’t worry if you don’t yet know much about style
sheets. They will be covered in later lecture.
59
Servlet Code
• No changes from previous example
– Returns a formatted time string
60
Building HTML Output: Results
61
© 2010 Marty Hall
Wrap-Up
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Summary
• JavaScript
Define request object

Define

request

object
• Check for both Microsoft and non-MS objects. Identical in all apps.
– Initiate request
• Get re
q
uest ob
j
ect
q j
• Designate an anonymous response handler function
• Initiate a GET request
– Handle response
W it f
d St t
f 4 d HTTP t t f 200

W
a
it

f
or rea
d
y
St
a
t
e o
f

4
an
d

HTTP
s
t
a
t
us o
f

200
• Extract return text with responseText
• Do something with result

Use innerHTML to insert result into desi
g
nated element
g
• HTML
– Give id to placeholder (often a div). Initiate process.

Java
Java
– Use JSP, servlet, or combination (MVC) as appropriate.
– Prevent browser caching.
63
Preview of Next Sections
• Ajax Development and Testing Tools
– Tools for debugging Ajax
– Tools for debugging JavaScript
Tools for building Ajax
based Web apps

Tools

for

building

Ajax
-
based

Web

apps
– Tools for developing xhtml
– Tools for buildin
g
and
p
reviewin
g
st
y
le sheets
g p g y
– Tools for validating xhtml
• Ajax Basics: Part II
– Sending GET data
– Reading data from textfields
S di POST d t

S
en
di
ng
POST

d
a
t
a
– Ajax toolkits
64
© 2010 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.