Slide Web thế hệ mới - Chapter 2.2 ajax basics tutorial

LI
lienhejb
0 lượt tải
43
0

Nội dung tài liệu

Trang 1

© 2007 Marty Hall© 2007 Marty Hall Ajax: The Basics Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/ajax.html Customized J2EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location. © 2007 Marty Hall© 2007 Marty Hall For live Ajax & GWT training, see training courses at http://courses.coreservlets.com/. Taught by the author of Core Servlets and JSP, More Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. • Courses developed and taught by Marty Hall – Java 5, Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF, Ajax, GWT, custom mix of topicsCustomized J2EE Training: http://courses.coreservlets.com/ • Courses developed and taught by coreservlets.com experts (edited by Marty) Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon.– Spring, Hibernate, EJB3, Ruby/Rails Developed and taught by well-known author and developer. At public venues or onsite at your location. Contact hall@coreservlets com for details goupee.com fb.com/groups/goupee

Trang 2

Topics in This Section • Ajax motivation • The basic Ajax process • Using dynamic content and JSP • Using dynamic content and servlets • Sending GET data • Sending POST data • Displaying HTML results • Parsing and displaying XML results • Toolkits 5 J2EE training: http://courses.coreservlets.com © 2007 Marty Hall© 2007 Marty Hall Motivation Customized J2EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location. goupee.com fb.com/groups/goupee

Trang 3

Why Ajax? • HTML and HTTP are weak – Non-interactive – Coarse-grained updates • Everyone wants to use a browser – Not a custom application • "Real" browser-based active content – Failed: Java Applets • Not universally supported; can't interact with the HTML – Serious alternative: Flash (and Flex) • Not yet universally supported; limited power – New and unproven • Microsoft Silverlight • JavaFX • Adobe Apollo 7 J2EE training: http://courses.coreservlets.com Google Suggest (http://labs.google.com/suggest/) 8 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 4

© 2007 Marty Hall© 2007 Marty Hall The Basic Process Customized J2EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location. The Basic Ajax Process • JavaScript – Define an object for sending HTTP requests – Initiate request • Get request object • Designate a response handler function – Supply as onreadystatechange attribute of request • Initiate a GET or POST request • Send data – Handle response • Wait for readyState of 4 and HTTP status of 200 • Extract return text with responseText or responseXML • Do something with result • HTML – Loads JavaScript – Designates control that initiates request 10 – Gives ids to input elements that will be read by scriptJ2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 5

Define a Request Object var request; function getRequestObject() { if (window.ActiveXObject) { return(new ActiveXObject("Microsoft.XMLHTTP")); } else if (window.XMLHttpRequest) { return(new XMLHttpRequest()); } else { return(null); Version for Internet Explorer } 5 and 6 } Object for Netscape 5+, Firefox, Opera, Safari, and Internet Explorer 7 Fails on older and nonstandard browsers 11 J2EE training: http://courses.coreservlets.com Initiate Request function sendRequest() { Response handler function name request = getRequestObject(); request.onreadystatechange = handleResponse; request.open("GET", "message-data.html", true); request.send(null); } URL of server-side resource Don't wait for response POST data (Send request asynchronously) (always null for GET) 12 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 6

Handle Response function handleResponse() { if (request.readyState == 4) { alert(request.responseText); } } Response is returned from server (handler gets invoked multiple times) Text of server response Pop up dialog box 13 J2EE training: http://courses.coreservlets.com Complete JavaScript Code (show-message.js) var request; function getRequestObject() { if (window.ActiveXObject) { return(new ActiveXObject("Microsoft.XMLHTTP")); } else if (window.XMLHttpRequest) { return(new XMLHttpRequest()); } else { return(null); } } function sendRequest() { request = getRequestObject(); request.onreadystatechange = handleResponse; request.open("GET", "message-data.html", true); request.send(null); } function handleResponse() { if (request.readyState == 4) { alert(request.responseText); } } 14 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 7

The Firefox JavaScript Console • Open via Tools Æ Error Console • Also see Venkman JavaScript debugger – http://www.mozilla.org/projects/venkman/ – https://addons.mozilla.org/firefox/216/ 15 J2EE training: http://courses.coreservlets.com HTML Code • Use xhtml, not HTML 4 – In order to manipulate it with 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 <script src="relative-url-of-JavaScript-file" type="text/javascript"></script> • Use separate </script> end tag • Designate control to initiate request <input type="button" value="button label" onclick="mainFunction()"/> 16 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 8

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"?> <!DOCTYPE html ...> <html xmlns="http://www.w3.org/1999/xhtml">...</html> – 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 – Scripts will not load if you use <script .../> instead of <script...></script> 17 J2EE training: http://courses.coreservlets.com HTML Code (show-message.html) <!DOCTYPE html PUBLIC "..." "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="show-message.js" type="text/javascript"></script> </head> <body> <center> <table border="1" bgcolor="gray"> <tr><th><big>Ajax: Simple Message</big></th></tr> </table> <p/> <form action="#"> <input type="button" value="Show Message" onclick="sendRequest()"/> </form> 18 </center></body></html> J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 9

HTML Code (message-data.html) Some random message • Note: executing this example – Since main page uses relative URL and HTML content 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. 19 J2EE training: http://courses.coreservlets.com The Basic Process: Results 20 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 10

© 2007 Marty Hall© 2007 Marty Hall Dynamic Content from JSP Customized J2EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon. 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 – Prevents functions from applying to multiple situations – Instead, make generic function and pass address to it • JavaScript file was in same folder as HTML – Makes it hard to reuse the JavaScript in different pages – 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 22 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 11

Steps • JavaScript – Define an object for sending HTTP requests – Initiate request • Get request object • Designate a response handler function – Supply as onreadystatechange attribute of request • Initiate a GET or POST request to a JSP page • Send data – Handle response • Wait for readyState of 4 and HTTP status of 200 • Extract return text with responseText or responseXML • Do something with result • HTML – Loads JavaScript from centralized directory – Designates control that initiates request 23 – Gives ids to input elements that will be read by scriptJ2EE training: http://courses.coreservlets.com Define a Request Object var request; function getRequestObject() { if (window.ActiveXObject) { return(new ActiveXObject("Microsoft.XMLHTTP")); } else if (window.XMLHttpRequest) { return(new XMLHttpRequest()); } else { return(null); } } No changes from previous example 24 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 12

Initiate Request function sendRequest(address) { request = getRequestObject(); request.onreadystatechange = showResponseAlert; 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.) 25 J2EE training: http://courses.coreservlets.com Handle Response function showResponseAlert() { if ((request.readyState == 4) && (request.status == 200)) { alert(request.responseText); } } Server response came back with no errors. (HTTP status code 200.) 26 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 13

Complete JavaScript Code (Part of ajax-basics.js) var request; function getRequestObject() { if (window.ActiveXObject) { return(new ActiveXObject("Microsoft.XMLHTTP")); } else if (window.XMLHttpRequest) { return(new XMLHttpRequest()); } else { return(null); } } function sendRequest(address) { request = getRequestObject(); request.onreadystatechange = showResponseAlert; request.open("GET", address, true); request.send(null); } function showResponseAlert() { if ((request.readyState == 4) && (request.status == 200)) { alert(request.responseText); } 27 } J2EE training: http://courses.coreservlets.com HTML Code • Loads JavaScript from central location <script src="../scripts/ajax-basics.js" type="text/javascript"></script> • Passes JSP address to main function <input type="button" value="Show Server Time" onclick='sendRequest("show-time.jsp")'/> • Uses style sheet <link rel="stylesheet" Note single quotes href="../css/styles.css" (Because of double type="text/css"/> quotes inside parens.) 28 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 14

HTML Code (show-time-1.html) <!DOCTYPE html PUBLIC "..." "http://www.w3.org/..."> <html xmlns="http://www.w3.org/1999/xhtml"> <head><title>Ajax: Time</title> <link rel="stylesheet" href="../css/styles.css" type="text/css"/> <script src="../scripts/ajax-basics.js" type="text/javascript"></script> </head> <body> ... <form action="#"> <input type="button" value="Show Server Time" onclick='sendRequest("show-time.jsp")'/> </form> 29 </center></body></html> J2EE training: http://courses.coreservlets.com JSP Code (show-time.jsp) <%= new java.util.Date() %> • Note: executing this example – You must run from Tomcat. • Otherwise JSP cannot execute 30 • Otherwise status code is -1, not 200 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 15

Message from JSP: Results 31 J2EE training: http://courses.coreservlets.com © 2007 Marty Hall© 2007 Marty Hall Dynamic Content from Servlet Customized J2EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location. goupee.com fb.com/groups/goupee

Trang 16

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 – Solution: send Cache-Control and Pragma headers • Date was not formatted – Just used the toString method of Date – Solution: use String.format (sprintf) and %t controls • JSP is wrong technology – JSP is best for lots of HTML and little or no logic/Java – But now we have logic but no HTML – Solution: use a servlet 33 J2EE training: http://courses.coreservlets.com Steps • JavaScript – Define an object for sending HTTP requests – Initiate request • Get request object • Designate a response handler function – Supply as onreadystatechange attribute of request • Initiate a GET or POST request to a servlet • Send data – Handle response • Wait for readyState of 4 and HTTP status of 200 • Extract return text with responseText or responseXML • Do something with result • HTML – Loads JavaScript from centralized directory – Designates control that initiates request 34 – Gives ids to input elements that will be read by scriptJ2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 17

Define a Request Object var request; function getRequestObject() { if (window.ActiveXObject) { return(new ActiveXObject("Microsoft.XMLHTTP")); } else if (window.XMLHttpRequest) { return(new XMLHttpRequest()); } else { return(null); } } No changes from previous example 35 J2EE training: http://courses.coreservlets.com Initiate Request function sendRequest(address) { request = getRequestObject(); request.onreadystatechange = showResponseAlert; request.open("GET", address, true); request.send(null); } No changes from previous example 36 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 18

Handle Response function showResponseAlert() { if ((request.readyState == 4) && (request.status == 200)) { alert(request.responseText); } } No changes from previous example 37 J2EE training: http://courses.coreservlets.com HTML Code (show-time-2.html) <!DOCTYPE html PUBLIC "..." "http://www.w3.org/..."> <html xmlns="http://www.w3.org/1999/xhtml"> <head><title>Ajax: Time</title> <link rel="stylesheet" href="../css/styles.css" type="text/css"/> <script src="../scripts/ajax-basics.js" type="text/javascript"></script> </head> Address of servlet. <body> (From url-pattern of ... servlet-mapping.) <form action="#"> <input type="button" value="Show Server Time" onclick='sendRequest("../show-time")'/> </form> </center></body></html> 38 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 19

Servlet Code package coreservlets; import ... public class ShowTime extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Cache-Control", "no-cache"); response.setHeader("Pragma", "no-cache"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); Date currentTime = new Date(); String message = String.format("It is now %tr on %tD.", currentTime, currentTime); out.print(message); } 39 } J2EE training: http://courses.coreservlets.com web.xml ... <servlet> <servlet-name>ShowTime</servlet-name> <servlet-class>coreservlets.ShowTime</servlet-class> </servlet> <servlet-mapping> <servlet-name>ShowTime</servlet-name> <url-pattern>/show-time</url-pattern> </servlet-mapping> ... 40 J2EE training: http://courses.coreservlets.com goupee.com fb.com/groups/goupee

Trang 20

Message from Servlet: Results 41 J2EE training: http://courses.coreservlets.com © 2007 Marty Hall© 2007 Marty Hall Sending GET Data Customized J2EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5, Java 6, etc. Ruby/Rails coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location. goupee.com fb.com/groups/goupee

Hiển thị 20 trang đầu. Tải tài liệu để xem đầy đủ.

Bình luận (0)

Đăng nhập để tham gia bình luận

Chưa có bình luận nào. Hãy là người đầu tiên!