SlideShare una empresa de Scribd logo
1 de 24
Descargar para leer sin conexión
© 2008 Marty Hall




                Ajax: The Basics
                      Part II
           Originals of Slides and Source Code for Examples:
       http://courses.coreservlets.com/Course-Materials/ajax.html

                 Customized Java EE Training: http://courses.coreservlets.com/
  Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
   Developed and taught by well-known author and developer. At public venues or onsite at your location.




                                                                                                              © 2008 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 topics
                 Customized Java EE 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 or 6, etc. Spring/Hibernate coming soon.
              Spring, Hibernate, EJB3, Ruby/Rails
   Developed and taught by well-known author and developer.compublic venues or onsite at your location.
                                          Contact hall@coreservlets
                                                                    At for details
Topics in This Section
    •   Sending GET data
    •   Reading textfield values
    •   Sending POST data
    •   Ajax toolkits and libraries
    •   Ajax books




4                                                              Java EE training: http://courses.coreservlets.com




                                                                                                 © 2008 Marty Hall




                    Sending GET Data

                       Customized Java EE Training: http://courses.coreservlets.com/
          Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
           Developed and taught by well-known author and developer. At public venues or onsite at your location.
Servlet Example:
    Design Deficiencies
    • No data sent from HTML page to servlet
      – Solution: attach data to end of the URL (GET data)
           • Use normal GET format:
               – mainaddress?var1=val1&var2=val2


    • Notes
      – In next examples we will get data from input fields, but
        for now we will embed it directly in the URL
      – If you have an quot;" in a URL in xhtml, you are required to
        replace it with quot;"
      – To read the data on the server, servlet does
        request.getParameter as usual

6                                                Java EE training: http://courses.coreservlets.com




    Steps
    • JavaScript
      – Define an object for sending HTTP requests
      – Initiate request
           • Get request object
           • Designate an anonymous response handler function
           • Initiate a GET or POST request to a servlet
               – URL has GET data attached to the end
      – Handle response
           • Wait for readyState of 4 and HTTP status of 200
           • Extract return text with responseText or responseXML
           • Use innerHTML to insert result into designated element
    • HTML
      –   Load JavaScript from centralized directory
      –   Designate control that initiates request
      –   Give ids to input elements
7
      –   Define a blank placeholder element with a known id
                                                 Java EE training: http://courses.coreservlets.com
Define a Request Object

    function getRequestObject() {
      if (window.ActiveXObject) {
        return(new ActiveXObject(quot;Microsoft.XMLHTTPquot;));
      } else if (window.XMLHttpRequest) {
        return(new XMLHttpRequest());
      } else {
        return(null);
      }
    }
                             No changes from previous examples




8                                      Java EE training: http://courses.coreservlets.com




     Initiate Request

    function ajaxResult(address, resultRegion) {
      var request = getRequestObject();
      request.onreadystatechange =
        function() { showResponseText(request,
                                      resultRegion); };
      request.open(quot;GETquot;, address, true);
      request.send(null);
    }



                             No changes from previous example.
                             The difference is the address, which
                             will be passed in from HTML page.


9                                      Java EE training: http://courses.coreservlets.com
Handle Response
     function showResponseText(request, resultRegion) {
       if ((request.readyState == 4) &&
           (request.status == 200)) {
         htmlInsert(resultRegion, request.responseText);
       }
     }

     function htmlInsert(id, htmlData) {
       document.getElementById(id).innerHTML = htmlData;
     }



                             Changed slightly from previous section:
                             now uses htmlInsert helper function.


10                                     Java EE training: http://courses.coreservlets.com




      HTML Code

     ...
     <fieldset>
       <legend>
         Sending Fixed GET Data, Result Shown in HTML
       </legend>
       <form action=quot;#quot;>
         <input type=quot;buttonquot; value=quot;Show Chicago Timequot;
                 onclick='ajaxResult
                           (quot;show-time-in-city?city=Chicagoquot;,
                            quot;chicago-timequot;)'/>
       </form>
       <div id=quot;chicago-timequot;></div>
     </fieldset>
     ...



11                                     Java EE training: http://courses.coreservlets.com
Servlet Code
     • Servlet reads the quot;cityquot; parameter
        – Uses this to determine time zone
        – Unknown or missing city results in error message
     • Servlet generates HTML markup
        – Rather than returning an ordinary string to be inserted
          into the div, returns text with xhtml tags
           • Provides more control over the final result
           • Remember to be check that the final result is legal in xhtml
               – Tags should be lowercase
               – Be aware of nesting rules (e.g., block-level elements allowed inside
                 div and td, but only inline elements allowed inside p or span)




12                                              Java EE training: http://courses.coreservlets.com




      Servlet Code
     public class ShowTimeInCity extends HttpServlet {
       public void doGet(HttpServletRequest request,
                         HttpServletResponse response)
           throws ServletException, IOException {
         response.setHeader(quot;Cache-Controlquot;, quot;no-cachequot;);
         response.setHeader(quot;Pragmaquot;, quot;no-cachequot;);
         PrintWriter out = response.getWriter();
         String cityName = request.getParameter(quot;cityquot;);
         String message = CityUtils.getTime(cityName);
         if (message.startsWith(quot;Inquot;)) { // Found city
           message =
             String.format(quot;<hr/><h2>%s</h2><hr/>quot;, message);
         } else { // No city or unknown city
           message =
             String.format(quot;<h2 class='error'>%s</h2>quot;, message);
         }
         out.print(message);
       }
     }
13                                              Java EE training: http://courses.coreservlets.com
CityUtils Class
     • Maintains a table of cities and associated
       time zones (populations also – used later)
       – Given the name of a city, it finds the difference in hours
         between that city's time and server time (east coast USA)
     • Computes server time
       – Using standard GregorianCalendar class
     • Converts to time in that city
       – By calling the quot;addquot; method with the time zone offset
     • Formats the time and day
       – Using String.format with %tr and %tD


       – Reminder: full source code is online
14        • http://courses.coreservlets.com/Course-Materials/ajax.html
                                          Java EE training: http://courses.coreservlets.com




     Sending GET Data: Results




15                                                 Java EE training: http://courses.coreservlets.com
© 2008 Marty Hall




               Reading User Input
               (and Embedding it
                  in GET Data)
                      Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     GET Example: Design Deficiencies
     • City name was always Chicago
       – Solution: send user data
          • Give an id to textfield
                – <input type=quot;textquot; id=quot;someIDquot;/>
                – The id is not the same as the textfield name. The name is used
                  only in regular form submissions, which does not apply to Ajax.
          • Read data from textfield
                – document.getElementById(someID).value
     • Textfields can have spaces and other
       characters that are illegal in URLs
       – Solution: filter (escape) textfield data
          • Call quot;escapequot; to convert spaces and other special chars
          • Put result into the GET data
          • Request URL with embedded GET data
17                                                            Java EE training: http://courses.coreservlets.com
Summary of New Features
     • Read a textfield value
        – userInput = document.getElementById(someID).value;
             • The value property works for textfields and most other input
               elements. But for radio buttons and checkboxes, the value is
               either quot;onquot; or empty. We will show examples of this later
     • Escape spaces and other special characters
        – userInput = escape(userInput);
     • Put data into the URL
        – url = baseURL + quot;?someName=quot; + userInput;
             • For multiple input elements, put quot;&quot; between name/value pairs.
     • Send out request and process result
        – No changes from previous examples
     • Helper function
     function getValue(id) {
       return(escape(document.getElementById(id).value));
     }
18                                                        Java EE training: http://courses.coreservlets.com




      Steps
     • JavaScript
        – Define an object for sending HTTP requests
        – Initiate request
             • Get request object
             • Designate an anonymous response handler function
             • Initiate a GET or POST request to a servlet
                 – URL has GET data attached to the end
                 – Data based on document.getElementById(id).value of some textfield
        – Handle response
             • Wait for readyState of 4 and HTTP status of 200
             • Extract return text with responseText or responseXML
             • Use innerHTML to insert result into designated element
     • HTML
        –   Load JavaScript from centralized directory
        –   Designate control that initiates request
        –   Give ids to input elements
        –   Defines a blank placeholder element with a known id
19                                                        Java EE training: http://courses.coreservlets.com
Define a Request Object

     function getRequestObject() {
       if (window.ActiveXObject) {
         return(new ActiveXObject(quot;Microsoft.XMLHTTPquot;));
       } else if (window.XMLHttpRequest) {
         return(new XMLHttpRequest());
       } else {
         return(null);
       }
     }
                              No changes from previous examples




20                                     Java EE training: http://courses.coreservlets.com




      Initiate Request
     function showTimeInCity(inputField, resultRegion) {
       var baseAddress = quot;show-time-in-cityquot;;
       var data = quot;city=quot; + getValue(inputField);
       var address = baseAddress + quot;?quot; + data;
       ajaxResult(address, resultRegion);
     }

     function ajaxResult(address, resultRegion) {
       var request = getRequestObject();
       request.onreadystatechange =
         function() { showResponseText(request,
                                       resultRegion); };
       request.open(quot;GETquot;, address, true);
       request.send(null);
     }

                                        The ajaxResult function is unchanged
                                        from previous example
21                                     Java EE training: http://courses.coreservlets.com
Handle Response
     function showResponseText(request, resultRegion) {
       if ((request.readyState == 4) &&
           (request.status == 200)) {
         htmlInsert(resultRegion, request.responseText);
       }
     }


                        No changes from previous example




22                                       Java EE training: http://courses.coreservlets.com




      HTML Code
     ...
     <fieldset>
       <legend>
         Sending Dynamic GET Data, Result Shown in HTML
       </legend>
       <form action=quot;#quot;>
         <label>City: <input type=quot;textquot; id=quot;city-1quot;/>
         </label><br/>
         <input type=quot;buttonquot; value=quot;Show City Timequot;
                 onclick='showTimeInCity(quot;city-1quot;,
                                         quot;city-1-timequot;)'/>
       </form>
       <div id=quot;city-1-timequot;></div>
     </fieldset>
     ...


23                                       Java EE training: http://courses.coreservlets.com
Style Sheet Code
     h2 { color: #440000;
         font-weight: bold;
         font-size: 18px;
         font-family: Arial, Helvetica, sans-serif;
     }
     .error { background-color: yellow;
             color: red;
             font-weight: bold;
             font-size: 20px;
             font-family: Arial, Helvetica, sans-serif;
             border-style: inset;
     }




24                                        Java EE training: http://courses.coreservlets.com




      Servlet Code
     public class ShowTimeInCity extends HttpServlet {
       public void doGet(HttpServletRequest request,
                         HttpServletResponse response)
           throws ServletException, IOException {
         response.setHeader(quot;Cache-Controlquot;, quot;no-cachequot;);
         response.setHeader(quot;Pragmaquot;, quot;no-cachequot;);
         PrintWriter out = response.getWriter();
         String cityName = request.getParameter(quot;cityquot;);
         String message = CityUtils.getTime(cityName);
         if (message.startsWith(quot;Inquot;)) { // Found city
           message =
             String.format(quot;<hr/><h2>%s</h2><hr/>quot;, message);
         } else { // No city or unknown city
           message =
             String.format(quot;<h2 class='error'>%s</h2>quot;, message);
         }
         out.print(message);
       }                             No changes from previous example
     }
25                                        Java EE training: http://courses.coreservlets.com
Reading User Input: Results
     (Good Data)




26                      Java EE training: http://courses.coreservlets.com




     Reading User Input: Results
     (Bad Data)




27                      Java EE training: http://courses.coreservlets.com
© 2008 Marty Hall




                Sending POST Data

                      Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     GET vs. POST
     • In normal Web pages, there are compelling
       reasons for choosing POST or GET
          • POST
                –   URL is simpler
                –   Data is hidden from people looking over your shoulder
                –   Larger amounts of data can be sent
                –   Can send special characters (e.g., in uploaded files)
          • GET
                – Can bookmark results page
     • With Ajax, end users don't see URL, so
       choice is relatively arbitrary
       – Unless there is a very large amount of data, in which case
         POST is preferred

29                                                            Java EE training: http://courses.coreservlets.com
Sending POST Data in JavaScript
     • Collect data from form
        – Give ids to input elements
             <input type=quot;textquot; id=quot;some-idquot;/>
        – Read data
             var value1 = document.getElementById(quot;some-idquot;).value;
        – URL-encode data and form into query string
             var data = quot;var1=quot; + escape(value1);
     • Specify POST instead of GET in quot;openquot;
             request.open(quot;POSTquot;, address, true);
     • Specify form encoding type
             request.setRequestHeader(quot;Content-Typequot;,
                              quot;application/x-www-form-urlencodedquot;);
     • Supply data in quot;sendquot;
             request.send(data);
30                                                  Java EE training: http://courses.coreservlets.com




      Steps
     • JavaScript
        – Define an object for sending HTTP requests
        – Initiate request
             • Get request object
             • Designate an anonymous response handler function
             • Initiate a POST request to a servlet
                 – Put POST data in the send method
                 – Data based on document.getElementById(id).value of some textfield
        – Handle response
             • Wait for readyState of 4 and HTTP status of 200
             • Extract return text with responseText or responseXML
             • Use innerHTML to insert result into designated element
     • HTML
        –   Load JavaScript from centralized directory
        –   Designate control that initiates request
        –   Give ids to input elements
        –   Define a blank placeholder element with a known id
31                                                  Java EE training: http://courses.coreservlets.com
Define a Request Object

     function getRequestObject() {
       if (window.ActiveXObject) {
         return(new ActiveXObject(quot;Microsoft.XMLHTTPquot;));
       } else if (window.XMLHttpRequest) {
         return(new XMLHttpRequest());
       } else {
         return(null);
       }
     }
                              No changes from previous examples




32                                     Java EE training: http://courses.coreservlets.com




      Initiate Request
     function showTimeInCityPost(inputField, resultRegion) {
       var address = quot;show-time-in-cityquot;;
       var data = quot;city=quot; + getValue(inputField);
       ajaxResultPost(address, data, resultRegion);
     }

     function ajaxResultPost(address, data, resultRegion) {
       var request = getRequestObject();
       request.onreadystatechange =
         function() { showResponseText(request,
                                       resultRegion); };
       request.open(quot;POSTquot;, address, true);
       request.setRequestHeader
                      (quot;Content-Typequot;,
                       quot;application/x-www-form-urlencodedquot;);
       request.send(data);
     }
33                                     Java EE training: http://courses.coreservlets.com
Handle Response
     function showResponseText(request, resultRegion) {
       if ((request.readyState == 4) &&
           (request.status == 200)) {
         htmlInsert(resultRegion, request.responseText);
       }
     }


                        No changes from previous example




34                                       Java EE training: http://courses.coreservlets.com




      HTML Code
     ...
     <fieldset>
       <legend>
         Sending Dynamic POST Data, Result Shown in HTML
       </legend>
       <form action=quot;#quot;>
         <label>City: <input type=quot;textquot; id=quot;city-2quot;/>
         </label><br/>
         <input type=quot;buttonquot; value=quot;Show City Timequot;
                 onclick='showTimeInCityPost(quot;city-2quot;,
                                            quot;city-2-timequot;)'/>
       </form>
       <div id=quot;city-2-timequot;></div>
     </fieldset>
     ...


35                                       Java EE training: http://courses.coreservlets.com
Servlet Code
     public class ShowTimeInCity extends HttpServlet {
       public void doGet(HttpServletRequest request,
                         HttpServletResponse response)
           throws ServletException, IOException {
         // Shown in previous examples
       }

         public void doPost(HttpServletRequest request,
                            HttpServletResponse response)
             throws ServletException, IOException {
           doGet(request, response);
         }
     }



                                    No changes from previous example
36                                     Java EE training: http://courses.coreservlets.com




         Reading User Input: Results
         (Good Data)




37                                     Java EE training: http://courses.coreservlets.com
Reading User Input: Results
     (Bad Data)




38                                                          Java EE training: http://courses.coreservlets.com




                                                                                              © 2008 Marty Hall




                             Ajax Toolkits
                             and Libraries

                    Customized Java EE Training: http://courses.coreservlets.com/
       Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
        Developed and taught by well-known author and developer. At public venues or onsite at your location.
Client-Side Tools
     (JavaScript Libraries with Ajax Support)
     • Prototype
       – http://www.prototypejs.org/
     • Dojo
       – http://www.dojotoolkit.org/
     • script.aculo.us
       – http://script.aculo.us/
     • ExtJS
       – http://extjs.com/
     • Yahoo User Interface Library (YUI)
       – http://developer.yahoo.com/yui/

40                                      Java EE training: http://courses.coreservlets.com




     Server-Side Tools
     • Direct Web Remoting
       – Lets you call Java methods semi-directly from JavaScript
       – http://getahead.ltd.uk/dwr/
     • JSON/JSON-RPC
       – For sending data to/from JavaScript with less parsing
       – http://www.json.org/
       – http://json-rpc.org/




41                                      Java EE training: http://courses.coreservlets.com
Hybrid Client/Server Tools
     • JSP custom tag libraries
       – Create tags that generate HTML and JavaScript
       – http://courses.coreservlets.com/
         Course-Materials/msajsp.html
     • AjaxTags (built on top of script.aculo.us)
       – JSP custom tags that generate Ajax functionality
          • Supports many powerful Ajax capabilities with very simple
            syntax
          • http://ajaxtags.sourceforge.net
     • Google Web Toolkit
       – Write code in Java, translate it to JavaScript
          • http://code.google.com/webtoolkit/
       – Also see https://ajax4jsf.dev.java.net/
          • GWT/JSF Integration Toolkit
42                                        Java EE training: http://courses.coreservlets.com




     JSF-Based Tools
     • Trinidad (formerly Oracle ADF)
       – http://www.oracle.com/technology/products/jdev/htdocs/
         partners/addins/exchange/jsf/ (also myfaces.apache.org)
     • Tomahawk
       – http://myfaces.apache.org/tomahawk/
     • Ajax4JSF (and RichFaces)
       – http://labs.jboss.com/jbossajax4jsf/
     • IceFaces
       – http://www.icefaces.org/
     • Build your own
       – http://courses.coreservlets.com/Course-Materials/jsf.html
43                                        Java EE training: http://courses.coreservlets.com
Books
      (In Rough Order of Preference)
     • Ajax in Practice
        – Crane et al. Manning.
     • JavaScript: The Definitive Guide
        – Flanagan. O'Reilly.
     • Foundations of Ajax
        – Asleson and Schutta. APress.
     • Ajax in Action
        – Crane, Pascarello, and James. Manning.
     • GWT in Action
        – Hanson and Tacy. Manning.
     • Pro JSF and Ajax
        – Jacobi and Fallows. APress.
     • Prototype and Scriptaculous in Action
        – Crane et al. Manning.
     • Pro Ajax and Java Frameworks
        – Schutta and Asleson. APress.
     • Professional Ajax
44      – Zakas, et al. Wrox. Wait for 2nd edition.Java EE training: http://courses.coreservlets.com




                                                                                                     © 2008 Marty Hall




                                                Wrapup

                           Customized Java EE Training: http://courses.coreservlets.com/
              Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
               Developed and taught by well-known author and developer. At public venues or onsite at your location.
Preview of Next Section
     • Ajax Development and Debugging
       Environments
          –   Tools for debugging Ajax
          –   Tools for debugging JavaScript
          –   Tools for building Ajax-based Web apps
          –   Tools for developing xhtml
          –   Tools for building and previewing style sheets
          –   Tools for validating xhtml




46                                                                 Java EE training: http://courses.coreservlets.com




         Summary
     •   JavaScript
          – Define request object
               • Check for both Microsoft and non-MS objects. Identical in all apps.
          – Initiate request
               •   Get request object
               •   Designate an anonymous response handler function
               •   Read user data with getElementById(id).value, then escape it
               •   Initiate a GET or POST request
                     – If POST, set Content-Type and put data in send method
                     – If GET, append data on end of address after quot;?quot;
          – Handle response
               • Wait for readyState of 4 and HTTP status of 200
               • Extract return text with responseText
               • Do something with result
                     – Use innerHTML to insert result into designated element
     •   HTML
          – Give ids to input elements and to result region. Initiate process.
     •   Java
          – Use JSP, servlet, or combination (MVC) as appropriate.
          – Prevent browser caching.
47                                                                 Java EE training: http://courses.coreservlets.com
© 2008 Marty Hall




                         Questions?

             Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon.
 Developed and taught by well-known author and developer. At public venues or onsite at your location.

Más contenido relacionado

La actualidad más candente

15 expression-language
15 expression-language15 expression-language
15 expression-languagesnopteck
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, mavenFahad Golra
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basicssnopteck
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web SocketsFahad Golra
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server PageVipin Yadav
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final) Hitesh-Java
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Som Prakash Rai
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsIMC Institute
 
Java script Examples by Som
Java script Examples by Som  Java script Examples by Som
Java script Examples by Som Som Prakash Rai
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGESKalpana T
 
Ruby On Rails Tutorial
Ruby On Rails TutorialRuby On Rails Tutorial
Ruby On Rails Tutorialsunniboy
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsKaml Sah
 

La actualidad más candente (20)

15 expression-language
15 expression-language15 expression-language
15 expression-language
 
Lecture 5 JSTL, custom tags, maven
Lecture 5   JSTL, custom tags, mavenLecture 5   JSTL, custom tags, maven
Lecture 5 JSTL, custom tags, maven
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
Lecture 6 Web Sockets
Lecture 6   Web SocketsLecture 6   Web Sockets
Lecture 6 Web Sockets
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
JSP - Part 2 (Final)
JSP - Part 2 (Final) JSP - Part 2 (Final)
JSP - Part 2 (Final)
 
Resthub lyonjug
Resthub lyonjugResthub lyonjug
Resthub lyonjug
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Java Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom TagsJava Web Programming [5/9] : EL, JSTL and Custom Tags
Java Web Programming [5/9] : EL, JSTL and Custom Tags
 
Java script Examples by Som
Java script Examples by Som  Java script Examples by Som
Java script Examples by Som
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
 
JAVA SERVER PAGES
JAVA SERVER PAGESJAVA SERVER PAGES
JAVA SERVER PAGES
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
Ruby On Rails Tutorial
Ruby On Rails TutorialRuby On Rails Tutorial
Ruby On Rails Tutorial
 
J2EE jsp_01
J2EE jsp_01J2EE jsp_01
J2EE jsp_01
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Java server pages
Java server pagesJava server pages
Java server pages
 
10 jsp-scripting-elements
10 jsp-scripting-elements10 jsp-scripting-elements
10 jsp-scripting-elements
 

Similar a Ajax Basics 2

03 form-data
03 form-data03 form-data
03 form-datasnopteck
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Ramamohan Chokkam
 
05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web FrameworkLuther Baker
 
Karate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter ThomasKarate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter Thomasintuit_india
 
Boston Computing Review - Java Server Pages
Boston Computing Review - Java Server PagesBoston Computing Review - Java Server Pages
Boston Computing Review - Java Server PagesJohn Brunswick
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqelajobandesther
 
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajaxs_pradeep
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 

Similar a Ajax Basics 2 (20)

03 form-data
03 form-data03 form-data
03 form-data
 
Json generation
Json generationJson generation
Json generation
 
Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268Automatically generating-json-from-java-objects-java-objects268
Automatically generating-json-from-java-objects-java-objects268
 
Lecture5
Lecture5Lecture5
Lecture5
 
Prototype-1
Prototype-1Prototype-1
Prototype-1
 
05 status-codes
05 status-codes05 status-codes
05 status-codes
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web Framework
 
Karate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter ThomasKarate for Complex Web-Service API Testing by Peter Thomas
Karate for Complex Web-Service API Testing by Peter Thomas
 
Jsp
JspJsp
Jsp
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
Ajax
AjaxAjax
Ajax
 
I Feel Pretty
I Feel PrettyI Feel Pretty
I Feel Pretty
 
Boston Computing Review - Java Server Pages
Boston Computing Review - Java Server PagesBoston Computing Review - Java Server Pages
Boston Computing Review - Java Server Pages
 
Networking and Data Access with Eqela
Networking and Data Access with EqelaNetworking and Data Access with Eqela
Networking and Data Access with Eqela
 
JEE Programming - 05 JSP
JEE Programming - 05 JSPJEE Programming - 05 JSP
JEE Programming - 05 JSP
 
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax
 
14 mvc
14 mvc14 mvc
14 mvc
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 

Último

Falcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business GrowthFalcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business GrowthFalcon investment
 
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...rajveerescorts2022
 
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...amitlee9823
 
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876dlhescort
 
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...lizamodels9
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsP&CO
 
Business Model Canvas (BMC)- A new venture concept
Business Model Canvas (BMC)-  A new venture conceptBusiness Model Canvas (BMC)-  A new venture concept
Business Model Canvas (BMC)- A new venture conceptP&CO
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizharallensay1
 
Malegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
Malegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort ServiceMalegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
Malegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort ServiceDamini Dixit
 
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756dollysharma2066
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Sheetaleventcompany
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...Aggregage
 
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...Falcon Invoice Discounting
 
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 MonthsSEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 MonthsIndeedSEO
 
Falcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to ProsperityFalcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to Prosperityhemanthkumar470700
 
Whitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
Whitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLWhitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
Whitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLkapoorjyoti4444
 
Falcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investorsFalcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investorsFalcon Invoice Discounting
 
Phases of Negotiation .pptx
 Phases of Negotiation .pptx Phases of Negotiation .pptx
Phases of Negotiation .pptxnandhinijagan9867
 
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...allensay1
 

Último (20)

Falcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business GrowthFalcon Invoice Discounting: Empowering Your Business Growth
Falcon Invoice Discounting: Empowering Your Business Growth
 
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
👉Chandigarh Call Girls 👉9878799926👉Just Call👉Chandigarh Call Girl In Chandiga...
 
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
Call Girls Jp Nagar Just Call 👗 7737669865 👗 Top Class Call Girl Service Bang...
 
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
Call Girls in Delhi, Escort Service Available 24x7 in Delhi 959961-/-3876
 
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
Call Girls From Pari Chowk Greater Noida ❤️8448577510 ⊹Best Escorts Service I...
 
Value Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and painsValue Proposition canvas- Customer needs and pains
Value Proposition canvas- Customer needs and pains
 
Business Model Canvas (BMC)- A new venture concept
Business Model Canvas (BMC)-  A new venture conceptBusiness Model Canvas (BMC)-  A new venture concept
Business Model Canvas (BMC)- A new venture concept
 
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al MizharAl Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
Al Mizhar Dubai Escorts +971561403006 Escorts Service In Al Mizhar
 
Malegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
Malegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort ServiceMalegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
Malegaon Call Girls Service ☎ ️82500–77686 ☎️ Enjoy 24/7 Escort Service
 
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Majnu Ka Tilla, Delhi Contact Us 8377877756
 
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
Chandigarh Escorts Service 📞8868886958📞 Just📲 Call Nihal Chandigarh Call Girl...
 
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
The Path to Product Excellence: Avoiding Common Pitfalls and Enhancing Commun...
 
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
Unveiling Falcon Invoice Discounting: Leading the Way as India's Premier Bill...
 
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 MonthsSEO Case Study: How I Increased SEO Traffic & Ranking by 50-60%  in 6 Months
SEO Case Study: How I Increased SEO Traffic & Ranking by 50-60% in 6 Months
 
Falcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to ProsperityFalcon's Invoice Discounting: Your Path to Prosperity
Falcon's Invoice Discounting: Your Path to Prosperity
 
(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7
(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7
(Anamika) VIP Call Girls Napur Call Now 8617697112 Napur Escorts 24x7
 
Whitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
Whitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRLWhitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
Whitefield CALL GIRL IN 98274*61493 ❤CALL GIRLS IN ESCORT SERVICE❤CALL GIRL
 
Falcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investorsFalcon Invoice Discounting: The best investment platform in india for investors
Falcon Invoice Discounting: The best investment platform in india for investors
 
Phases of Negotiation .pptx
 Phases of Negotiation .pptx Phases of Negotiation .pptx
Phases of Negotiation .pptx
 
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
Call Girls Service In Old Town Dubai ((0551707352)) Old Town Dubai Call Girl ...
 

Ajax Basics 2

  • 1. © 2008 Marty Hall Ajax: The Basics Part II Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/ajax.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location. © 2008 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 topics Customized Java EE 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 or 6, etc. Spring/Hibernate coming soon. Spring, Hibernate, EJB3, Ruby/Rails Developed and taught by well-known author and developer.compublic venues or onsite at your location. Contact hall@coreservlets At for details
  • 2. Topics in This Section • Sending GET data • Reading textfield values • Sending POST data • Ajax toolkits and libraries • Ajax books 4 Java EE training: http://courses.coreservlets.com © 2008 Marty Hall Sending GET Data Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 3. Servlet Example: Design Deficiencies • No data sent from HTML page to servlet – Solution: attach data to end of the URL (GET data) • Use normal GET format: – mainaddress?var1=val1&var2=val2 • Notes – In next examples we will get data from input fields, but for now we will embed it directly in the URL – If you have an quot;&quot; in a URL in xhtml, you are required to replace it with quot;&amp;quot; – To read the data on the server, servlet does request.getParameter as usual 6 Java EE training: http://courses.coreservlets.com Steps • JavaScript – Define an object for sending HTTP requests – Initiate request • Get request object • Designate an anonymous response handler function • Initiate a GET or POST request to a servlet – URL has GET data attached to the end – Handle response • Wait for readyState of 4 and HTTP status of 200 • Extract return text with responseText or responseXML • Use innerHTML to insert result into designated element • HTML – Load JavaScript from centralized directory – Designate control that initiates request – Give ids to input elements 7 – Define a blank placeholder element with a known id Java EE training: http://courses.coreservlets.com
  • 4. Define a Request Object function getRequestObject() { if (window.ActiveXObject) { return(new ActiveXObject(quot;Microsoft.XMLHTTPquot;)); } else if (window.XMLHttpRequest) { return(new XMLHttpRequest()); } else { return(null); } } No changes from previous examples 8 Java EE training: http://courses.coreservlets.com Initiate Request function ajaxResult(address, resultRegion) { var request = getRequestObject(); request.onreadystatechange = function() { showResponseText(request, resultRegion); }; request.open(quot;GETquot;, address, true); request.send(null); } No changes from previous example. The difference is the address, which will be passed in from HTML page. 9 Java EE training: http://courses.coreservlets.com
  • 5. Handle Response function showResponseText(request, resultRegion) { if ((request.readyState == 4) && (request.status == 200)) { htmlInsert(resultRegion, request.responseText); } } function htmlInsert(id, htmlData) { document.getElementById(id).innerHTML = htmlData; } Changed slightly from previous section: now uses htmlInsert helper function. 10 Java EE training: http://courses.coreservlets.com HTML Code ... <fieldset> <legend> Sending Fixed GET Data, Result Shown in HTML </legend> <form action=quot;#quot;> <input type=quot;buttonquot; value=quot;Show Chicago Timequot; onclick='ajaxResult (quot;show-time-in-city?city=Chicagoquot;, quot;chicago-timequot;)'/> </form> <div id=quot;chicago-timequot;></div> </fieldset> ... 11 Java EE training: http://courses.coreservlets.com
  • 6. Servlet Code • Servlet reads the quot;cityquot; parameter – Uses this to determine time zone – Unknown or missing city results in error message • Servlet generates HTML markup – Rather than returning an ordinary string to be inserted into the div, returns text with xhtml tags • Provides more control over the final result • Remember to be check that the final result is legal in xhtml – Tags should be lowercase – Be aware of nesting rules (e.g., block-level elements allowed inside div and td, but only inline elements allowed inside p or span) 12 Java EE training: http://courses.coreservlets.com Servlet Code public class ShowTimeInCity extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader(quot;Cache-Controlquot;, quot;no-cachequot;); response.setHeader(quot;Pragmaquot;, quot;no-cachequot;); PrintWriter out = response.getWriter(); String cityName = request.getParameter(quot;cityquot;); String message = CityUtils.getTime(cityName); if (message.startsWith(quot;Inquot;)) { // Found city message = String.format(quot;<hr/><h2>%s</h2><hr/>quot;, message); } else { // No city or unknown city message = String.format(quot;<h2 class='error'>%s</h2>quot;, message); } out.print(message); } } 13 Java EE training: http://courses.coreservlets.com
  • 7. CityUtils Class • Maintains a table of cities and associated time zones (populations also – used later) – Given the name of a city, it finds the difference in hours between that city's time and server time (east coast USA) • Computes server time – Using standard GregorianCalendar class • Converts to time in that city – By calling the quot;addquot; method with the time zone offset • Formats the time and day – Using String.format with %tr and %tD – Reminder: full source code is online 14 • http://courses.coreservlets.com/Course-Materials/ajax.html Java EE training: http://courses.coreservlets.com Sending GET Data: Results 15 Java EE training: http://courses.coreservlets.com
  • 8. © 2008 Marty Hall Reading User Input (and Embedding it in GET Data) Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location. GET Example: Design Deficiencies • City name was always Chicago – Solution: send user data • Give an id to textfield – <input type=quot;textquot; id=quot;someIDquot;/> – The id is not the same as the textfield name. The name is used only in regular form submissions, which does not apply to Ajax. • Read data from textfield – document.getElementById(someID).value • Textfields can have spaces and other characters that are illegal in URLs – Solution: filter (escape) textfield data • Call quot;escapequot; to convert spaces and other special chars • Put result into the GET data • Request URL with embedded GET data 17 Java EE training: http://courses.coreservlets.com
  • 9. Summary of New Features • Read a textfield value – userInput = document.getElementById(someID).value; • The value property works for textfields and most other input elements. But for radio buttons and checkboxes, the value is either quot;onquot; or empty. We will show examples of this later • Escape spaces and other special characters – userInput = escape(userInput); • Put data into the URL – url = baseURL + quot;?someName=quot; + userInput; • For multiple input elements, put quot;&quot; between name/value pairs. • Send out request and process result – No changes from previous examples • Helper function function getValue(id) { return(escape(document.getElementById(id).value)); } 18 Java EE training: http://courses.coreservlets.com Steps • JavaScript – Define an object for sending HTTP requests – Initiate request • Get request object • Designate an anonymous response handler function • Initiate a GET or POST request to a servlet – URL has GET data attached to the end – Data based on document.getElementById(id).value of some textfield – Handle response • Wait for readyState of 4 and HTTP status of 200 • Extract return text with responseText or responseXML • Use innerHTML to insert result into designated element • HTML – Load JavaScript from centralized directory – Designate control that initiates request – Give ids to input elements – Defines a blank placeholder element with a known id 19 Java EE training: http://courses.coreservlets.com
  • 10. Define a Request Object function getRequestObject() { if (window.ActiveXObject) { return(new ActiveXObject(quot;Microsoft.XMLHTTPquot;)); } else if (window.XMLHttpRequest) { return(new XMLHttpRequest()); } else { return(null); } } No changes from previous examples 20 Java EE training: http://courses.coreservlets.com Initiate Request function showTimeInCity(inputField, resultRegion) { var baseAddress = quot;show-time-in-cityquot;; var data = quot;city=quot; + getValue(inputField); var address = baseAddress + quot;?quot; + data; ajaxResult(address, resultRegion); } function ajaxResult(address, resultRegion) { var request = getRequestObject(); request.onreadystatechange = function() { showResponseText(request, resultRegion); }; request.open(quot;GETquot;, address, true); request.send(null); } The ajaxResult function is unchanged from previous example 21 Java EE training: http://courses.coreservlets.com
  • 11. Handle Response function showResponseText(request, resultRegion) { if ((request.readyState == 4) && (request.status == 200)) { htmlInsert(resultRegion, request.responseText); } } No changes from previous example 22 Java EE training: http://courses.coreservlets.com HTML Code ... <fieldset> <legend> Sending Dynamic GET Data, Result Shown in HTML </legend> <form action=quot;#quot;> <label>City: <input type=quot;textquot; id=quot;city-1quot;/> </label><br/> <input type=quot;buttonquot; value=quot;Show City Timequot; onclick='showTimeInCity(quot;city-1quot;, quot;city-1-timequot;)'/> </form> <div id=quot;city-1-timequot;></div> </fieldset> ... 23 Java EE training: http://courses.coreservlets.com
  • 12. Style Sheet Code h2 { color: #440000; font-weight: bold; font-size: 18px; font-family: Arial, Helvetica, sans-serif; } .error { background-color: yellow; color: red; font-weight: bold; font-size: 20px; font-family: Arial, Helvetica, sans-serif; border-style: inset; } 24 Java EE training: http://courses.coreservlets.com Servlet Code public class ShowTimeInCity extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader(quot;Cache-Controlquot;, quot;no-cachequot;); response.setHeader(quot;Pragmaquot;, quot;no-cachequot;); PrintWriter out = response.getWriter(); String cityName = request.getParameter(quot;cityquot;); String message = CityUtils.getTime(cityName); if (message.startsWith(quot;Inquot;)) { // Found city message = String.format(quot;<hr/><h2>%s</h2><hr/>quot;, message); } else { // No city or unknown city message = String.format(quot;<h2 class='error'>%s</h2>quot;, message); } out.print(message); } No changes from previous example } 25 Java EE training: http://courses.coreservlets.com
  • 13. Reading User Input: Results (Good Data) 26 Java EE training: http://courses.coreservlets.com Reading User Input: Results (Bad Data) 27 Java EE training: http://courses.coreservlets.com
  • 14. © 2008 Marty Hall Sending POST Data Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location. GET vs. POST • In normal Web pages, there are compelling reasons for choosing POST or GET • POST – URL is simpler – Data is hidden from people looking over your shoulder – Larger amounts of data can be sent – Can send special characters (e.g., in uploaded files) • GET – Can bookmark results page • With Ajax, end users don't see URL, so choice is relatively arbitrary – Unless there is a very large amount of data, in which case POST is preferred 29 Java EE training: http://courses.coreservlets.com
  • 15. Sending POST Data in JavaScript • Collect data from form – Give ids to input elements <input type=quot;textquot; id=quot;some-idquot;/> – Read data var value1 = document.getElementById(quot;some-idquot;).value; – URL-encode data and form into query string var data = quot;var1=quot; + escape(value1); • Specify POST instead of GET in quot;openquot; request.open(quot;POSTquot;, address, true); • Specify form encoding type request.setRequestHeader(quot;Content-Typequot;, quot;application/x-www-form-urlencodedquot;); • Supply data in quot;sendquot; request.send(data); 30 Java EE training: http://courses.coreservlets.com Steps • JavaScript – Define an object for sending HTTP requests – Initiate request • Get request object • Designate an anonymous response handler function • Initiate a POST request to a servlet – Put POST data in the send method – Data based on document.getElementById(id).value of some textfield – Handle response • Wait for readyState of 4 and HTTP status of 200 • Extract return text with responseText or responseXML • Use innerHTML to insert result into designated element • HTML – Load JavaScript from centralized directory – Designate control that initiates request – Give ids to input elements – Define a blank placeholder element with a known id 31 Java EE training: http://courses.coreservlets.com
  • 16. Define a Request Object function getRequestObject() { if (window.ActiveXObject) { return(new ActiveXObject(quot;Microsoft.XMLHTTPquot;)); } else if (window.XMLHttpRequest) { return(new XMLHttpRequest()); } else { return(null); } } No changes from previous examples 32 Java EE training: http://courses.coreservlets.com Initiate Request function showTimeInCityPost(inputField, resultRegion) { var address = quot;show-time-in-cityquot;; var data = quot;city=quot; + getValue(inputField); ajaxResultPost(address, data, resultRegion); } function ajaxResultPost(address, data, resultRegion) { var request = getRequestObject(); request.onreadystatechange = function() { showResponseText(request, resultRegion); }; request.open(quot;POSTquot;, address, true); request.setRequestHeader (quot;Content-Typequot;, quot;application/x-www-form-urlencodedquot;); request.send(data); } 33 Java EE training: http://courses.coreservlets.com
  • 17. Handle Response function showResponseText(request, resultRegion) { if ((request.readyState == 4) && (request.status == 200)) { htmlInsert(resultRegion, request.responseText); } } No changes from previous example 34 Java EE training: http://courses.coreservlets.com HTML Code ... <fieldset> <legend> Sending Dynamic POST Data, Result Shown in HTML </legend> <form action=quot;#quot;> <label>City: <input type=quot;textquot; id=quot;city-2quot;/> </label><br/> <input type=quot;buttonquot; value=quot;Show City Timequot; onclick='showTimeInCityPost(quot;city-2quot;, quot;city-2-timequot;)'/> </form> <div id=quot;city-2-timequot;></div> </fieldset> ... 35 Java EE training: http://courses.coreservlets.com
  • 18. Servlet Code public class ShowTimeInCity extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Shown in previous examples } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } } No changes from previous example 36 Java EE training: http://courses.coreservlets.com Reading User Input: Results (Good Data) 37 Java EE training: http://courses.coreservlets.com
  • 19. Reading User Input: Results (Bad Data) 38 Java EE training: http://courses.coreservlets.com © 2008 Marty Hall Ajax Toolkits and Libraries Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 20. Client-Side Tools (JavaScript Libraries with Ajax Support) • Prototype – http://www.prototypejs.org/ • Dojo – http://www.dojotoolkit.org/ • script.aculo.us – http://script.aculo.us/ • ExtJS – http://extjs.com/ • Yahoo User Interface Library (YUI) – http://developer.yahoo.com/yui/ 40 Java EE training: http://courses.coreservlets.com Server-Side Tools • Direct Web Remoting – Lets you call Java methods semi-directly from JavaScript – http://getahead.ltd.uk/dwr/ • JSON/JSON-RPC – For sending data to/from JavaScript with less parsing – http://www.json.org/ – http://json-rpc.org/ 41 Java EE training: http://courses.coreservlets.com
  • 21. Hybrid Client/Server Tools • JSP custom tag libraries – Create tags that generate HTML and JavaScript – http://courses.coreservlets.com/ Course-Materials/msajsp.html • AjaxTags (built on top of script.aculo.us) – JSP custom tags that generate Ajax functionality • Supports many powerful Ajax capabilities with very simple syntax • http://ajaxtags.sourceforge.net • Google Web Toolkit – Write code in Java, translate it to JavaScript • http://code.google.com/webtoolkit/ – Also see https://ajax4jsf.dev.java.net/ • GWT/JSF Integration Toolkit 42 Java EE training: http://courses.coreservlets.com JSF-Based Tools • Trinidad (formerly Oracle ADF) – http://www.oracle.com/technology/products/jdev/htdocs/ partners/addins/exchange/jsf/ (also myfaces.apache.org) • Tomahawk – http://myfaces.apache.org/tomahawk/ • Ajax4JSF (and RichFaces) – http://labs.jboss.com/jbossajax4jsf/ • IceFaces – http://www.icefaces.org/ • Build your own – http://courses.coreservlets.com/Course-Materials/jsf.html 43 Java EE training: http://courses.coreservlets.com
  • 22. Books (In Rough Order of Preference) • Ajax in Practice – Crane et al. Manning. • JavaScript: The Definitive Guide – Flanagan. O'Reilly. • Foundations of Ajax – Asleson and Schutta. APress. • Ajax in Action – Crane, Pascarello, and James. Manning. • GWT in Action – Hanson and Tacy. Manning. • Pro JSF and Ajax – Jacobi and Fallows. APress. • Prototype and Scriptaculous in Action – Crane et al. Manning. • Pro Ajax and Java Frameworks – Schutta and Asleson. APress. • Professional Ajax 44 – Zakas, et al. Wrox. Wait for 2nd edition.Java EE training: http://courses.coreservlets.com © 2008 Marty Hall Wrapup Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 23. Preview of Next Section • Ajax Development and Debugging Environments – Tools for debugging Ajax – Tools for debugging JavaScript – Tools for building Ajax-based Web apps – Tools for developing xhtml – Tools for building and previewing style sheets – Tools for validating xhtml 46 Java EE training: http://courses.coreservlets.com Summary • JavaScript – Define request object • Check for both Microsoft and non-MS objects. Identical in all apps. – Initiate request • Get request object • Designate an anonymous response handler function • Read user data with getElementById(id).value, then escape it • Initiate a GET or POST request – If POST, set Content-Type and put data in send method – If GET, append data on end of address after quot;?quot; – Handle response • Wait for readyState of 4 and HTTP status of 200 • Extract return text with responseText • Do something with result – Use innerHTML to insert result into designated element • HTML – Give ids to input elements and to result region. Initiate process. • Java – Use JSP, servlet, or combination (MVC) as appropriate. – Prevent browser caching. 47 Java EE training: http://courses.coreservlets.com
  • 24. © 2008 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Java 5 or 6, etc. Spring/Hibernate coming soon. Developed and taught by well-known author and developer. At public venues or onsite at your location.