Sunteți pe pagina 1din 60

Web 2.

0 Programming
using AJAX &
Blueprints

Sang Shin
sang.shin@sun.com
www.javapassion.com
Technology Evangelist
Sun Microsystems, Inc.
1
Agenda
• What is Web 2.0?
• What is Rich User Experience?
• Rich Internet Application (RIA) Technologies
• AJAX: Real-life examples
• What is and Why AJAX?
• Technologies used in AJAX
• AJAX usage cases
• Anatomy of AJAX interaction
• Toolkits
2
What is Web 2.0?
Web 2.0 Principles
• Web as a Platform
• Collection Intelligence
> Folksonomy – Collaborative Categorization
• Data is key and should be shared
> Mashups

4
Web 2.0 Principles
• Software is in constantly evolving
> Software release cycles dead?
• Lightweight Programming Models
> SOAP/REST
• Rich User Experience
> AJAX

5
Web 1.0 Web 1.5 Web 2.0

• Personal Websites • Wikis • Blogging - Roller


• Email/News Groups • Discussion Forums • RSS – Syndication
• Popups • Popunders • Google Ads
• Web Directories • Yahoo • Delici.io.us
• Web Classifieds • Cragislist • HousingMaps.com
• Terraserver • MapQuest • Google Maps
• mp3 • Napster • iTunes

6
What Makes the Web 2.0 Different?
• Personalized
• User oriented
• Easy to Use
• Get you to the information you want
• Useful

7
Mashups?

8
Rich User Experience
for Web Application
Rich User Experience
• Take a look at a typical desktop application
(Spreadsheet)
• The program responses intuitively and quickly
• The program gives a user meaningful feedbacks
instantly
> The cursor changed shape
> Icons light up as mouse hovers them
> Selected text changes color
• Things happen naturally
> I don't have to click a button or a link
10
Characteristics of Conventional
Web Application
• “Click, wait, and refresh” user interaction
> Page refreshes from the server needed for all events, data
submissions, and navigation
> The user has to wait for the response
• Synchronous “request/response” communication
model
• Browser always initiates the request

11
Issues of Conventional
Web Application
• Slow response
• Loss of operation context during refresh
• Excessive server load and bandwidth consumption
• Lack of two-way, real-time communication capability
for server initiated updates

These are the reasons why Rich Internet Application


(RIA) technologies were born.
12
Rich Internet
Application(RIA)
Technologies
Rich Internet Application (RIA)
Technologies
• Macromedia Flash
• Java Web Start
• DHTML
• DHTML with IFrame
• AJAX

14
Macromedia Flash
• Designed for playing interactive movies
• Programmed with ActionScript
• Implementation examples
> Macromedia Flex
> Laszlo suite (open source)
• Pros:
> Good for vector graphics
• Cons:
> Browser needs a Flash plug-in
> ActionScript is proprietary and hard to debug
15
Java Web Start
• Desktop application delivered over the net
• Pros
> Desktop experience once loaded
> Leverages Java technology to its fullest extent
> Disconnected operation possible
> Application can be digitally signed
• Cons
> Old JRE-based system do not work

16
DHTML (Dynamic HTML)
• DHTML = JavaScript + DOM + CSS
• Used for creating interactive applications
• No asynchronous communication, however
> Full page refresh still required

17
DHTML with IFrame

• IFrame was introduced as a programmable layout to


the webpage
> An Iframe is represented as an element of a DOM tree
> You can move it, resize it, even hide it while the page is
visible
• An invisible IFrame can add asynchronous behavior
> The visible user experience is uninterrupted
• It is still a hack

18
AJAX
• DHTML plus Asynchronous communication
capability through XMLHttpRequest
> No full-page refresh required
> User work flow is not interrupted
• Pros
> Tremendous industry momentum
> Several toolkits and frameworks are emerging
• Cons
> Browser incompatibility
> JavaScript is hard to maintain and debug
19
AJAX: Real-life
Examples
Real-Life Examples of AJAX apps
• Google maps
> http://maps.google.com/
• Goolgle Suggest
> http://www.google.com/webhp?complete=1&hl=en
• Gmail
> http://gmail.com/
• ZUGGEST- an XMLHttp Experiment using Amazon
> http://www.francisshanahan.com/zuggest.aspx

21
AJAX: Demo
Google Maps vs.
Yahoo Maps Old vs.
Yahoo Maps New
Key Aspects of Google Maps

• A user can drag the entire map by using the mouse


• The action that triggers the download of new map
data is not a specific click on a link but a moving the
map around
> The user workflow is uninterrupted by the need to
communicate with the server
• Other parts of the page remains the same
• Behind the scene
> The map data is requested and downloaded asynchronously

23
AJAX: Usage Cases
Usage cases for AJAX
• Real-time form data validation
> User IDs, serial numbers, postal codes, or even special
coupon codes that require server-side validation can be
validated in a form before the user submits a form
• Auto-Completion
> Email address, name, or city name may be autocompleted as
the user types
• Master detail operation
> Based on a client event, an HTML page can fetch more
detailed information on data such as a product listing
25
Usage cases for AJAX
• Advanced GUI widgets and controls
> Controls such as tree controls, menus, and progress bars
may be provided that do not require page refreshes
• Refreshing data
> HTML pages may poll data from a server for up-to-date data
such as scores, stock quotes, weather, or application-specific
data
• Server side notification
> An HTML page may simulate a server-side push by polling
the server for event notifications in the background
26
Demo Scenario

• Run sample AJAX applications within NetBeans IDE


> Auto completion
> Data validation
> Progress bar
• You can try this demo yourself
> These applications are provided as built-in sample
applications in NetBeans

27
AJAX:
What is and Why AJAX?
Welcome To AJAX
• "Partial screen update" replaces the "click, wait, and
refresh" user interaction model
> Only user interface elements that contain new information are
updated (fast response)
> The rest of the user interface remains displayed without
interruption (no loss of operational context)
• Asynchronous communication replaces
"synchronous request/response model."
> A user can continue to use the application while the client
program requests information from the server in the
background
> Separation of displaying from data fetching
29
Interrupted user
operation while
the data is being
fetched

Uninterrupted
user operation
while data is
being fetched

30
31
AJAX:
Technologies Used
in AJAX
Technologies Used in AJAX
• Javascript
> Loosely typed object based scripting language
> JavaScript in a page is called when an event in a page occurs
• DOM
> API for accessing and manipulating structured documents
> Represents the structure of XML and HTML documents
• CSS
> CSS allow for a clear separation of the presentation from the
content and may be changed programatically by JavaScript
• HTTP
> XMLHttpRequest
33
XMLHttpRequest
• JavaScript object
> Created within a JavaScript function
• Adopted by modern browsers
> Mozilla™, Firefox, Safari, and Opera
• Communicates with a server via standard HTTP
GET/POST
• Documents must be text/xml
• XMLHttpRequest object works in the background
> Does not interrupt user operation
34
Server-Side AJAX Request
Processing
• Server programming model remains the same
> It receives standard HTTP GETs/POSTs
> Can use Servlet, JSP, JSF, ...
• With minor constraints
> More frequent granular requests from client
> Response content type needs to be text/xml

35
AJAX: Anatomy Of
AJAX Interaction
using
Anatomy of an AJAX Interaction

37
Steps Of Interaction
1.A client event occurs
2.An XMLHttpRequest object is created and configured
3.The XMLHttpRequest object makes a call
4.The request is processed by the ValidateServlet.
5.The ValidateServlet returns an XML document
containing the result
6.The XMLHttpRequest object calls the callback() function
and processes the result
7.The HTML DOM is updated
38
1. A Client event occurs
• JavaScript technology functions are called as the
result of an event
• The validateUserId() function is mapped to a
onkeyup event on a link or form component

<input type="text"
size="20"
id="userid"
name="id"
onkeyup="validateUserId();">
39
2. An XMLHttpRequest object is
created and configured
var req;
function initRequest(url) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function validateUserId() {
if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
initRequest(url);
req.onreadystatechange = processRequest;
req.open("GET", url, true);
req.send(null);
} 40
3. XMLHttpRequest object makes a call
function initRequest(url) {
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
} else if (window.ActiveXObject) {
isIE = true;
req = new ActiveXObject("Microsoft.XMLHTTP");
}
}
function validateUserId() {
if (!target) target = document.getElementById("userid");
var url = "validate?id=" + escape(target.value);
initRequest(url);
req.onreadystatechange = processRequest;
req.open("GET", url, true);
req.send(null);
}
• URL is set to validate?id=greg
41
XMLHttpRequest Methods
• open(“method”, “URL”, syn/asyn)
> Assigns destination URL, method, mode
• send(content)
> Sends request including string or DOM object data
• abort()
> Terminates current request
• getAllResponseHeaders()
> Returns headers (labels + values) as a string
• getResponseHeader(“header”)
> Returns value of a given header
• setRequestHeader(“label”,”value”)
> Sets Request Headers before sending
42
XMLHttpRequest Properties
• onreadystatechange
> Event handler that fires at each state change
> You implement your own function that handles this
• readyState – current status of request
> 0 = uninitialized
> 1 = loading
> 2 = loaded
> 3 = interactive (some data has been returned)
> 4 = complete
• status
> HTTP Status returned from server: 200 = OK
43
XMLHttpRequest Properties
• responseText
> String version of data returned from server
• responseXML
> XML DOM document of data returned
• statusText
> Status text returned from server

44
4. The request is processed by the
ValidateServlet (page 1)
public class ValidationServlet extends HttpServlet {
private ServletContext context;
private HashMap accounts = new HashMap();
public void init(ServletConfig config) throws ServletException {
this.context = config.getServletContext();
accounts.put("greg","account data");
accounts.put("duke","account data");
}

45
4. The request is processed by the
ValidateServlet (page 2)
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String targetId = request.getParameter("id");

if ((targetId != null) && !accounts.containsKey(targetId.trim())) {


response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<valid>true</valid>");
} else {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<valid>false</valid>");
}
}

46
5. The ValidateServlet returns an XML
document containing the results

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws IOException, ServletException {
String targetId = request.getParameter("id");
if ((targetId != null) && !users.containsKey(targetId.trim())) {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("valid");
} else {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("invalid");
}
}
}
47
6. XMLHttpRequest object calls callback()
function and processes the result
• The XMLHttpRequest object was configured to call
the processRequest() function when there are
changes to the readyState of the XMLHttpRequest
object

function processRequest() {
if (req.readyState == 4) {
if (req.status == 200) {
var message =
req.responseXML.getElementsByTagName("valid")[0].
childNodes[0].nodeValue;
setMessageUsingDOM(message);
... 48
Browser and DOM
• Browsers maintain an object representation of the
documents being displayed
> In the form of Document Object Model (DOM)
• JavaScript technology in an HTML page has access
to the DOM, and APIs are available that allow
JavaScript technology to modify the DOM after the
page has loaded

49
Object Representation of the XML
Document Retrieved
• Following a successful request, JavaScript
technology code may modify the DOM of the HTML
page
• The object representation of the XML document that
was retrieved from the ValidateServlet is available to
JavaScript technology code using the
req.responseXML, where req is an XMLHttpRequest
object

50
DOM APIs for Navigation
• DOM APIs provide a means for JavaScript
technology to navigate the content from that
document and use that content to modify the DOM
of the HTML page
<message>
valid
</message>
function parseMessage() {
var message = req.responseXML.getElementsByTagName
("message")[0];
setMessage(message.childNodes[0].nodeValue);
}
51
7. The HTML DOM is updated
• JavaScript technology can gain a reference to any
element in the HTML DOM using a number of APIs
• The recommended way to gain a reference to an
element is to call
> document.getElementById("userIdMessage"), where
"userIdMessage" is the ID attribute of an element appearing in
the HTML document
• JavaScript technology may now be used to modify
the element's attributes; modify the element's style
properties; or add, remove, or modify child elements
52
Change the Body content of an
Element
<script type="text/javascript">
function setMessage(message) {
mdiv = document.getElementById("userIdMessage");
if (message == "invalid") {
mdiv.innerHTML = "<div style=\"color:red\">Invalid User Id</
div>";
} else {
mdiv.innerHTML = "<div style=\"color:green\">Valid User Id</
div>";
}
}
</script>
<body>
<div id="userIdMessage"></div>
</body> 53
AJAX: Demo
Analyze AutoComplete AJAX
Interaction
• Capture the HTTP traffic via HTTP Monitor
• Make a breakpoint in the doGet() method of
AutocompleteServlet
• Display some messages from client' JavaScript's
functions through alert(“some message”)

55
Toolkits and
Frameworks
Reasons for using Client-side
JavaScript Libraries
• Provides higher abstraction APIs
> Easier to develop AJAX applications
• Handles browser incompatibilities
> No need to reinvent the wheel
• Handles graceful degradation
> Uses Iframe if the browser does not support XMLHttpRequest
• Handles various UI issues
> Back and forward buttons
> Bookmarking
57
Client-side JavaScript Libraries

• DOJO Toolkit
> http://dojotoolkit.com/
• Prototype
> http://prototype.conio.net/
• Many more are emerging

58
Server-side Frameworks

• Two types
> The server generates JavaScript code dynamically
> Component-based model
> JSF components can hide the complexity of AJAX programming
completely
• Examples
> DWR (Dynamic Web Remoting)
> http://dwr.dev.java.net/

59
Web 2.0 Programming
using AJAX &
Blueprints

Sang Shin
sang.shin@sun.com
www.javapassion.com
Technology Evangelist
Sun Microsystems, Inc.
60

S-ar putea să vă placă și