ajax: riding the browser based horse a little further

49
Web 2.0 and Java: Rich Internet Applications and AJAX Lee Chuk Munn Staff Engineer Sun Microsystems, Inc.

Upload: sampetruda

Post on 20-May-2015

979 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: AJAX: Riding the Browser Based Horse a Little Further

Web 2.0 and Java:Rich Internet Applications and AJAXLee Chuk MunnStaff EngineerSun Microsystems, Inc.

Page 2: AJAX: Riding the Browser Based Horse a Little Further

Goal

Learn how to architect and build rich web applications using AJAX and J2EE™ technologies.

Page 3: AJAX: Riding the Browser Based Horse a Little Further

Agenda• Architecture• XMLHttpRequest Object• User Interface• Server Side• Example of AJAX Use Cases• Considerations and Gotchas• AJAX Applications and the Java EE Platform• Summary

Page 4: AJAX: Riding the Browser Based Horse a Little Further

Conventional Rich Web Applications

• Page refreshes needed for all events, data submissions, and navigation

• Plugins, applets, or browser black magic• Have varying support for JavaScript™

technology and CSS• Use the least common denominator of technologies

Page 5: AJAX: Riding the Browser Based Horse a Little Further

New Wave of Web Application

• Google maps http://maps.google.com/

• Gmailhttp://gmail.com/

• Google Suggest http://www.google.com/webhp?complete=1&hl=en

• ZUGGEST- an XMLHttp Experiment using Amazonhttp://www.francisshanahan.com/zuggest.aspx

Page 6: AJAX: Riding the Browser Based Horse a Little Further

What is AJAX?• AJAX is an acronym for Asynchronous Javascript

And XML> AJAX uses JavaScript combined with xml to grab

information from a server without refreshing the page> nothing new, the main requirement is the web browser

has the support for XMLHttpRequest object> The term AJAX was coined Jesse James Garrett in

February 2005

• Advantages on web applications:> Reduce server load (sometimes)> Dramatic improvement in user interface

Page 7: AJAX: Riding the Browser Based Horse a Little Further

Architecture

Page 8: AJAX: Riding the Browser Based Horse a Little Further

Traditional Web

Page 9: AJAX: Riding the Browser Based Horse a Little Further

AJAX

Page 10: AJAX: Riding the Browser Based Horse a Little Further

Anatomy of an AJAX RequestRealtime update

Page 11: AJAX: Riding the Browser Based Horse a Little Further

Major Components AJAX

• Javascript> JavaScript in a page is called when an event in a page

occurs

• DOM> API for accessing and manipulating structured documents> Represent 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 JavaScrip

• HTTP> XMLHttpRequest

Page 12: AJAX: Riding the Browser Based Horse a Little Further

Examples of AJAX Use Cases

• Real time form data validation• Auto-completion• Master details operations• Sophisticated user interface control• Server side notification

Page 13: AJAX: Riding the Browser Based Horse a Little Further

The XMLHttpRequestObject

Page 14: AJAX: Riding the Browser Based Horse a Little Further

XMLHttpRequest• Communication may be GET/POST• Does not show the user anything—no status

messages• Documents must be text/xml• Page continues to process events, the

XMLHttpRequest object works in the background• Limited Number of requests allowed• Allows you to specify a handler method for state

changes• Handler notified when request is:

> Initialized, Started, In the process of being returned, Completely finished

Page 15: AJAX: Riding the Browser Based Horse a Little Further

XmlHttpRequest• Creating an XmlHttpRequest instance

> Many/most aspects of using this object have been standardized

> Creating the object, however, is browser specific

• Asynchronous requests> Utilize a combination of the onreadystatechange function

and status-properties to ensure processing occurs when server processing is complete

• Response> The content must be set to text/xml> Should turn off caching

Page 16: AJAX: Riding the Browser Based Horse a Little Further

XMLHttpRequest Methods• open(“method”, “URL”, sync/async)

> Assigns destination URL, method, mode> sync = false, async = true

• 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

Page 17: AJAX: Riding the Browser Based Horse a Little Further

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

• responseText> String version of data returned from server

• responseXML> XML DOM document of data returned

• statusText> Status text returned from server

Page 18: AJAX: Riding the Browser Based Horse a Little Further

Instantiating XMLHttpRequest01 var req;02 //Non IE browser03 if (window.XMLHttpRequest) {04 req = new XMLHttpRequest();05 else if (window.ActiveXObject) {06 req = new ActiveXObject(“Microsoft.XMLHTTP”);07 } else {08 alert(“Your browser is not currently supported”);09 return;10 }11 //Use GET to send data asynchronously12 req.open(“GET”, url, true);13 //Set the callback function14 req.onreadystatechange = callback;15 //Send the request16 req.send(null);

Page 19: AJAX: Riding the Browser Based Horse a Little Further

Synchronous vs. Asynchronous• Synchronous mode (not AJAX application)

> req.open('GET', 'url' , false)> Can be used to retrieve data and update selected parts of the

page without refreshing the entire page> if there is nothing useful for the user to do after a request is

submitted to a server> Block the user interface

• Asynchronous mode (AJAX application)> req.open('GET', 'url', true)

> Get a callback when the data has been received> Browser continue to work as normal while requests are

processed in the background> Example: Pan a google map as fast as you can and realize

the page itself never reloads

Page 20: AJAX: Riding the Browser Based Horse a Little Further

Synchronous vs. Asynchronous

• Requests can be made asynchronously or synchronously> both techniques allow web page to be updated without

refreshing it> anything useful the user can do while processing

request?> if yes then use asynchronous, otherwise use synchronous

• Most frameworks support either• Asynchronous is typically recommended• Synchronous requests may freeze the browser for

the duration of the request

Page 21: AJAX: Riding the Browser Based Horse a Little Further

The User Interface

Page 22: AJAX: Riding the Browser Based Horse a Little Further

Elements in a AJAX Web Page

• Figure out the use case> Eg. Realtime validation of user login

• Decide on the JavaScript event you which to intercept> Eg. onKeyUp, onMouseOver, onLoad, onSubmit

• Set a function to intercept this event• Define a callback function• Set aside an area to display the result

Page 23: AJAX: Riding the Browser Based Horse a Little Further

Example: User Validation01 <head>02 <script type=”text/javascript”>03 function validateUserId( ) {04 //do something here05 }06 function processCallback( ) {07 //do something here08 }09 </script>10 </head>11 <body>12 <input type="text" size="20" id="userId" name="id"13 onkeyup="validateUserId( )">1415 <div id=”message”></div>16 </body>

Page 24: AJAX: Riding the Browser Based Horse a Little Further

Sending Request

• Decide if operation is synchronous or asynchronous• Decide if HTTP method is GET or POST

> Slight coding difference

• For asynchronous request > Set callback function> Dispatch method needs to be thread-safe due to network

latency

• Encode the data before sending to server

Page 25: AJAX: Riding the Browser Based Horse a Little Further

Example: Dispatch Function – GET 01 function validateUserId( ) {02 //Get an instance of XMLHttpRequest03 var req = //get a XMLHttpRequest object04 //Get the user id 05 var user = document.getElementById(“userId”);06 //Construct the URL07 var url = “validate?id=” + escape(user.value);08 //Set the callback09 req.onreadystate = processCallback;10 //Send the request11 req.open(“GET”, url, true);12 req.send(null);13 }

Page 26: AJAX: Riding the Browser Based Horse a Little Further

Example: Dispatch Function – POST 01 function validateUserId( ) {02 //Get an instance of XMLHttpRequest03 var req = //get a XMLHttpRequest object04 //Get the user id 05 var user = document.getElementById(“userId”);06 //Construct the URL07 var url = “validate”;08 //Set the callback09 req.onreadystate = processCallback;10 //Send the request11 req.open(“POST”, url, true);12 req.setRequestHeader(“Content-Type”13 , “application/x-www-form-urlencoded”);14 req.send(“id=” + escape(user.value));15 }

Page 27: AJAX: Riding the Browser Based Horse a Little Further

Example: Callback Function01 function processCallback( ) {02 //Check if the request has completed03 if (req.readyState != 4)04 return;05 //Check if the status is okay06 if (req.status != 200) {07 alert(“Error!”);08 return;09 }10 //Extract the result from the return XML document11 var result = req.responseXML12 .getElementByTagName(“message”)[0];13 var msg = result.childNodes[0].nodeValue;14 displayMessage(msg);15 }

<message> valid / invalid</message>

Page 28: AJAX: Riding the Browser Based Horse a Little Further

Example: Displaying the Result

01 function displayMessage(msgText) {02 var msgElement =03 document.getElementById(“message”);04 var text;05 if (msgText == valid) {06 msgElement.style.color = “green”;07 text = document.createTextNode(“Valid user id”);08 } else {09 msgElement.style.color = “red”;10 text = document.createTextNode(“Invalid user id”);11 }12 msgElement.replaceChild(13 text, msgElement..childNodes[0]);14 }

Update the HTML's DOM

Page 29: AJAX: Riding the Browser Based Horse a Little Further

The Server's Side

Page 30: AJAX: Riding the Browser Based Horse a Little Further

Server Side AJAX Processing

• Request are either in HTTP GET or POST• Use Servlet programming model to handle these

request• Things to keep in mind

> Responses must be encoded in 'text/xml'> Data must be in XML format> Request to Servlet may be more frequent and granular

> Eg. each keystroked is processed in real time validation> Turn off caching

Page 31: AJAX: Riding the Browser Based Horse a Little Further

Example: AJAX Server Processing01 public void doGet(HttpServletRequest req02 , HttpServletResponse res)03 throws IOException, ServletException {0405 //Extract the parameter and check if we have a valid ID06 String id = req.getParameter(“id”);07 String valid = checkId(id);0809 //Encode the response as “text/xml”10 res.setContent(“text/xml”);11 //Request the browser not to cache the results12 res.setHeader(“Cache-Control”, “no-cache”);13 //Write the result14 res.getWriter().write(valid);15 }

Page 32: AJAX: Riding the Browser Based Horse a Little Further

Considerationsand Gotchas

Page 33: AJAX: Riding the Browser Based Horse a Little Further

Things to Consider• AJAX requires you to think about interface and

interaction> Usability is the key—and is what you should strive for

> Do not break what the user is focusing on> Make sure to give the user feedback

> Do not over-use it• How do you handle state + sessions?

> Decision on where to put state information gets trickier> Can all be on the client so you can have truly stateless servers> Requires a lot more client code for state – server already has

mechanism for clustered> State synchronization> What happens if the server or network dies?

Page 34: AJAX: Riding the Browser Based Horse a Little Further

Things to Consider (cont.)• Navigation Issues

> Back button is meaningless unless you code ‘undo’ functionality to it> Invisible IFRAME and puts results back to visible web page> Google Maps, Dojo toolkit (http://dojotoolkit.org)

> Bookmarking doesn’t work unless you manually change the URL> Explicitly create link for bookmarking eg. GoogleMap

> Refresh button can kill your app> Save state in <body onload> method

• Don’t assume the server is going to respond instantly> Network latency – consider interval between user request

and server response> Need visual feedback for background activity> Preload data on the server where possible

Page 35: AJAX: Riding the Browser Based Horse a Little Further

AJAX Efficiency

• Keep requests as concise as possible• Only request/respond with the data required• Preload data on the server where possible• Put some thought into what event will trigger• Some events happen faster than is practical to

make server requests> i.e. Although Google Suggest appears to make a request

on each keystroke, closer examination reveals it is actually makes requests at regular time intervals

Page 36: AJAX: Riding the Browser Based Horse a Little Further

Things You May not Like• Big problems could easily arise from a user disabling

JavaScript in their browsers!• There will be some learning curve

> You may not already be doing it

• Browser differences - not completely standardized• Not yet official part of any spec• Debugging - Java code on server mixes with

JavaScript on the client• Viewable source

> Potential security issues> Reverse engineering

Page 37: AJAX: Riding the Browser Based Horse a Little Further

Java Server Facesand

AJAX

Page 38: AJAX: Riding the Browser Based Horse a Little Further

JavaServer Faces: What is it?

• A server-side user interface component framework for Java

TM

technology-based web applications> Components> Events> Validators> Back-end-data integration> Designed to be added to tools

Page 39: AJAX: Riding the Browser Based Horse a Little Further

JSF Architecture

Client

Server

UIRequest(events)

Response(markup)

Page 40: AJAX: Riding the Browser Based Horse a Little Further

Architecture: Dependencies

JSF App

Servlets (2.3 or later)

JSP (1.2 or later) JSF API

JSF Tags

JSF App

Page 41: AJAX: Riding the Browser Based Horse a Little Further

Sample JSFTM Page

1: <%@ taglib uri=”http://java.sun.com/jsf/html” prefix=”h” %>2: <%@ taglib uri=”http://java.sun.com/jsf/core” prefix=”f” %>

3: <f:view>4: <h:form formName=”logonForm”>5: <h:panelGrid columns=”2”>6: <h:outputText value=”Username:”/>7: <h:inputText id=”username” length=”16”8: value=”#{LoginFormBean.userName}”/>9: 10: <h:commandButton type=”submit”11: label=”Log On”12: action=”success”/>13: <h:commandButton type=”reset”14: label=”Reset”/>15: </h:panelGrid>16: </h:form>17: </f:view>

Page 42: AJAX: Riding the Browser Based Horse a Little Further

JSF Component Approach

• Using “AJAX-enabled” JavaServer Faces components to construct the user interface> Control Content Rendering > Control of Server Side Logic> All in one component> Reusable> Usable in a tool> Hide AJAX complexity from page developers

Page 43: AJAX: Riding the Browser Based Horse a Little Further

AJAXing JSF Components

<h:outputText value="Name:" /> <dl:dlabel size="40" valueBinding="#{SessionBean.name}" /><h:outputText value="Street:" /> <dl:dlabel size="40" valueBinding="#{SessionBean.street}" /><h:outputText value="City:" /> <dl:dlabel size="40" valueBinding="#{SessionBean.city}" /><h:outputText value="State:" /> <dl:dlabel size="40" valueBinding="#{SessionBean.state}" /><h:outputText value="Zip:" /> <dl:dlabel size="40" valueBinding="#{SessionBean.zip}" />

Page 44: AJAX: Riding the Browser Based Horse a Little Further

AJAX Enabled JSF Components

Page 45: AJAX: Riding the Browser Based Horse a Little Further

AjaxPhaseListenerRender generates:<script type="text/javascript" src="faces/ajax-textfield.js">script request: write out JavaScript to be included in JSP

public void afterPhase(PhaseEvent event) { String rootId = event.getFacesContext().getViewRoot().getViewId(); if (rootId.endsWith(SCRIPT_VIEW_ID)) { handleResourceRequest(event, "script.js","text/javascript"); } else if (rootId.endsWith(CSS_VIEW_ID)) { handleResourceRequest(event, "styles.css", "text/css"); } else if (rootId.indexOf(AJAX_VIEW_ID) != -1) { handleAjaxRequest(event); }}

Page 46: AJAX: Riding the Browser Based Horse a Little Further

jMaki Project

• Wrapping AJAX in JavaServer Faces> Using JSF components or JSF tags> Hides AJAX complexity from developer

• Currently supports components from> Dojo, Script.aculo.us, Yahoo UI Widgets, Spry DHTML

Goodies and Google

• Allows mix and match web components easily• Developers can create new jMaki components• NetBeans plugin• https://ajax.dev.java.net

Page 47: AJAX: Riding the Browser Based Horse a Little Further

Summary

Page 48: AJAX: Riding the Browser Based Horse a Little Further

Summary

• AJAX programming style helps makes web application more interactive

• Inherent problems with AJAX> Network latency, JavaScript support, browser issues, etc.

• JavaEE is a great platform for delivering AJAX applications> Only have to redevelop the client> Future versions of web technology will have tighter support

for AJAX

• Start small and don't over do it

Page 49: AJAX: Riding the Browser Based Horse a Little Further

Thank YouQuestions?