- Account
- Join for Free
- Sign In
- Help & Info
- Privacy Notice
- DMCA
- Contact Us
- Terms Of Use
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? 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 crequest/response d 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 ... more.
less.
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.<br><br> AJAX Components: Traditional Web vs. AJAX Examples of AJAX apps " Google maps http://maps.google.com/ " Zimbra: demo at http://www.zimbra.com " Goold Suggest http://www.google.com/webhp?complete=1&hl=en " ZUGGEST- an XMLHttp Experiment using Amazon http://www.francisshanahan.com/zuggest.aspx " Mashup housing want-ads (craglist.org)with Google maps http://www.housingmaps.com/ 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 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 ( cmethod d, cURL d, 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 ( cheader d) > Returns value of a given header " setRequestHeader ( clabel d, dvalue d) > 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 3 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) > xmlHttpRequest.open('GET', 'url' , false ) > Block the user interface and may freeze the browser for the duration of the request " Asynchronous mode (AJAX application) > xmlHttpRequest.open('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.<br><br> A client event occurs. 2. An XMLHttpRequest object is created and configured.<br><br> 3. The XMLHttpRequest object makes a call. 4.<br><br> The request is processed by the ValidateServlet. 5. The ValidateServlet returns an XML document containing the result.<br><br> 6. The XMLHttpRequest object calls the callback() function and processes the result. 7.<br><br> The HTML DOM is updated. " AJAX Guidelines 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 (http://dojotoolkit.org) > 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.<br><br> " 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.<br><br> 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?<br><br> > 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.<br><br> HTTP Methods " GET > When the data will not change " POST > When operation has cside-effects d 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.<br><br> Use plain text for when injecting content into the HTML. Use JavaScript to return object representations data. AJAX Consideration AJAX Consideration and Gotchas 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.<br><br> " 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 (http://www.xml.com/cs/user/view/cs_msg/2815) 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 req .open( cGET d, 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.<br><br> Although Google Suggest appears to make a request on each keystroke, closer examination reveals it is actually makes requests at regular time intervals " Don 9t assume the server is going to respond instantly > Network latency 3 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 Strategies and Best Practices: Practices: AutoComplete Using a Servlet 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?<br><br> index.jsp Page Auto-Complete Form 1. <form name="autofillform" action="autocomplete" method=" get "> 2. <input type="text" 3.<br><br> size="20" 4. autocomplete = "off" 5. id="complete-field" 6.<br><br> name="id" 7. onkeyup="doCompletion ();"> 8. <input id="submit_btn" type="Submit" value="Lookup Employee"> 9.<br><br> </form> AutoComplete Event Handler 1. function doCompletion () { 2. if (completeField.value == "") { 3.<br><br> clearTable(); 4. } else { 5. var url = "autocomplete?action=complete&id=" + escape (completeField.value); 6.<br><br> var req = initRequest (url); 7. req. onreadystatechange = function() { 8.<br><br> if (req. readyState == 4) { 9. if (req.<br><br> status == 200) { 10. parseMessages (req. responseXML ); 11.<br><br> } else if (req.status == 204){ 12. clearTable (); 13. }}}; 14.<br><br> req.open("GET", url, true) ; 15. req.send(null) ; 16. }} AutoComplete XMLHttpRequest 1.<br><br> function initRequest (url) { 2. if (window.XMLHttpRequest) { 3. return new XMLHttpRequest(); 4.<br><br> } else if (window.ActiveXObject) { 5. isIE = true; 6. return new ActiveXObject ("Microsoft.XMLHTTP"); 7.<br><br> } 8.} AutoComplete Servlet doGet() 1. public void doGet (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { ... 2.<br><br> String targetId = request.getParameter("id"); 3. Iterator it = employees.keySet().iterator(); 4. while (it.hasNext()) { 5.<br><br> EmployeeBean e = (EmployeeBean)employees.get((String)it.next()); 6. if ((e.getFirstName()... || e.getLastName()...) { 7.<br><br> sb.append("<employee>"); sb.append("<id>" + e.getId() + "</id>"); 8. sb.append("<firstName>" + e.getFirstName() + "</firstName>"); 9. sb.append("<lastName>" + e.getLastName() + "</lastName>"); 10.<br><br> sb.append("</employee>"); namesAdded = true; 11. } } 12. if (namesAdded) { 13.<br><br> response.setContentType("text/xml") ; 14. response.setHeader("Cache-Control", "no-cache" ); 15. response.getWriter().write ("<employees>" + sb.toString() + "</employees>"); 16.<br><br> } else { 17. response.setStatu s(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.<br><br> clearTable(); 3. var employees = responseXML.getElementsByTagName ("employees")[0]; 4. if (employees.childNodes.length > 0) { 5.<br><br> completeTable.setAttribute("bordercolor", "black"); 6. completeTable.setAttribute("border", "1"); 7. } else { 8.<br><br> clearTable(); 9. } 10. 11.<br><br> for (loop = 0; loop < employees.childNodes.length; loop++) { 12. var employee = employees.childNodes[loop]; 13. var firstName = employee.getElementsByTagName("firstName")[0]; 14.<br><br> var lastName = employee.getElementsByTagName("lastName")[0]; 15. var employeeId = employee.getElementsByTagName("id")[0]; 16. appendEmployee(firstName.childNodes[0].nodeValue,lastName.childNodes[0].<br><br> nodeValue, employeeId.childNodes[0].nodeValue); } } AutoComplete Update Demo Demo Auto complete Auto complete Strategies and Best Strategies and Best Practices: Practices: AutoComplete Using a JSF AutoComplete Using a JSF Component 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 " Control Content Rendering " Control of Server Side Logic " All in one component " Reusable " Usable in a tool " Hide AJAX complexity from page developers Benefits Include: AJAX With JavaServer" Faces ( cJavaServer Faces d) 1. AJAX using the JavaServer Faces architecture to process AJAX requests 2.<br><br> Servlet Controller to process AJAX requests 3. Retrofitting existing applications Architecture 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.<br><br> size="40" id="cityField" 3. completionMethod=" 4. #{ApplicationBean.completeName} " 5./> Server Side Logic for JSF Component 1.public String[] completeName() { 2.<br><br> ArrayList results = new ArrayList(); 3. Iterator it = employees.keySet().iterator(); 4. while (it.hasNext()) { 5.<br><br> EmployeeBean e = (EmployeeBean)employees.get((String)it.next()); 6. if ((e.getFirstName().toLowerCase().startsWith(targetId) || 7. e.getLastName().toLowerCase().startsWith(targetId)) && 8.<br><br> !targetId.equals( "" )) { 9. 10. results.add(e.getId() + " " + 11.<br><br> e.getFirstName() + 12. e.getLastName()); 13. } } 14.<br><br> 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.<br><br> ServletContext context = config.getServletContext(); 3. facesContextFactory = ( FacesContextFactory ) 4. FactoryFinder.getFactory (FactoryFinder.FACES_CONTEXT_FACTORY); 5.<br><br> LifecycleFactory lifecycleFactory = (LifecycleFactory) 6. FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY); 7. String lifecycleId = context.getInitParameter 8.<br><br> (FacesServlet.LIFECYCLE_ID_ATTR); 9. if (lifecycleId == null) { 10. lifecycleId = LifecycleFactory.DEFAULT_LIFECYCLE; 11.<br><br> } 12. lifecycle = lifecycleFactory.getLifecycle(lifecycleId); 13.} 14.public void doGet (HttpServletRequest request, HttpServletResponse response) 15. throws IOException, ServletException { 16.<br><br> FacesContext context = facesContextFactory.getFacesContext( 17. servletConfig.getServletContext(), 18. request, response, lifecycle); Finding a Managed Bean From the FacesContext 1.mybean bean = (mybean)getbean; 2....<br><br> 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 4Need to turn browser autocomplete off 4<input ...<br><br> 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 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 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 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 9t overdo it " You can use AJAX with your J2EE platform applications today For More Information " The BluePrints Solutions catalog on AJAX: > https://bpcatalog.dev.java.net/nonav/solutions.html " AJAX Q & A > https://blueprints.dev.java.net/ajax-faq.html " Asynchronous JavaScript Technology and XML (AJAX) With Java 2 Platform, Enterprise Edition > http://java.sun.com/developer/technicalArticles/J2EE/AJAX/inde x.html " AJAX Frameworks > http://ajaxpatterns.org/wiki/index.php?title=AJAXFrameworks " AJAX Library and Frameworks Comparison > http://wiki.osafoundation.org/bin/view/Projects/AjaxLibraries Cross Browser Resources " Cross Browser Discussion > http://www.quirksmode.org/index.html > http://www.ajaxian.com/archives/browsers/index.html " Cross Browser quirk > http://www.quirksmode.org/blog/archives/2005/09/xmlhttp " JavaScript libraries such as Dojo that makes these differences less painful > http://dojotoolkit.org/ Web-tier Programming Codecamp II : AJAX inyoung.cho@sun.com Technology Evangelist Sun Microsystems, Inc.