Doris AJAX presentation for singapore
Upcoming SlideShare
Loading in...5

Doris AJAX presentation for singapore






Total Views
Views on SlideShare
Embed Views



1 Embed 1 1



Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

    Doris AJAX presentation for singapore Doris AJAX presentation for singapore Presentation Transcript

    • Web-tier Programming Codecamp II : AJAX Inyoung Cho Technology Evangelist Sun Microsystems, Inc.
    • Goal Learn how to architect and build rich web ™ applications using AJAX and J2EE technologies.
    • Agenda • What is AJAX? • AJAX Anatomy • AJAX Guidelines • AJAX Consideration and Gotchas • Strategies and Best Practices: > AutoComplete Using a Servlet > AutoComplete Using a JSF Component • AJAX Issues & Futures • Summary and Resources
    • What is AJAX?
    • Conventional Rich Web Application • Click, wait, and refresh user interaction > Page refreshes from the server needed for all events, data submissions, and navigation > Lost of operation context during refresh > Excessive server load and bandwidth consumption • Synchronous “request/response” communication model > Browser always initiates the request > The user has to wait for the response -- Slow response • Lack of two-way, real-time communication capability for server initiated updates • Plugins, applets, or browser black magic
    • 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 apps: > Dramatic improvement in user interface > "Partial screen update" replaces the "click, wait, and refresh" user interaction model
    • User Interface: Traditional Web vs. AJAX
    • Components: Traditional Web vs. AJAX
    • Examples of AJAX apps • Google maps • Zimbra: demo at • Goold Suggest • ZUGGEST- an XMLHttp Experiment using Amazon • Mashup housing want-ads ( Google maps
    • 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
    • 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
    • AJAX Anatomy
    • Things Needed 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 > 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 JavaScript • HTTP > XMLHttpRequest
    • Characteristics of XMLHttpRequest • Communication may be GET/POST • 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
    • 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 content type > Setting this to text/xml with make your life easier in almost all implementations
    • 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
    • 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
    • Synchronous Versus Asynchronous • Synchronous mode (not AJAX application) >'GET', 'url' , false) > Block the user interface and may freeze the browser for the duration of the request • Asynchronous mode (AJAX application) >'GET', 'url', true) >Get a callback when the data has been received > Browser continue to work and requests processed in background • Requests can be made asynchronously or synchronously > both techniques allow web page to be updated without refreshing > 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
    • Anatomy of an AJAX Request
    • Steps of An AJAX 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. •
    • AJAX Guidelines
    • AJAX Guidelines • Usability • JavaScript Libraries • I18n • State Management • HTTP methods • Return content-types
    • Usability • Back/Forward button meaningless • Refresh button can kill your app > Save state in <body onload> method • Bookmarking/URL sharing not working • Printing dynamically rendered pages can be problematic • JavaScript framework Dojo toolkit ( > provides API's history manipulation and navigation control > provides client-side for bookmarking and URL manipulation • Requires thinking about interface and interaction > Usability is the key > Do not break what the user is focusing on > Make sure to give the user feedback > Do not over-use it Recommendation: Consider the meaning of each and weigh the benefits when designing your application.
    • JavaScript Libraries • There are differences in javascript implementations • Serializing complex data and mapping it to javascript isn't a trival task • Directly consuming xml in Javascript can be painful due to browser differences in technologies like xslt • Dojo: a key focus on user experience • Prototype: focuses more on AJAX interactions > JavaScript objects and utility methods (request, update, periodic_update) • DWR(Dynamic Web Remoting): both client-side and server-side framework > do RPC calls from client-side JavaScript to Java objects in a web container server side > Framework support, DHTML manipulation, servlet access
    • Internationalization (I18n) • Page Content Type <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> • Use JavaScript encodeURI() when building URLs or sending localizable content. • Call HttpServletRequest.setCharacterEncoding("UTF-8") before retrieving any parameters from Java EE Recommendation: Use UTF-8 since it supports the widest number of languages and browsers.
    • Externalize Content from Java Code • Content types > HTML markup > CSS > JavaScript • Embedding in Output >Class-Loader >Request Dispatcher • Render Links in the Page Recommendation: If all possible do not in-line content in Java code. Externalize CSS styles to make HTML more flexible.
    • State Management • On Client > In memory in JavaScript Objects > In hidden form variables > In cookies • On Server > HttpSession > Persisted • How do you handle state + sessions? > Can all be on the client so you can have truly stateless servers? > What happens if the server or network dies? Recommendation: Consider keeping non-secure state related to the rendering of the client on the client. Keep secure persistent state on the server.
    • HTTP Methods • GET > When the data will not change • POST > When operation has “side-effects” and changes the state on the server. Recommendation: Follow the HTTP idempotency rules.
    • Response Content Type • XML • Text > Post processing on client > Inject directly into the page • JavaScript > Evaluated in JavaScript using eval() > JavaScript object representations of data(JSON) Recommendation: Use XML for structured portable data. Use plain text for when injecting content into the HTML. Use JavaScript to return object representations data.
    • AJAX Consideration and Gotchas
    • Browsers support • Need XmlHttpRequest browser support • Mozilla Firefox 1.0 and above • Netscape version 7.1 and above • Apple Safari 1.2 and above. • Microsoft Internet Exporer 5 and above • Konqueror (Unix) • Opera 7.6 and above
    • Cross Browser Support • Support in cross browser -- a defacto manner > no public standard defining AJAX • Major difference: manner in which you obtain a new XMLHttpRequest instance • Using AJAX requires cross browser testing • Using a component model such in JavaServer Faces will also make using AJAX less difficult > JSF component model allows you hide most of the JavaScript/DHTML/CSS from the page developers
    • AJAX/XMLhttp Initiate //XMLthttp variable will hold the XMLHttpRequest object var xmlhttp = false; // If the user is using Mozilla/Firefox/Safari if (window.XMLHttpRequest) { //Intiate the object xmlhttp = new XMLHttpRequest(); //Set the mime type xmlhttp.overrideMimeType('text/xml'); } // If the user is using IE else if (window.ActiveXObject) { //Intiate the object xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
    • AJAX readyState function callback() { if (req.readyState == 4) { if (req.status == 200) { // update the HTML DOM based on whether or not message is valid } } } • readyState has a few odd quirks • No browser correctly supports readyState in all cases > Won't impact standard xmlhttp scripts, but be careful with readyStates other than 4
    • Multiple Requests: Thread Safe Implementation ( 01 function send(url, callback) { 02 //Use an inner function to hold the local variables and 03 //perform the actual callback 04 function bindCallback() { 05 //Check readyState and status 06 processResult(req.responseXML); 07 } 08 09 //Define some local variables to hold the params 10 var req = //get an instance of XMLHttpRequest 11 var processResult = callback; 12 13 req.onreadystate = bindCallback; 14“GET”, url, true); 15 req.send(null); 16 }
    • 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 • 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
    • Things You May not Like • Big problems could easily arise from a user disabling JavaScript in their browsers! • Comlexity > Server side developers will need to understand that presentation logic will be required in the HTML client pages as well as in the server-side logic > HTML page developers must have JavaScript technology skills • Browser differences - not completely standardized • Not yet official part of any spec • Debugging - java code on server mixes with JavaScript on the client • Source is in plain view > Security? • Latest generation of browsers required
    • Strategies and Best Practices: AutoComplete Using a Servlet
    • AutoComplete Using a Servlet How can you provide a better means of navigating a large set of data based on a search query?
    • index.jsp Page Auto-Complete Form 1. <form name="autofillform" action="autocomplete" method="get"> 2. <input type="text" 3. size="20" 4. autocomplete="off" 5. id="complete-field" 6. name="id" 7. onkeyup="doCompletion();"> 8. <input id="submit_btn" type="Submit" value="Lookup Employee"> 9. </form>
    • AutoComplete Event Handler 1. function doCompletion() { 2. if (completeField.value == "") { 3. clearTable(); 4. } else { 5. var url = "autocomplete?action=complete&id=" + escape (completeField.value); 6. var req = initRequest(url); 7. req.onreadystatechange = function() { 8. if (req.readyState == 4) { 9. if (req.status == 200) { 10. parseMessages(req.responseXML); 11. } else if (req.status == 204){ 12. clearTable(); 13. }}}; 14."GET", url, true); 15. req.send(null); 16. }}
    • AutoComplete XMLHttpRequest 1. function initRequest(url) { 2. if (window.XMLHttpRequest) { 3. return new XMLHttpRequest(); 4. } else if (window.ActiveXObject) { 5. isIE = true; 6. return new ActiveXObject ("Microsoft.XMLHTTP"); 7. } 8.}
    • AutoComplete Servlet doGet() 1. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ... 2. String targetId = request.getParameter("id"); 3. Iterator it = employees.keySet().iterator(); 4. while (it.hasNext()) { 5. EmployeeBean e = (EmployeeBean)employees.get((String); 6. if ((e.getFirstName()... || e.getLastName()...) { 7. sb.append("<employee>"); sb.append("<id>" + e.getId() + "</id>"); 8. sb.append("<firstName>" + e.getFirstName() + "</firstName>"); 9. sb.append("<lastName>" + e.getLastName() + "</lastName>"); 10. sb.append("</employee>"); namesAdded = true; 11. }} 12. if (namesAdded) { 13. response.setContentType("text/xml"); 14. response.setHeader("Cache-Control", "no-cache"); 15. response.getWriter().write("<employees>" + sb.toString() + "</employees>"); 16. } else { 17. response.setStatus(HttpServletResponse.SC_NO_CONTENT); } }
    • Browser, DOM and JavaScript • Browsers maintain an object representation of the documents being displayed (referred to as the Document Object Model or 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 • 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 servlet is available to JavaScript technology code using the req.responseXML, where req is an XMLHttpRequest object
    • AutoComplete parseMessages 1.function parseMessages(responseXML) { 2. clearTable(); 3. var employees = responseXML.getElementsByTagName("employees")[0]; 4. if (employees.childNodes.length > 0) { 5. completeTable.setAttribute("bordercolor", "black"); 6. completeTable.setAttribute("border", "1"); 7. } else { 8. clearTable(); 9. } 10. 11. for (loop = 0; loop < employees.childNodes.length; loop++) { 12. var employee = employees.childNodes[loop]; 13. var firstName = employee.getElementsByTagName("firstName")[0]; 14. var lastName = employee.getElementsByTagName("lastName")[0]; 15. var employeeId = employee.getElementsByTagName("id")[0]; 16. appendEmployee(firstName.childNodes[0].nodeValue,lastName.childNodes[0]. nodeValue, employeeId.childNodes[0].nodeValue); } }
    • AutoComplete Update
    • Demo Auto complete
    • Strategies and Best Practices: AutoComplete Using a JSF Component
    • Why need a Framework or Toolkit? • There are differences in javascript implementations • Serializing complex data and mapping it to javascript isn't a trival task • Directly consuming xml in Javascript can be painful due to browser differences in technologies like xslt
    • JSF Component Approach Benefits Include: • Control Content Rendering • Control of Server Side Logic • All in one component • Reusable • Usable in a tool • Hide AJAX complexity from page developers
    • AJAX With JavaServer™ Faces (“JavaServer Faces”) Architecture 1.AJAX using the JavaServer Faces architecture to process AJAX requests 2.Servlet Controller to process AJAX requests 3.Retrofitting existing applications
    • 1. JSF Component That Renders Client-side AJAX Script and Processes AJAX Requests • AJAX is built into the lifecycle • Everything is handled by the JSF environment • JSF environment with a phase listener used to return initial JavaScript technology • JSF environment with a phase listener processes AJAX requests • View state from a page may also be accessed
    • Anatomy of an AJAX enabled JSF Component
    • AJAX Processing With a JSF Component
    • Page Developer's View of JSF Component 1.<ajaxTags:completionField 2. size="40" id="cityField" 3. completionMethod=" 4. #{ApplicationBean.completeName}" 5./>
    • Server Side Logic for JSF Component 1.public String[] completeName() { 2. ArrayList results = new ArrayList(); 3. Iterator it = employees.keySet().iterator(); 4. while (it.hasNext()) { 5. EmployeeBean e = (EmployeeBean)employees.get((String); 6. if ((e.getFirstName().toLowerCase().startsWith(targetId) || 7. e.getLastName().toLowerCase().startsWith(targetId)) && 8. !targetId.equals("")) { 9. 10. results.add(e.getId() + " " + 11. e.getFirstName() + 12. e.getLastName()); 13. } } 14. return (String[])results.toArray();}
    • 2. JSF Component That Uses Separate Servlet • Avoids JSF lifecycle > Performance > Risk • More difficult deployment • Beware of JSF technology interactions • JSF technology life-cycle events are not incurred
    • Architecture of a JavaServer Faces Component with separate AJAX Controller
    • 3. Retrofitting Existing Applications • Customizable but not easily re-usable • Capable of evaluating expressions and using managed beans • Mapping JSF ids to HTML ids • JSF technology life-cycle events are not incurred • May be used outside of a JSF platform interface runtime
    • AjaxServlet + JSF Components
    • Finding the JSF Faces Components From the AjaxServlet 1.public void init(ServletConfig config) throws ServletException { 2. ServletContext context = config.getServletContext(); 3. facesContextFactory = (FacesContextFactory) 4. FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY); 5. LifecycleFactory lifecycleFactory = (LifecycleFactory) 6. FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY); 7. String lifecycleId = context.getInitParameter 8. (FacesServlet.LIFECYCLE_ID_ATTR); 9. if (lifecycleId == null) { 10. lifecycleId = LifecycleFactory.DEFAULT_LIFECYCLE; 11. } 12. lifecycle = lifecycleFactory.getLifecycle(lifecycleId); 13.} 14.public void doGet(HttpServletRequest request, HttpServletResponse response) 15. throws IOException, ServletException { 16. FacesContext context = facesContextFactory.getFacesContext( 17. servletConfig.getServletContext(), 18. request, response, lifecycle);
    • Finding a Managed Bean From the FacesContext 1.mybean bean = (mybean)getbean; 2.... 3.protected Object getbean(FacesContext context, String name) { 4. return context.getApplication().getVariableResolver() .resolveVariable(context, name); 5.} 6.
    • General JSF Component Issues • Validation messages should use same CSS styles and elements as JSF components • Syncing up state in the HTML DOM and JSF interface • AutoComplete—Need to turn browser autocomplete off—<input ... autocomplete="off"/> • Each JSF component should have shareable JavaScript technology and CSS rendering • Encapsulate the XMLHttpRequest and callback functions to prevent JavaScript technology conflicts
    • AJAX Issues & Futures
    • AJAX Futures • AJAX-enabled JSF Component libraries • Standardization of XMLHttpRequest • More best practices in the programming model • Better browser support and tool support > Debugging and testing • Framework support and new frameworks • Performance and Security
    • Demo
    • DEMO • Google Mapviwer in Creator • Blueprints solutions in NetBeans • Create a AJAX enabled JSF components using Sun Java Studio Creator • zimbra
    • Summary and Resources
    • Summary • AJAX helps make applications more interactive • J2EE technology is a great platform for AJAX applications • AJAX does not come for free • Start small and don’t overdo it • You can use AJAX with your J2EE platform applications today
    • For More Information • The BluePrints Solutions catalog on AJAX: > • AJAX Q & A > • Asynchronous JavaScript Technology and XML (AJAX) With Java 2 Platform, Enterprise Edition > x.html • AJAX Frameworks > • AJAX Library and Frameworks Comparison >
    • Cross Browser Resources • Cross Browser Discussion > > • Cross Browser quirk > • JavaScript libraries such as Dojo that makes these differences less painful >
    • Web-tier Programming Codecamp II : AJAX Technology Evangelist Sun Microsystems, Inc.