SlideShare une entreprise Scribd logo
1  sur  20
Télécharger pour lire hors ligne
© 2009 Marty Hall




         The AjaxTags Library:
          Advanced Features
            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, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
   Developed and taught by well-known author and developer. At public venues or onsite at your location.




                                                                                                                © 2009 Marty Hall




 For live Ajax & GWT training, see training
courses at http://courses.coreservlets.com/.
          t htt //                l t       /
      Taught by the author of Core Servlets and JSP, More
     Servlets and JSP and this tutorial. Available at public
                  JSP,          tutorial
     venues, or customized versions can be held on-site at
                       your organization.
    •C
     Courses d
             developed and t
                 l   d d taught b M t H ll
                             ht by Marty Hall
           – Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x & 2.0, Ajax, GWT, custom mix of topics
           – Ajax courses can concentrate on EElibrary (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo) or survey several
                  Customized Java one Training: http://courses.coreservlets.com/
    • Courses developed and taught by coreservlets.com experts (edited by Marty)
  Servlets, – Spring, Hibernate/JPA, 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
            JSP, JSF 1.x & JSF 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
Topics in This Section
    • Regions that display temporarily while
      server-side resource runs
              id
    • Autocomplete textboxes with associated
      values displayed in other textboxes
    • Prefunctions and postfunctions
      – Arbitrary JavaScript that runs before or after server-side
                                                       server side
        resource
    • Functions that run when server has error
    • Multiple triggers for server-side resources


4




                                                                                                 © 2009 Marty Hall




                            Setup/Review

                      Customized Java EE Training: http://courses.coreservlets.com/
        Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
         Developed and taught by well-known author and developer. At public venues or onsite at your location.
Installation
    • Several required JAR files
       – In Eclipse: WebContent/WEB-INF/lib
       – In deployed app: WEB-INF/lib
       – Download from http://ajaxtags sourceforge net/
                         http://ajaxtags.sourceforge.net/
    • Prototype and Scriptaculous JS files
       – In Eclipse: WebContent/scripts
       – In deployed app: scripts
       – Download from http://script.aculo.us/
    • Simple installation
       – Download prebuilt starting-point project:
         ajaxtags-blank.zip
          j t     bl k i
          • Download from
6
            http://courses.coreservlets.com/Course-Materials/ajax.html




     Basic Setup: advanced.jsp
     (Covered in Previous Lecture)
    <!DOCTYPE ...>
    <%@ taglib uri="http://ajaxtags org/tags/ajax"
                uri http://ajaxtags.org/tags/ajax
                prefix="ajax" %>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type"
           content="text/html;charset=UTF-8"" />
    <jsp:include page="/WEB-INF/includes/header.jsp"/>
    ...
    <title>Advanced AjaxTags Examples</title>
    </head>
    <body>
    <b d >
      ...
    </body></html>



7
Basic Setup: header.jsp
     (Covered in Previous Lecture)
    <% request.setAttribute("contextPath",
                             request.getContextPath());
                             request getContextPath()); %>
    <script src="${contextPath}/scripts/prototype-1.4.0.js"
             type="text/javascript"></script>
    <script src="${contextPath}/scripts/scriptaculous.js"
         p         {            }     p        p          j
             type="text/javascript"></script>
    <script src="${contextPath}/scripts/overlibmws.js"
             type="text/javascript"></script>
    <script src="${contextPath}/scripts/ajaxtags-1.2-beta2.js"
             type="text/javascript"></script>
    <link rel="stylesheet"
           href="${contextPath}/css/styles.css"
           h f "${    t tP th}/     / t l       "
           type="text/css"/>




8




                                                                                                  © 2009 Marty Hall




        ajax:autocomplete with
               indicator

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.
Basic Idea
     • Approach
        – indicator attribute designates section (usually div or span)
          that will be enabled while results are being loaded
           • It is disabled to start with and disabled again when results
                                     with,
             come back
           • Often contains animated GIF showing progress
     • Main use
        – Gives user feedback when server-side resource takes a
          long time
             g
     • Note
        – You can reproduce indicator region in other places by
          using Effect.Show from Scriptaculous
           • See later lectures on Scriptaculous
10




      JSP Example
     <fieldset>
       <legend>ajax:autocomplete with indicator</legend>
          g     j          p                    / g
       <form>
         <label for="language">Programming language:</label>
         <input type="text" name="language" id="language"/>
         <span id "indicatorRegion" style "display:none;">
               id="indicatorRegion" style="display:none;">
           <img src="${contextPath}/images/busy-indicator.gif"/>
           Loading...
         </span>
       </form>
       <ajax:autocomplete
         source="language"
         target= language
         target="language"
         baseUrl="${contextPath}/slow-language-completer.ajax"
         className="autocomplete"
         minimumCharacters="1"
         indicator="indicatorRegion"/>
     </fieldset>

11
Server-Side Code
     public class SlowLanguageCompleter          LanguageCompleter
                                                 shown in previous
         extends LanguageCompleter {             section
       @Override
       public String getXmlContent(HttpServletRequest request,
                                   HttpServletResponse
       response)
           throws Exception {
         try { Thread.sleep(5000); } catch(Exception e) {}
           y              p(    )         (    p          )
         return(super.getXmlContent(request, response));
       }
     }




12




      Results




13
© 2009 Marty Hall




        ajax:autocomplete with
             Linked Fields

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     Basic Idea
     • Approach
       –S
        Server-side resource returns a list with names that are
                 id                    li    ih         h
        different from values
          • xmlBuilder.addItem("name1", "value1");
          • I last section, names and values were th same
            In l t    ti            d l            the
                 – When name selected from dropdown, that name (value) put into
                   the textfield that has the dropdown
       – Names shown in dropdown box under main textfield
       – When a value is selected from dropdown, secondary
         value placed into a different textfield
     • M i uses
       Main
       – When you have auxiliary information to display to user
          • E.g., show description when catalog ID selected
              g,             p                g
       – When you have associated values
          • E.g., word in another language
15
JSP Example
     <fieldset>
       <legend>ajax:autocomplete with linked fields</legend>
       <form>
          <label for="englishAnimal">English animal:</label>
          <input type="text" id="englishAnimal"/>
                 type text id englishAnimal />
          <label for="spanishAnimal">Spanish animal:</label>
          <input type="text" id="spanishAnimal"/>
       </form>
        /
       <ajax:autocomplete
          source="englishAnimal"
          target="spanishAnimal"
          baseUrl="${contextPath}/animal-completer.ajax"
          parameters="englishAnimal={englishAnimal}"
          className="autocomplete"
          minimumCharacters="1"/>
     </fieldset>
16




      Server-Side Code
     import javax.servlet.http.*;
     import org ajaxtags helpers *;
            org.ajaxtags.helpers. ;
     import org.ajaxtags.servlets.*;

     p
     public class AnimalCompleter extends BaseAjaxServlet {
                           p                   j
       @Override
       public String getXmlContent(HttpServletRequest request,
                                   HttpServletResponse response)
           throws Exception {
         String animalPrefix =
           request.getParameter("englishAnimal");
         String animalList = makeAnimalList(animalPrefix);
         St i     i lLi t      k A i lLi t( i lP fi )
         return(animalList);
       }




17
Server-Side Code (Continued)
         private static final String[][] animals =
         { {"aardvark", "aardvark"},{"alligator", "cocodrilo"},
            { aardvark , aardvark },{ alligator , cocodrilo },
            {"antelope", "antílopo"}, {"baboon", "babuino"},
            {"bat", "murciélago"}, {"bear", "oso"}, {"cat", "gato"},
            {"camel", "camello"}, {"conch", "concha"}
         };
         private String makeAnimalList(String animalPrefix) {
            animalPrefix = animalPrefix.toUpperCase();
            AjaxXmlBuilder builder = new AjaxXmlBuilder();
            for(String[] animalPair: animals) {
              String englishAnimal = animalPair[0];
              String spanishAnimal = animalPair[1];
              if(englishAnimal.toUpperCase().startsWith(animalPrefix)) {
                builder.addItem(englishAnimal, spanishAnimal);
              }
            }
            return(builder.toString());
         }
18   }




         Results




19
© 2009 Marty Hall




           ajax:updateField with
               p
               postFunction

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     Basic Idea
     • Approach
       – Y li a regular JavaScript function as the value of the
         You list      l J S i f           i    h    l    f h
         postFunction or preFunction attribute
          • Almost all tags support postFunction and preFunction
       – The postFunction fires after the server-side resource is
         finished
       – The preFunction fires just before the server-side resource
              p                j
         is called
     • Main uses
       – preFunction
          • To make an “I am working” message or image
          • Form field validation
       – postFunction
          • To highlight results or show a success message
21
Script
     • scripts/postFunction.js
        – N that i i using scriptaculous calls
          Note h it is i      i     l      ll
        function showConversionSuccess() {
          // Temporarily highlight Celsius and Kelvin fields
                p       y  g   g
          new Effect.Highlight('c');
          new Effect.Highlight('k');
          // Turn on successMessage div, then fade it out.
          Element.show('successMessage');
                      (              g );
          setTimeout("Effect.DropOut('successMessage');", 2000);
        }
     • advanced.jsp                           Loads scriptaculous and Prototype.
                                              Defines contextPath variable.
        <head>
        ...
        <jsp:include page="/WEB-INF/includes/header.jsp"/>
        <script src="${contextPath}/scripts/postFunction.js"
             p       ${           }/    p /p             j
                type="text/javascript"></script>
        <title>Advanced AjaxTags Examples</title>
        </head>
22




      JSP Example
     <fieldset>
       <legend>ajax:updateField with p
          g     j    p               postFunction</legend>
                                                  / g
       <form>
         <label for="f">Enter temperature in Fahrenheit:</label>
         <input type="text" id="f"/>
         <input type "button" id "convertButton" value "Convert"/>
                type="button" id="convertButton" value="Convert"/>
         <hr width="500" align="left"/>
         <label for="c">Temperature in Celsius:</label>
         <input type="text" id="c"/>
         <label for="k">Temperature in Kelvin:</label>
         <input type="text" id="k"/><p/>
         <div id="successMessage" style="display:none"
              class= temporaryMessage >
              class="temporaryMessage">
         Calculation complete</div>
       </form>




23
JSP Example (Continued)
       <ajax:updateField
         source= f
         source="f"
         target="c,k"
         baseUrl="${contextPath}/temperature-converter.ajax"
         action= convertButton
         action="convertButton"
         parameters="f={f}"
         parser="new ResponseXmlParser()"
         postFunction showConversionSuccess />
         postFunction="showConversionSuccess"/>
     </fieldset>




24




      Server-Side Code
     • Same TemperatureConverter as in previous
       section
           i
        – Given a temperature in Fahrenheit, returns a list of
          corresponding temperatures in Celsius and Kelvin
        – Use of postFunction does not change how server-side
          resource works




25
Style Sheet Entries
     .temporaryMessage {
       border:2px solid blue;
       background-color:#eeffee;
       color:#009900;
       font-weight:
       font weight: bold;
     }




26




      Results


                                   Immediately after
                                   pressing button.

                                   Two seconds later.




27
© 2009 Marty Hall




                  ajax:tabPanel with
                    errorFunction

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     Basic Idea
     • Approach
       – You list a regular JavaScript function as the value of the
         errorFunction attribute
          • Almost all AjaxTags tags support errorFunction
       – If server-side resource returns an HTTP status code other
         than 200, the errorFunction is triggered
     • Main uses
       – Error messages
       – Default values when server-side resource is unavailable
                             server side




29
Script
     • scripts/errorFunction.js
         function warn() {
           alert("Server error!nn" +
                 "Did you forget to specifyn" +
                 "a default tab?");
                 " d f lt t b?")
         }


     • error.jsp
         <head>
         ...
         <jsp:include page="/WEB-INF/includes/header.jsp"/>
         <script src="${contextPath}/scripts/errorFunction.js"
                 type="text/javascript"></script>
         <title>Advanced AjaxTags Examples</title>
         </head>
30




      JSP Example
     <fieldset>
       <legend>ajax:tabPanel</legend>
       <h2>Largest Cities in Selected Northeast States</h2>
       <div class="tabPanelWrapper">
         <ajax:tabPanel
           panelStyleId="panel"
           contentStyleId="content"
           panelStyleClass="tabPanel"            Should say defaultTab="true".
           contentStyleClass="tabContent"        Without a default tab, tabPanel tries
           currentStyleClass="currentTab"        to load contextPath/null.
           errorFunction="warn">
           <ajax:tab
             caption="Maryland"
             baseUrl="${contextPath}/population-finder.ajax"
             parameters="state=Maryland,city=Baltimore"/>
           <ajax:tab
             caption="Virginia"
             baseUrl="${contextPath}/population-finder.ajax"
             parameters="state=Virginia,city=Virginia Beach"/>
             ...
         </ajax:tabPanel>
31   </div></fieldset>
Server-Side Code
     • Same PopulationFinder as in previous
       section
           i
       – Given a state and a city, returns the population
       – Use of errorFunction does not change how server-side
                                                      server side
         resource works




32




     Results




33
© 2009 Marty Hall




                ajax:htmlContent with
                   Multiple Triggers

                       Customized Java EE Training: http://courses.coreservlets.com/
         Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
          Developed and taught by well-known author and developer. At public venues or onsite at your location.




     Basic Idea
     • Approach
       – In previous section, we used source to designate button
          • Gives the ID of the element that will trigger the action
       – If you use sourceClass instead then any element that
                                  instead,
         has that CSS classname can be a trigger
          • The element must support onclick (push buttons, links,
            radio buttons checkboxes, etc )
                  buttons, checkboxes etc.)
     • Main use
       – Multiple ways of triggering an action




35
JSP Example
     <fieldset>
       <legend>ajax:htmlContent with Multiple Triggers</legend>
       <form>
         <label for="state2">State:</label>
         <select id="state2">
           <option value="">Select State</option>
           <option value="Maryland">Maryland</option>
           ...
           <option value="New York">New York</option>
         </select>
         <label for="city2">City:</label>
         <select id="city2" disabled="disabled">
           <option value="">Select City</option>
         </select>
         <br/><hr align="left" width="500"/>
         <input type="button" value="Show Population" class="trigger"/>
         <a href="javascript://no-op" class="trigger">Show Population</a>
         <input type="radio" class="trigger"/>Show Population
         <br/><hr align="left" width="500"/>
         <span id="population"></span>
       </form>
36




      JSP Example (Continued)
       <ajax:select
         baseUrl="${contextPath}/city-finder.ajax"
                  ${            }/  y         j
         source="state2"
         target="city2"
         parameters="state={state2}"/>
       <ajax:htmlContent
          baseUrl="${contextPath}/population-finder.ajax"
          sourceClass="trigger"
          target="population"
          parameters="state={state2},city={city2}"/>
     </fieldset>




37
Server-Side Code
     • Same PopulationFinder as in previous
       examples
            l
       – Given a state and a city, returns the population
       – Type of trigger does not change how server-side resource
                                                server side
         works




38




     Results




39
Summary
     • indicator attribute
        – Specifies region that displays temporarily while server-side resource
                                                           server side
          runs
     • Returning a list for ajax:autocomplete with names
       different from values
        – Names get shown in the dropdown list
        – Name gets inserted in source textfield
            • I e the textfield that actually had dropdown list
              I.e.,
        – Value gets inserted in target textfield
     • preFunction and postFunctions attributes
        – Arbitrary JavaScript that runs before or after server-side resource
     • errorFunction attribute
        – Function that runs when server has error
     • sourceClass attribute
        – Designates elements that trigger server-side resources
40




                                                                                                    © 2009 Marty Hall




                                    Questions?

                         Customized Java EE Training: http://courses.coreservlets.com/
           Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.
            Developed and taught by well-known author and developer. At public venues or onsite at your location.

Contenu connexe

Tendances (18)

10 jsp-scripting-elements
10 jsp-scripting-elements10 jsp-scripting-elements
10 jsp-scripting-elements
 
Rest and Sling Resolution
Rest and Sling ResolutionRest and Sling Resolution
Rest and Sling Resolution
 
Ruby On Rails Tutorial
Ruby On Rails TutorialRuby On Rails Tutorial
Ruby On Rails Tutorial
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Web Applications and Deployment
Web Applications and DeploymentWeb Applications and Deployment
Web Applications and Deployment
 
14 mvc
14 mvc14 mvc
14 mvc
 
WEB TECHNOLOGIES JSP
WEB TECHNOLOGIES  JSPWEB TECHNOLOGIES  JSP
WEB TECHNOLOGIES JSP
 
JSP
JSPJSP
JSP
 
Introduction to JSP
Introduction to JSPIntroduction to JSP
Introduction to JSP
 
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 server pages
Java server pagesJava server pages
Java server pages
 
J2 Ee Overview
J2 Ee OverviewJ2 Ee Overview
J2 Ee Overview
 
J2EE - Practical Overview
J2EE - Practical OverviewJ2EE - Practical Overview
J2EE - Practical Overview
 
Java 8 Overview
Java 8 OverviewJava 8 Overview
Java 8 Overview
 
Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010Ruby On Rails Seminar Basis Softexpo Feb2010
Ruby On Rails Seminar Basis Softexpo Feb2010
 
J2EE jsp_01
J2EE jsp_01J2EE jsp_01
J2EE jsp_01
 
Sightly - Part 2
Sightly - Part 2Sightly - Part 2
Sightly - Part 2
 

En vedette

123 robotics experiments for the evil genius
123 robotics experiments for the evil genius123 robotics experiments for the evil genius
123 robotics experiments for the evil genius江里久 ちかと
 
Html5 Cheat Sheet
Html5 Cheat SheetHtml5 Cheat Sheet
Html5 Cheat SheetAkramWaseem
 
Package and distribute your Python code
Package and distribute your Python codePackage and distribute your Python code
Package and distribute your Python codeSanket Saurav
 
A Few Interesting Things in Apple's Swift Programming Language
A Few Interesting Things in Apple's Swift Programming LanguageA Few Interesting Things in Apple's Swift Programming Language
A Few Interesting Things in Apple's Swift Programming LanguageSmartLogic
 
DBMS lab manual
DBMS lab manualDBMS lab manual
DBMS lab manualmaha tce
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL fileRACHIT_GUPTA
 
An Introduction to Python Programming
An Introduction to Python ProgrammingAn Introduction to Python Programming
An Introduction to Python ProgrammingMorteza Zakeri
 
12th CBSE Practical File
12th CBSE Practical File12th CBSE Practical File
12th CBSE Practical FileAshwin Francis
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerTOPS Technologies
 

En vedette (20)

123 robotics experiments for the evil genius
123 robotics experiments for the evil genius123 robotics experiments for the evil genius
123 robotics experiments for the evil genius
 
Tutorial Python
Tutorial PythonTutorial Python
Tutorial Python
 
Html5 Cheat Sheet
Html5 Cheat SheetHtml5 Cheat Sheet
Html5 Cheat Sheet
 
Tutorial python2
Tutorial python2Tutorial python2
Tutorial python2
 
Package and distribute your Python code
Package and distribute your Python codePackage and distribute your Python code
Package and distribute your Python code
 
Python 3 Days
Python  3 DaysPython  3 Days
Python 3 Days
 
Python Tutorial
Python TutorialPython Tutorial
Python Tutorial
 
A Few Interesting Things in Apple's Swift Programming Language
A Few Interesting Things in Apple's Swift Programming LanguageA Few Interesting Things in Apple's Swift Programming Language
A Few Interesting Things in Apple's Swift Programming Language
 
DBMS lab manual
DBMS lab manualDBMS lab manual
DBMS lab manual
 
Dbms viva questions
Dbms viva questionsDbms viva questions
Dbms viva questions
 
Java PRACTICAL file
Java PRACTICAL fileJava PRACTICAL file
Java PRACTICAL file
 
An Introduction to Python Programming
An Introduction to Python ProgrammingAn Introduction to Python Programming
An Introduction to Python Programming
 
Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
 
Dbms lab questions
Dbms lab questionsDbms lab questions
Dbms lab questions
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
DBMS Practical File
DBMS Practical FileDBMS Practical File
DBMS Practical File
 
12th CBSE Practical File
12th CBSE Practical File12th CBSE Practical File
12th CBSE Practical File
 
Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Most Asked Java Interview Question and Answer
Most Asked Java Interview Question and AnswerMost Asked Java Interview Question and Answer
Most Asked Java Interview Question and Answer
 
Oracle Complete Interview Questions
Oracle Complete Interview QuestionsOracle Complete Interview Questions
Oracle Complete Interview Questions
 

Similaire à Ajax Tags Advanced

Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxtutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
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
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basicssnopteck
 
13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
03 form-data
03 form-data03 form-data
03 form-datasnopteck
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptxtutorialsruby
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setupsnopteck
 
java beans
java beansjava beans
java beanslapa
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Arun Gupta
 

Similaire à Ajax Tags Advanced (20)

Prototype-1
Prototype-1Prototype-1
Prototype-1
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
JavaScript-Core
JavaScript-CoreJavaScript-Core
JavaScript-Core
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
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
 
02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
Json generation
Json generationJson generation
Json generation
 
13 java beans
13 java beans13 java beans
13 java beans
 
03 form-data
03 form-data03 form-data
03 form-data
 
jQuery-3-UI
jQuery-3-UIjQuery-3-UI
jQuery-3-UI
 
JQuery-Tutorial
 JQuery-Tutorial JQuery-Tutorial
JQuery-Tutorial
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-3-UI.pptx
 
jQuery-3-UI
jQuery-3-UIjQuery-3-UI
jQuery-3-UI
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
 
java beans
java beansjava beans
java beans
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
 
Java script core
Java script coreJava script core
Java script core
 

Plus de AkramWaseem

Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
Mseduebookexcitinglearningweb Final 120914022330 Phpapp02Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
Mseduebookexcitinglearningweb Final 120914022330 Phpapp02AkramWaseem
 
Xml Messaging With Soap
Xml Messaging With SoapXml Messaging With Soap
Xml Messaging With SoapAkramWaseem
 
Ascii Table Characters
Ascii Table CharactersAscii Table Characters
Ascii Table CharactersAkramWaseem
 
Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1AkramWaseem
 
Scripts Python Dbapi
Scripts Python DbapiScripts Python Dbapi
Scripts Python DbapiAkramWaseem
 
Random And Dynamic Images Using Python Cgi
Random And Dynamic Images Using Python CgiRandom And Dynamic Images Using Python Cgi
Random And Dynamic Images Using Python CgiAkramWaseem
 
Python And My Sq Ldb Module
Python And My Sq Ldb ModulePython And My Sq Ldb Module
Python And My Sq Ldb ModuleAkramWaseem
 
Internet Programming With Python Presentation
Internet Programming With Python PresentationInternet Programming With Python Presentation
Internet Programming With Python PresentationAkramWaseem
 
Docs Python Org Howto Webservers Html
Docs Python Org Howto Webservers HtmlDocs Python Org Howto Webservers Html
Docs Python Org Howto Webservers HtmlAkramWaseem
 

Plus de AkramWaseem (17)

Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
Mseduebookexcitinglearningweb Final 120914022330 Phpapp02Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
Mseduebookexcitinglearningweb Final 120914022330 Phpapp02
 
Xml Messaging With Soap
Xml Messaging With SoapXml Messaging With Soap
Xml Messaging With Soap
 
Xhtml Basics
Xhtml BasicsXhtml Basics
Xhtml Basics
 
Uml Tutorial
Uml TutorialUml Tutorial
Uml Tutorial
 
Xhtml Basics
Xhtml BasicsXhtml Basics
Xhtml Basics
 
Ascii Table Characters
Ascii Table CharactersAscii Table Characters
Ascii Table Characters
 
Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1Www Kitebird Com Articles Pydbapi Html Toc 1
Www Kitebird Com Articles Pydbapi Html Toc 1
 
Scripts Python Dbapi
Scripts Python DbapiScripts Python Dbapi
Scripts Python Dbapi
 
Random And Dynamic Images Using Python Cgi
Random And Dynamic Images Using Python CgiRandom And Dynamic Images Using Python Cgi
Random And Dynamic Images Using Python Cgi
 
Python And My Sq Ldb Module
Python And My Sq Ldb ModulePython And My Sq Ldb Module
Python And My Sq Ldb Module
 
Pydbapi
PydbapiPydbapi
Pydbapi
 
My Sq Ldb Tut
My Sq Ldb TutMy Sq Ldb Tut
My Sq Ldb Tut
 
Internet Programming With Python Presentation
Internet Programming With Python PresentationInternet Programming With Python Presentation
Internet Programming With Python Presentation
 
Cgi
CgiCgi
Cgi
 
Docs Python Org Howto Webservers Html
Docs Python Org Howto Webservers HtmlDocs Python Org Howto Webservers Html
Docs Python Org Howto Webservers Html
 
Handson Python
Handson PythonHandson Python
Handson Python
 
Tutor Py
Tutor PyTutor Py
Tutor Py
 

Ajax Tags Advanced

  • 1. © 2009 Marty Hall The AjaxTags Library: Advanced Features 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, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. © 2009 Marty Hall For live Ajax & GWT training, see training courses at http://courses.coreservlets.com/. t htt // l t / Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial. Available at public JSP, tutorial venues, or customized versions can be held on-site at your organization. •C Courses d developed and t l d d taught b M t H ll ht by Marty Hall – Java 6, intermediate/beginning servlets/JSP, advanced servlets/JSP, Struts, JSF 1.x & 2.0, Ajax, GWT, custom mix of topics – Ajax courses can concentrate on EElibrary (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo) or survey several Customized Java one Training: http://courses.coreservlets.com/ • Courses developed and taught by coreservlets.com experts (edited by Marty) Servlets, – Spring, Hibernate/JPA, 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. JSP, JSF 1.x & JSF 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
  • 2. Topics in This Section • Regions that display temporarily while server-side resource runs id • Autocomplete textboxes with associated values displayed in other textboxes • Prefunctions and postfunctions – Arbitrary JavaScript that runs before or after server-side server side resource • Functions that run when server has error • Multiple triggers for server-side resources 4 © 2009 Marty Hall Setup/Review Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 3. Installation • Several required JAR files – In Eclipse: WebContent/WEB-INF/lib – In deployed app: WEB-INF/lib – Download from http://ajaxtags sourceforge net/ http://ajaxtags.sourceforge.net/ • Prototype and Scriptaculous JS files – In Eclipse: WebContent/scripts – In deployed app: scripts – Download from http://script.aculo.us/ • Simple installation – Download prebuilt starting-point project: ajaxtags-blank.zip j t bl k i • Download from 6 http://courses.coreservlets.com/Course-Materials/ajax.html Basic Setup: advanced.jsp (Covered in Previous Lecture) <!DOCTYPE ...> <%@ taglib uri="http://ajaxtags org/tags/ajax" uri http://ajaxtags.org/tags/ajax prefix="ajax" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"" /> <jsp:include page="/WEB-INF/includes/header.jsp"/> ... <title>Advanced AjaxTags Examples</title> </head> <body> <b d > ... </body></html> 7
  • 4. Basic Setup: header.jsp (Covered in Previous Lecture) <% request.setAttribute("contextPath", request.getContextPath()); request getContextPath()); %> <script src="${contextPath}/scripts/prototype-1.4.0.js" type="text/javascript"></script> <script src="${contextPath}/scripts/scriptaculous.js" p { } p p j type="text/javascript"></script> <script src="${contextPath}/scripts/overlibmws.js" type="text/javascript"></script> <script src="${contextPath}/scripts/ajaxtags-1.2-beta2.js" type="text/javascript"></script> <link rel="stylesheet" href="${contextPath}/css/styles.css" h f "${ t tP th}/ / t l " type="text/css"/> 8 © 2009 Marty Hall ajax:autocomplete with indicator Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.
  • 5. Basic Idea • Approach – indicator attribute designates section (usually div or span) that will be enabled while results are being loaded • It is disabled to start with and disabled again when results with, come back • Often contains animated GIF showing progress • Main use – Gives user feedback when server-side resource takes a long time g • Note – You can reproduce indicator region in other places by using Effect.Show from Scriptaculous • See later lectures on Scriptaculous 10 JSP Example <fieldset> <legend>ajax:autocomplete with indicator</legend> g j p / g <form> <label for="language">Programming language:</label> <input type="text" name="language" id="language"/> <span id "indicatorRegion" style "display:none;"> id="indicatorRegion" style="display:none;"> <img src="${contextPath}/images/busy-indicator.gif"/> Loading... </span> </form> <ajax:autocomplete source="language" target= language target="language" baseUrl="${contextPath}/slow-language-completer.ajax" className="autocomplete" minimumCharacters="1" indicator="indicatorRegion"/> </fieldset> 11
  • 6. Server-Side Code public class SlowLanguageCompleter LanguageCompleter shown in previous extends LanguageCompleter { section @Override public String getXmlContent(HttpServletRequest request, HttpServletResponse response) throws Exception { try { Thread.sleep(5000); } catch(Exception e) {} y p( ) ( p ) return(super.getXmlContent(request, response)); } } 12 Results 13
  • 7. © 2009 Marty Hall ajax:autocomplete with Linked Fields Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Basic Idea • Approach –S Server-side resource returns a list with names that are id li ih h different from values • xmlBuilder.addItem("name1", "value1"); • I last section, names and values were th same In l t ti d l the – When name selected from dropdown, that name (value) put into the textfield that has the dropdown – Names shown in dropdown box under main textfield – When a value is selected from dropdown, secondary value placed into a different textfield • M i uses Main – When you have auxiliary information to display to user • E.g., show description when catalog ID selected g, p g – When you have associated values • E.g., word in another language 15
  • 8. JSP Example <fieldset> <legend>ajax:autocomplete with linked fields</legend> <form> <label for="englishAnimal">English animal:</label> <input type="text" id="englishAnimal"/> type text id englishAnimal /> <label for="spanishAnimal">Spanish animal:</label> <input type="text" id="spanishAnimal"/> </form> / <ajax:autocomplete source="englishAnimal" target="spanishAnimal" baseUrl="${contextPath}/animal-completer.ajax" parameters="englishAnimal={englishAnimal}" className="autocomplete" minimumCharacters="1"/> </fieldset> 16 Server-Side Code import javax.servlet.http.*; import org ajaxtags helpers *; org.ajaxtags.helpers. ; import org.ajaxtags.servlets.*; p public class AnimalCompleter extends BaseAjaxServlet { p j @Override public String getXmlContent(HttpServletRequest request, HttpServletResponse response) throws Exception { String animalPrefix = request.getParameter("englishAnimal"); String animalList = makeAnimalList(animalPrefix); St i i lLi t k A i lLi t( i lP fi ) return(animalList); } 17
  • 9. Server-Side Code (Continued) private static final String[][] animals = { {"aardvark", "aardvark"},{"alligator", "cocodrilo"}, { aardvark , aardvark },{ alligator , cocodrilo }, {"antelope", "antílopo"}, {"baboon", "babuino"}, {"bat", "murciélago"}, {"bear", "oso"}, {"cat", "gato"}, {"camel", "camello"}, {"conch", "concha"} }; private String makeAnimalList(String animalPrefix) { animalPrefix = animalPrefix.toUpperCase(); AjaxXmlBuilder builder = new AjaxXmlBuilder(); for(String[] animalPair: animals) { String englishAnimal = animalPair[0]; String spanishAnimal = animalPair[1]; if(englishAnimal.toUpperCase().startsWith(animalPrefix)) { builder.addItem(englishAnimal, spanishAnimal); } } return(builder.toString()); } 18 } Results 19
  • 10. © 2009 Marty Hall ajax:updateField with p postFunction Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Basic Idea • Approach – Y li a regular JavaScript function as the value of the You list l J S i f i h l f h postFunction or preFunction attribute • Almost all tags support postFunction and preFunction – The postFunction fires after the server-side resource is finished – The preFunction fires just before the server-side resource p j is called • Main uses – preFunction • To make an “I am working” message or image • Form field validation – postFunction • To highlight results or show a success message 21
  • 11. Script • scripts/postFunction.js – N that i i using scriptaculous calls Note h it is i i l ll function showConversionSuccess() { // Temporarily highlight Celsius and Kelvin fields p y g g new Effect.Highlight('c'); new Effect.Highlight('k'); // Turn on successMessage div, then fade it out. Element.show('successMessage'); ( g ); setTimeout("Effect.DropOut('successMessage');", 2000); } • advanced.jsp Loads scriptaculous and Prototype. Defines contextPath variable. <head> ... <jsp:include page="/WEB-INF/includes/header.jsp"/> <script src="${contextPath}/scripts/postFunction.js" p ${ }/ p /p j type="text/javascript"></script> <title>Advanced AjaxTags Examples</title> </head> 22 JSP Example <fieldset> <legend>ajax:updateField with p g j p postFunction</legend> / g <form> <label for="f">Enter temperature in Fahrenheit:</label> <input type="text" id="f"/> <input type "button" id "convertButton" value "Convert"/> type="button" id="convertButton" value="Convert"/> <hr width="500" align="left"/> <label for="c">Temperature in Celsius:</label> <input type="text" id="c"/> <label for="k">Temperature in Kelvin:</label> <input type="text" id="k"/><p/> <div id="successMessage" style="display:none" class= temporaryMessage > class="temporaryMessage"> Calculation complete</div> </form> 23
  • 12. JSP Example (Continued) <ajax:updateField source= f source="f" target="c,k" baseUrl="${contextPath}/temperature-converter.ajax" action= convertButton action="convertButton" parameters="f={f}" parser="new ResponseXmlParser()" postFunction showConversionSuccess /> postFunction="showConversionSuccess"/> </fieldset> 24 Server-Side Code • Same TemperatureConverter as in previous section i – Given a temperature in Fahrenheit, returns a list of corresponding temperatures in Celsius and Kelvin – Use of postFunction does not change how server-side resource works 25
  • 13. Style Sheet Entries .temporaryMessage { border:2px solid blue; background-color:#eeffee; color:#009900; font-weight: font weight: bold; } 26 Results Immediately after pressing button. Two seconds later. 27
  • 14. © 2009 Marty Hall ajax:tabPanel with errorFunction Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Basic Idea • Approach – You list a regular JavaScript function as the value of the errorFunction attribute • Almost all AjaxTags tags support errorFunction – If server-side resource returns an HTTP status code other than 200, the errorFunction is triggered • Main uses – Error messages – Default values when server-side resource is unavailable server side 29
  • 15. Script • scripts/errorFunction.js function warn() { alert("Server error!nn" + "Did you forget to specifyn" + "a default tab?"); " d f lt t b?") } • error.jsp <head> ... <jsp:include page="/WEB-INF/includes/header.jsp"/> <script src="${contextPath}/scripts/errorFunction.js" type="text/javascript"></script> <title>Advanced AjaxTags Examples</title> </head> 30 JSP Example <fieldset> <legend>ajax:tabPanel</legend> <h2>Largest Cities in Selected Northeast States</h2> <div class="tabPanelWrapper"> <ajax:tabPanel panelStyleId="panel" contentStyleId="content" panelStyleClass="tabPanel" Should say defaultTab="true". contentStyleClass="tabContent" Without a default tab, tabPanel tries currentStyleClass="currentTab" to load contextPath/null. errorFunction="warn"> <ajax:tab caption="Maryland" baseUrl="${contextPath}/population-finder.ajax" parameters="state=Maryland,city=Baltimore"/> <ajax:tab caption="Virginia" baseUrl="${contextPath}/population-finder.ajax" parameters="state=Virginia,city=Virginia Beach"/> ... </ajax:tabPanel> 31 </div></fieldset>
  • 16. Server-Side Code • Same PopulationFinder as in previous section i – Given a state and a city, returns the population – Use of errorFunction does not change how server-side server side resource works 32 Results 33
  • 17. © 2009 Marty Hall ajax:htmlContent with Multiple Triggers Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Basic Idea • Approach – In previous section, we used source to designate button • Gives the ID of the element that will trigger the action – If you use sourceClass instead then any element that instead, has that CSS classname can be a trigger • The element must support onclick (push buttons, links, radio buttons checkboxes, etc ) buttons, checkboxes etc.) • Main use – Multiple ways of triggering an action 35
  • 18. JSP Example <fieldset> <legend>ajax:htmlContent with Multiple Triggers</legend> <form> <label for="state2">State:</label> <select id="state2"> <option value="">Select State</option> <option value="Maryland">Maryland</option> ... <option value="New York">New York</option> </select> <label for="city2">City:</label> <select id="city2" disabled="disabled"> <option value="">Select City</option> </select> <br/><hr align="left" width="500"/> <input type="button" value="Show Population" class="trigger"/> <a href="javascript://no-op" class="trigger">Show Population</a> <input type="radio" class="trigger"/>Show Population <br/><hr align="left" width="500"/> <span id="population"></span> </form> 36 JSP Example (Continued) <ajax:select baseUrl="${contextPath}/city-finder.ajax" ${ }/ y j source="state2" target="city2" parameters="state={state2}"/> <ajax:htmlContent baseUrl="${contextPath}/population-finder.ajax" sourceClass="trigger" target="population" parameters="state={state2},city={city2}"/> </fieldset> 37
  • 19. Server-Side Code • Same PopulationFinder as in previous examples l – Given a state and a city, returns the population – Type of trigger does not change how server-side resource server side works 38 Results 39
  • 20. Summary • indicator attribute – Specifies region that displays temporarily while server-side resource server side runs • Returning a list for ajax:autocomplete with names different from values – Names get shown in the dropdown list – Name gets inserted in source textfield • I e the textfield that actually had dropdown list I.e., – Value gets inserted in target textfield • preFunction and postFunctions attributes – Arbitrary JavaScript that runs before or after server-side resource • errorFunction attribute – Function that runs when server has error • sourceClass attribute – Designates elements that trigger server-side resources 40 © 2009 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 1.x & JSF 2.0, Struts Classic & Struts 2, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.