the script.aculo.us javascript library part i: ajax-specific

29
© 2009 Marty Hall The Script.aculo.us JavaScript Library Part I: Ajax-Specific 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 t htt // lt / 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 Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. C d l d dt ht b M t H ll 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. Courses developed and taught 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 one library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo) or survey several Courses developed and taught by coreservlets.com experts (edited by Marty) Spring, Hibernate/JPA, EJB3, Ruby/Rails Contact [email protected] for details

Upload: sampetruda

Post on 15-May-2015

954 views

Category:

Documents


5 download

TRANSCRIPT

Page 1: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

© 2009 Marty Hall

The Script.aculo.us JavaScript Library Part I:

Ajax-Specific Featuresj pOriginals 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.

p j

© 2009 Marty Hall

For live Ajax & GWT training, see training t htt // l t /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 Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at

your organization.C d l d d t ht b M t H ll

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.

• Courses developed and taught 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 one library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo) or survey several

• Courses developed and taught by coreservlets.com experts (edited by Marty)– Spring, Hibernate/JPA, EJB3, Ruby/Rails

Contact [email protected] for details

Page 2: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Topics in This Section

• Overview of Scriptaculous• Installation and documentation• Autocomplete textfields

– Local version– Ajax version

• In place Editor• In-place Editor– Free-text values– Values from combo boxValues from combo box

5

© 2009 Marty Hall

Introduction

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.

Page 3: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Overview

• FoundationB il f P– Built on top of Prototype

• Ajax-specific features– Autocompleting textfieldsAutocompleting textfields

• Textfields with dropdown list of matching choices• Covered in first half of this section

– In-place editorsIn-place editors• Clickable text that you can edit and send to server• Covered in second half of this section

• General features• General features– Visual effects (fade in, fade out, highlighting)

• Covered in next section– Drag and drop

• Covered in later section7

Downloading and Installation

• Download– http://script.aculo.us/downloads

• Unzip and grab .js files out of “src” folder– Usually put in subdirectory of scripts since there are many filesUsually put in subdirectory of scripts since there are many files

• This tutorial corresponds to Scriptaculous 1.8.1

• Online documentation– http://wiki.script.aculo.us/

• Online forumhtt // l / / b il i ff– http://groups.google.com/group/rubyonrails-spinoffs

• PrerequisiteScriptaculous requires Prototype I am using 1 6– Scriptaculous requires Prototype. I am using 1.6.

• So your HTML page needs to load both libraries• See separate lectures on Prototype

8

Page 4: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

© 2009 Marty Hall

Autocompleter.Local

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.

Autocompleter.Local

• Idea– Specify JavaScript array that has choices for textfield DropdownSpecify JavaScript array that has choices for textfield. Dropdown

box shown with choices that start with what has been typed so far• http://wiki.script.aculo.us/scriptaculous/show/Autocompletion

• Steps– Make an instance of Autocompleter.Local

• new Autocompleter.Local(textFieldID, divID, array)– Enable it when page loads

• window onload = function() { new Autocompleter Local( ); };• window.onload = function() { new Autocompleter.Local(...); };• Prototype gurus might use document.observe("dom:loaded",

...) instead of window.onload– Make an empty div with a designated CSS name

<di id "di ID" l " CSSN "></di >• <div id="divID" class="someCSSName"></div>– Attach style sheet that makes div absolutely positioned, puts border

on div, turns off bullets for ul lists, and makes a different background color for li.selected

10

Page 5: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Autocompleter.Local Example: JavaScriptJavaScript

var langString = "Java,C,C++,PHP,Visual Basic,...";var langArray = languageString split(" ");var langArray = languageString.split( , );

window.onload = function() {new Autocompleter Local("langField1", "langMenu1",new Autocompleter.Local( langField1 , langMenu1 ,

langArray);};

function googleSearch(id) {var language = getValue(id);window.location.href ="http://www.google.com/search?q=" + language;

}

function getValue(id) {return(escape(document.getElementById(id).value));

}11

Autocompleter.Local Example: HTML HeaderHTML Header

<!DOCTYPE ...><html xmlns="http://www.w3.org/1999/xhtml">p // g/ /<head><title>Scriptaculous and Autocomplete</title><link rel="stylesheet"

href="./css/styles.css"/ /type="text/css"/>

<script src="./scripts/prototype.js"type="text/javascript"></script>

<script src=sc pt s c"./scripts/scriptaculous/scriptaculous.js?load=effects,controls"

type="text/javascript"></script><script src="./scripts/autocomplete.js"

/ /type="text/javascript"></script></head>

If you know you will only use certain parts of scriptaculous library you can save

12

If you know you will only use certain parts of scriptaculous library, you can save download time by loading only some of it. To load all of it, just omit the "load=" part. I.e., <script src=".../scriptaculous.js"...></script>. Autocomplete is in controls, but relies on effects internally.

Page 6: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Autocompleter.Local Example: Main HTMLMain HTML

<body>...<fieldset><legend>Autocomplete.Local</legend><form action="#"><label for="langField1">Programming language:</label><input type="text" id="langField1"/><input type="button" value="Search on Language"

onclick="googleSearch('langField1')"/><br/><div id="langMenu1" class="autocomplete"></div>

</form></fi ld t></fieldset>...</body></html>

13

Autocompleter.Local Example: CSS

.autocomplete {position: absolute;position: absolute;color: #333333;background-color: #ffffff;border: 1px solid #666666;border: 1px solid #666666;font-family: Arial, sans-serif;overflow: hidden;

}}.autocomplete ul {

padding: 0;margin: 0;a g : 0;list-style: none;overflow: auto;

}}

14

Page 7: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Autocompleter.Local Example: CSS (Continued)(Continued)

.autocomplete li {display: block;display: block;white-space: nowrap;cursor: pointer;margin: 0px;margin: 0px;padding-left: 5px;padding-right: 5px;border: 0px solid #ffffff;border: 0px solid #ffffff;

}.autocomplete li.selected {

background-color: #cceeff;bac g ou d co o : #ccee ;border-top: 1px solid #99bbcc;border-bottom: 1px solid #99bbcc;

}}

15

Autocompleter.Local Example: ResultsResults

16

Page 8: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

© 2009 Marty Hall

Ajax.Autocompleter

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.

Ajax.Autocompleter

• Idea– Specify URL that computes list of choices Dropdown box shownSpecify URL that computes list of choices. Dropdown box shown

with choices that start with what has been typed so far• http://wiki.script.aculo.us/scriptaculous/show/Autocompletion

• Steps: summary– Same steps as with Autocompleter.Local except

• Specify url instead of array (url should return <ul> list)• Use class Ajax.Autocompleter instead of

Autocompleter.LocalAutocompleter.Local• Steps

– Make an instance of Ajax.Autocompleter• new Ajax.Autocompleter(textFieldID, divID, url)j p ( )

– Enable it when page loads• window.onload = function() { new Ajax.Autocompleter(...);

};– Make an empty div with a designated CSS name– Make an empty div with a designated CSS name

• <div id="divID" class="someCSSName"></div>– Attach same style sheet as with Autocompleter.Local

18

Page 9: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Ajax.Autocompleter Example: JavaScriptJavaScript

var langString = "Java,C,C++,PHP,Visual Basic,...";var langArray = languageString split(" ");var langArray = languageString.split( , );

window.onload = function() {new Autocompleter Local("langField1" "langMenu1"new Autocompleter.Local("langField1", "langMenu1",

langArray);new Ajax.Autocompleter("langField2", "langMenu2",

"l ")"languages");};

This is the relative URL By default it will be passed POST

19

This is the relative URL. By default it will be passed POST data of name-of-langField2=value-of-langField2

Ajax.Autocompleter Example: HTMLHTML

<fieldset><legend>Ajax Autocomplete</legend><legend>Ajax.Autocomplete</legend><form action="#"><label for="langField2">Programming language:</label><input type="text" id="langField2" name="langPrefix"/>p yp g g<input type="button" value="Search on Language"

onclick="googleSearch('langField2')"/><br/><div id="langMenu2" class="autocomplete"></div>

</form></fieldset>

By default name of field is

20

By default, name of field is parameter name

Page 10: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Ajax.Autocompleter Example: ServletServlet

public class LanguageCompleter extends HttpServlet {private static final String languageString = "Java,C,C++,...";

private static final String[] languageArray = languageString.split(",");

public void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException {response.setHeader("Cache-Control", "no-cache");response.setHeader("Pragma", "no-cache");String languagePrefix = request.getParameter("langPrefix");

List<String> languages = findLanguages(languagePrefix);

The name (not id!) of textfieldwas "langPrefix".

g g g g g g grequest.setAttribute("languages", languages);String outputPage = "/WEB-INF/results/language-list.jsp";

RequestDispatcher dispatcher =q p prequest.getRequestDispatcher(outputPage);

dispatcher.include(request, response);}

21

Ajax.Autocompleter Example: Servlet (Continued)Servlet (Continued)public void doPost(HttpServletRequest request,

HttpServletResponse response)HttpServletResponse response)throws ServletException, IOException {

doGet(request, response);}

private List<String> findLanguages(String languagePrefix) {languagePrefix = languagePrefix.toUpperCase();List<String> languages = new ArrayList<String>();List<String> languages = new ArrayList<String>();for(String language: languageArray) {if(language.toUpperCase().startsWith(languagePrefix)) {languages.add(language);

}}return(languages);

}}}

22

Page 11: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Ajax.Autocompleter Example: JSP

<%@ taglib uri="http://java.sun.com/jsp/jstl/core"prefix="c" %>prefix= c %>

<ul><c:forEach var="language" items="${languages}">

<li>${language}</li><li>${language}</li></c:forEach></ul>

Return value of URL should be <ul>

<li>...</li>

23

...<li>...</li>

</ul>Style sheet on client will suppress the bullets.

Ajax.Autocompleter Example: web xmlweb.xml<servlet>

<servlet-name>LanguageCompleter</servlet-name><servlet name>LanguageCompleter</servlet name><servlet-class>

coreservlets.LanguageCompleter</servlet-class></servlet class>

</servlet><servlet-mapping>

<servlet-name>LanguageCompleter</servlet-name><servlet name>LanguageCompleter</servlet name><url-pattern>/languages</url-pattern>

</servlet-mapping>

24

Page 12: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Ajax.Autocompleter Example: ResultsResults

25

© 2009 Marty Hall

Autocompleter Options

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.

Page 13: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Autocompleter Options

• Idea– Autocompleter.Local and Ajax.Autocompleter accept an

options array as the fourth argument• new Ajax Autocompleter(fieldID divID urlnew Ajax.Autocompleter(fieldID, divID, url,

{ opt1: ..., opt2: ..., ... });

• Legal properties for both classes– autoSelect (default: false)

• Should value automatically be inserted into textfield if there is only one matching choice?y g

– frequency (default: 0.4)• Interval in seconds between attempts to autocomplete

i Ch (d f lt 1)– minChars (default: 1)• The number of characters before autocompletion kicks in

27

Autocompleter Options (Continued)

• Options for Autocompleter.Localh i (d f l 10)– choices (default 10)• Maximum number of entries to display

– partialSearch (default true)• Should match be made at beginning of any word?

False means to match beginning of first word only.– partialChars (default 2)

• Number of characters before partial search kicks in. When number of chars is greater or equal to minChars but less than partialChars, you get a non-partial search (first word).

f llSearch (defa lt false)– fullSearch (default false)• Should match be anywhere? False means to match only at

the beginning of each candidate.selector (default: function that searches array)– selector (default: function that searches array)

• Function that does real work of doing match and building ul list.

28

Page 14: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Autocompleter Options (Continued)

• Options for Ajax.Autocompleteri di (d f l )– indicator (default: none)

• Id of element that should be shown while waiting for server result, then hidden again

N (d f lt f t tfi ld)– paramName (default: name of textfield)• parameter name sent to server (parameter value is

textfield value, of course)t (d f lt t )– parameters (default: empty)

• Extra string sent to server (fixed parameters)– tokens (default: empty)

• Array of delimeters: each entry outside delimeters is autocompleted separately

– afterUpdateElement (default: none)• Function to run when user makes choice. Lets you

respond automatically to selections.

29

Autocompleter Options Example: JavaScriptJavaScript

var langString = "Java,C,C++,PHP,Visual Basic,...";var langArray = languageString split(" ");var langArray = languageString.split( , );

window.onload = function() {new Autocompleter Local("langField1", "langMenu1",new Autocompleter.Local( langField1 , langMenu1 ,

langArray);new Ajax.Autocompleter("langField2", "langMenu2",

"languages");languages );new Ajax.Autocompleter("langField3", "langMenu3",

"languages-slow", { indicator: "indicatorRegion",{ g ,paramName: "langPrefix"});

};

30

Page 15: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Autocompleter Options Example: HTMLHTML

<fieldset><legend>Ajax Autocomplete with Indicator</legend><legend>Ajax.Autocomplete with Indicator</legend><form action="#"><span id="indicatorRegion" style="display:none;"><img src="images/busy-indicator.gif"/>g g y gLoading...

</span><br/><label for="langField3">Programming language:</label><input type="text" id="langField3" name="bad-name"/><input type="button" value="Search on Language"

onclick="googleSearch('langField3')"/><br/><di id "l M 3" l " t l t "></di ><div id="langMenu3" class="autocomplete"></div>

</form></fieldset>

31

Autocompleter Options Example: JavaJavapublic class SlowLanguageCompleter

extends LanguageCompleter {extends LanguageCompleter {public void doGet(HttpServletRequest request,

HttpServletResponse response)throws ServletException, IOException {

try { Thread.sleep(2000); } catch(InterruptedException ie) {}super.doGet(request, response);

}}}

32

Page 16: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Autocompleter Options Example: web xmlweb.xml<servlet>

<servlet-name>SlowLanguageCompleter</servlet-name><servlet name>SlowLanguageCompleter</servlet name><servlet-class>

coreservlets.SlowLanguageCompleter</servlet-class></servlet class></servlet><servlet-mapping>

<servlet-name>SlowLanguageCompleter</servlet-name><servlet name>SlowLanguageCompleter</servlet name><url-pattern>/languages-slow</url-pattern>

</servlet-mapping>

33

Autocompleter Options Example: ResultsResults

34

Page 17: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

© 2009 Marty Hall

In-Place Editors

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.

In-Place Editors

• IdeaText that you can click on edit and send to server– Text that you can click on, edit, and send to server

– Text is highlighted when mouse over it– Text passed to server as “value” request parameter

• Text shown as “Saving ” while waiting for server• Text shown as Saving... while waiting for server– Value returned from server is new textual value

• Might not be exactly what user entered

• BasicsBasics– new Ajax.InPlaceEditor("id-of-element", "url");

– Click on text to get editable textfield

– new Ajax.InPlaceCollectionEditornew Ajax.InPlaceCollectionEditor("id-of-element", "url"{ collection: ["Option1", ... "OptionN"]});

– Click on text to get select box of options

– Documentation• http://wiki.script.aculo.us/scriptaculous/show/InPlaceEditing

36

Page 18: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

InPlaceEditor Example

• JavaScriptwindow.onload = function() {

new Ajax.InPlaceEditor("element-to-edit", "show-value.jsp");

};

• HTML• HTML<h2 id="element-to-edit">Here is Some Text</h2>

• JSP<% try { Thread.sleep(2000);

} t h(I t t dE ti i ) {}} catch(InterruptedException ie) {} %>You sent "${param.value}"

37

InPlaceEditor Example: Results

38

Page 19: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

InPlaceCollectionEditor Example

• JavaScripti d l d f ti () {window.onload = function() {new Ajax.InPlaceEditor("element-to-edit",

"show-value.jsp");new Ajax.InPlaceCollectionEditornew Ajax.InPlaceCollectionEditor

("flyer-status", "show-value.jsp",{ collection: ["Silver", "Gold", "Platinum",

"Wood", "Hay", "Stubble"]});};

• HTML<h2>Frequent Flyer Status:

<span id="flyer-status">Silver</span></h2>

• JSP<% try { Thread.sleep(2000); y { p( )

} catch(InterruptedException ie) {} %>You sent "${param.value}"

39

InPlaceCollectionEditor Example: ResultsResults

40

Page 20: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

In-Place Editor Options: Basic OptionsBasic Options

• okButton (default: true)– Should you use "ok" button? Often set to false.

• okText (default: "ok")T f fi i b– Text of confirmation button

• cancelLink (default: true)Should you have "cancel" link?– Should you have cancel link?

• savingText (default "Saving...")– Text to show while waiting for server responseText to show while waiting for server response

• clickToEditText (default: "Click to edit")– Text to show in tooltip when mouse hovers over textp

• paramName (default: "value")– Request parameter name

41

In-Place Editor Options: Ajax Request OptionsAjax.Request Options

• Idea– You can use ajaxOptions to specify an options object that

gets passed to the underlying Ajax.Request object• new Ajax InPlaceEditor("id" "url" { ajaxOptions: { blah });new Ajax.InPlaceEditor( id , url , { ajaxOptions: { blah });• For {blah} above, you can use all of the same options as

discussed in the earlier section on the Prototype Ajax librarieslibraries

• Most important usage: extra parameters– You are editing a first name, but what customer id does

that first name go with?• var params = { param1: $("div-id").innerHTML,

param2: $F("textfield-id")};p ( )}• var options = { parameters: params }• new Ajax.InPlaceEditor("id", "url", { ajaxOptions: options });

42

Page 21: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

In-Place Editor Options: Collection OptionsCollection Options

• collection– Array of choices

• loadCollectionURLURL h J S i f h i– URL that returns JavaScript array of choices

• loadCollectionTextText to show while waiting for server to send array of– Text to show while waiting for server to send array of choices

43

In-Place Editor Options: Styling OptionsStyling Options

• highlightColor (default: pale yellow)– Color to show when mouse is over and when result first

comes back from server

• highlightendColor (default: white)• highlightendColor (default: white)– Color to show temporarily when hightlighting finishes

• hoverClassName, formClassName,hoverClassName, formClassName, loadingClassName, savingClassName

• (defaults: none, "inplaceeditor-form", "inplaceeditor-l di " "i l dit i ")loading", "inplaceeditor-saving")

– CSS name of elements at different stages

• formIDformID– id of form that is created when you click

44

Page 22: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

In-Place Editor Options: Callback OptionsCallback Options

• onEnterHover– Defaults to setting background color

• onLeaveHoverD f l f di b k d l– Defaults to fading out background color

• onEnterEditMode• onFailure• onFailure

– Defaults to showing error message

• onComplete• onComplete– This is often used when you are doing server-side

validation of values. You can check a custom header from the server and show error message if needed.

• onLeaveEditMode45

Advanced Example: JavaScript

window.onload = function() {var options = {var options {

okButton: false, clickToEditText: "Click to update your info"

};new Ajax.InPlaceEditor("firstName",

"update-firstName",options);

new Ajax InPlaceEditor("lastName"new Ajax.InPlaceEditor( lastName , "update-lastName",options);

new Ajax.InPlaceEditor("email", j ( ,"update-email",options);

new Ajax.InPlaceEditor("flyerNum", " d t fl N ""update-flyerNum",options);

};46

Page 23: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Advanced Example: Servlet for Initial PageServlet for Initial Page

public class ShowTraveler extends HttpServlet {public void doGet(HttpServletRequest request,p p q q

HttpServletResponse response)throws ServletException, IOException {

response.setHeader("Cache-Control", "no-cache");response.setHeader("Pragma", "no-cache");response.setHeader( Pragma , no cache );HttpSession session = request.getSession();Traveler traveler = (Traveler)session.getAttribute("traveler");

if (traveler == null) {if (traveler == null) {traveler = new Traveler();session.setAttribute("traveler", traveler);

} String outputPage = "/WEB-INF/results/show-traveler.jsp";

RequestDispatcher dispatcher =request.getRequestDispatcher(outputPage);

dispatcher.include(request, response);}

}47

Advanced Example: JSP for Initial PageJSP for Initial Page

...<ul style="font-size: 18px"><ul style font size: 18px ><li>First name: <span id="firstName">${traveler.firstName}</span>

</li><li>Last name: <span id="lastName">${traveler.lastName}</span>

</li><li>Email address:<li>Email address: <span id="email">${traveler.email}</span>

</li><li>Frequent Flyer Number: <span id="flyerNum">${traveler.flyerNum}</span>

</li></ul>...

48

Page 24: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Advanced Example: Helper Class for Initial PageHelper Class for Initial Page

public class Traveler implements Serializable {private String firstName = "Joe";p g ;private String lastName = "Traveler";private String email = "[email protected]";private String flyerNum = "a1234";

public Traveler(String firstName, String lastName,String email, String flyerNum) {

setFirstName(firstName);setLastName(lastName);setEmail(email);setFlyerNum(flyerNum);

}}

public Traveler () {}

// Standard getters and setters}

49

Advanced Example: Initial Page: ResultsInitial Page: Results

50

Page 25: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Advanced Example: Servlets for UpdatingServlets for Updating

• Purpose– These are the servlets specified earlier in the

Ajax.InPlaceEditor constructors• update-firstName update-lastName update-emailupdate firstName, update lastName, update email,

update-flyerNum

• Behavior– They look up the session, get a Traveler object from the

session, then store first name, last name, etc. in that object– They also have a delay to simulate use on a loadedThey also have a delay to simulate use on a loaded

network• This lets you see "Saving..." message while waiting for

server updateserver update

51

Advanced Example: Servlets for Updating (Parent)Servlets for Updating (Parent)

public abstract class UpdateTraveler extends HttpServlet {public void doPost(HttpServletRequest request,public void doPost(HttpServletRequest request,

HttpServletResponse response)throws ServletException, IOException {

response.setHeader("Cache-Control", "no-cache");p ( , )response.setHeader("Pragma", "no-cache");HttpSession session = request.getSession();Traveler traveler = (Traveler)session.getAttribute("traveler");

if (traveler == null) {traveler = new Traveler();

i tAtt ib t ("t l " t l )session.setAttribute("traveler", traveler);}

52

Page 26: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Advanced Example: Servlets for Updating (Parent Cont )Servlets for Updating (Parent, Cont.)

String newVal = request.getParameter("value");if ((newVal != null) && !(newVal trim() equals(""))) {if ((newVal ! null) && !(newVal.trim().equals( ))) {doUpdate(traveler, newVal);

}PrintWriter out = response.getWriter();p g ()try { Thread.sleep(2000); } catch(InterruptedException ie) {}out.print(getResult(traveler));

}

public abstract void doUpdate(Traveler traveler,St i V l)String newVal);

public abstract String getResult(Traveler traveler);}

53

Advanced Example: Servlets for Updating (First Name)Servlets for Updating (First Name)

public class UpdateFirstName extends UpdateTraveler {public void doUpdate(Traveler traveler,public void doUpdate(Traveler traveler,

String newVal) {traveler.setFirstName(newVal);

}}

public String getResult(Traveler traveler) {return(traveler.getFirstName());

}}

54

Page 27: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Advanced Example: Results

55

© 2009 Marty Hall

Wrap-up

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.

Page 28: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Recommended Books

• Prototype and script.aculo.us: You Never K J S i C ld D Thi !Knew JavaScript Could Do This!– By Christophe Porteneuve

Prototype and Scriptaculous in Action• Prototype and Scriptaculous in Action– By Dave Crane, Bear Bebeault, Tom Locke

57

Summary

window.onload = function() {new Autocompleter Local("fieldID1"new Autocompleter.Local( fieldID1 ,

"divID1", arrayOfChoices);

new Ajax Autocompleter("fieldID2"new Ajax.Autocompleter( fieldID2 ,"divID2", "urlThatReturnsList");

new Ajax Autocompleter("fieldID3"new Ajax.Autocompleter("fieldID3","divID3", "urlThatReturnsList" { indicator "ind id"{ indicator: "ind-id",paramName: "p-name",more-options...});

}};

58

Page 29: The Script.aculo.us JavaScript Library Part I: Ajax-Specific

Summary (Continued)

window.onload = function() {new Ajax.InPlaceEditor("id-to-edit-1",

"url-to-send-value");new Ajax.InPlaceCollectionEditornew Ajax.InPlaceCollectionEditor("id-to-edit-2", "url-to-send-value",{ collection: ["Option1",...,"OptionN"]});

};

59

© 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.