prototype-1

29
© 2009 Marty Hall The Prototype Framework Part I: Ajax Support (Prototype 1.6 Version) 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 1 library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, Google Closure) 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: tutorialsruby

Post on 15-May-2015

1.135 views

Category:

Technology


3 download

TRANSCRIPT

Page 1: Prototype-1

© 2009 Marty Hall

The Prototype FrameworkypPart I: Ajax Support

(Prototype 1.6 Version)( yp )

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.

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 1 library (jQuery, Prototype/Scriptaculous, Ext-JS, Dojo, Google Closure) 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: Prototype-1

Topics in This Section

• Overview of Prototype• Installation and documentation• Ajax.Request

– Basics– Options

• HTML lookup and insertion• HTML lookup and insertion• Ajax.Updater• Ajax PeriodicalUpdater• Ajax.PeriodicalUpdater• Handling JSON Data• Comparing Ajax support to other libraries• Comparing Ajax support to other libraries

– jQuery, Dojo, Ext-JS5

© 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: Prototype-1

Overview of Prototype

• Ajax utilities– Ajax.Request, Ajax.Updater, Ajax.PeriodicalUpdater– Wraps response in Ajax.Response

• Several new properties but especially responseJSON• Several new properties, but especially responseJSON

• General DOM utilities– $() to find element$()– $F() to get form value– element.update() to put into innerHTML– Many helpers in Element class

• General utilitesE t i f Cl F ti A St i– Extensions for Class, Function, Array, String

7

Ajax Utilities

• Ajax.RequestT k URL d i bj ( S d– Takes URL and options object (onSuccess and parameters properties).

– Calls URL, passes result (Ajax.Response) to onSuccess• Ajax.Updater

– Takes id of result region and URL. Invokes URL once and puts responseText in result region– Invokes URL once and puts responseText in result region

• Ajax.PeriodicalUpdater– Takes id of result region, URL, options object with g , , p j

“frequency” property. Can call “stop” on updater later.• Ajax.Response

Passed to response handler functions– Passed to response handler functions– properties: responseText, responseXML, responseJSON

8

Page 4: Prototype-1

Downloading and Installation

• Downloadh // j /d l d– http://www.prototypejs.org/download

• Download a single .js file (e.g., prototype-1.6.02.js)– Recommend renaming to prototype.js to simplify later upgrades

Thi t t i l d t P t t 1 6• This tutorial corresponds to Prototype 1.6

• Online API– http://www.prototypejs.org/apip p yp j g p

• Tips and Tutorials– http://www.prototypejs.org/learn

B C tibilit• Browser Compatibility– Firefox: 1.5 or later– Internet Explorer: 6.0 or later (does not work in IE 5.5!)Internet Explorer: 6.0 or later (does not work in IE 5.5!)– Safari: 2.0 or later– Opera: 9.25 or later

9

Industry Usage

10

Approximately 40% of matches to “prototype and JavaScript” were false positives such as “build a prototype with JavaScript”. So, discount the Prototype graph by about 40%.

Page 5: Prototype-1

© 2009 Marty Hall

Ajax Request:Ajax.Request:Basics

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.Request: Basic Syntax

• new Ajax.Request(relative-url, options)C ll l i l i Aj R– Calls relative-url, wraps response in Ajax.Reponse, passes response to function specified in options

• Note it is “new Ajax.Request(...)”, not “Ajax.Request(...)”

• Options– An anonymous object– Most important property: onSuccessMost important property: onSuccess

• Basic example– new Ajax.Request(

fil j"some-file.jsp",{onSuccess: someHandlerFunction});

– someHandlerFunction should take one argument of type Ajax ResponseAjax.Response.

– It is automatically wrapped in anonymous function with local copy of request object, so it is threadsafe.

12

Page 6: Prototype-1

Data-Centric Ajax with and without Toolkitswithout Toolkits

• With basic JavaScriptfunction getRequestObject() {if (window.XMLHttpRequest) {return(new XMLHttpRequest());

} else if (window.ActiveXObject) { return(new ActiveXObject("Microsoft.XMLHTTP"));

} else { return(null); }}function sendRequest() {var request = getRequestObject();request.onreadystatechange = function() { someFunct(request); };

request.open("GET", "some-url", true);request.send(null);

}13

Data-Centric Ajax with and without Toolkitswithout Toolkits

• jQuery (handler passed response text)$.ajax({url: "address",

success: handlerFunct});

Prototype (handler passed response object)• Prototype (handler passed response object)new Ajax.Request("address",

{onSuccess: handlerFunct});

• Ext (handler passed response object)Ext.Ajax.request({url: "address",

success: handlerFunct});

• Dojo (handler passed response text)d j h G t({ l " dd "dojo.xhrGet({url: "address",

load: handlerFunct});

14

Page 7: Prototype-1

Ajax.Request Example Code: JavaScriptJavaScriptfunction showTime1() {

new Ajax Request(new Ajax.Request("show-time.jsp",{ onSuccess: showAlert });

Thi i P t t Aj R bj t}

function showAlert(response) {

This is a Prototype Ajax.Response object,not the raw XmlHttpRequest.

alert(response.responseText);}

15

Ajax.Request Example Code: HTMLHTML...<head><title>Prototype and Ajax</title><head><title>Prototype and Ajax</title>...<script src="./scripts/prototype.js"

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

type="text/javascript"></script></head><body>...<fieldset>

<legend>Ajax.Request: Basics</legend>g j q / g<form action="#">

<input type="button" value="Show Time"onclick='showTime1()'/>onclick= showTime1() />

</form></fieldset>

16

Page 8: Prototype-1

Ajax.Request Example Code: JSPJSPIt is now <%= new java.util.Date() %>

17

Ajax.Request: Results

18

Page 9: Prototype-1

© 2009 Marty Hall

Ajax Request:Ajax.Request:Passing Parametersg

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.Request Options{ property1: v1 property2: v2 }{ property1: v1, property2: v2...}

• The second arg is an anonymous object with these as the most important propertiesas the most important properties– onSuccess (default: none)

• Response handler function (takes Ajax.Response as arg)• There are also many similar related options: onCompleteThere are also many similar related options: onComplete,

onFailure, onException, onXYX (for HTTP status codes)– parameters (default: empty string)

• Can be explicit parameter string: "p1=val1&p2=val2"• Can also be parameter object: {p1: val1, p2: val2}

– Values will be escaped automatically

– asynchronous (default: true)method (default: post)– method (default: post)

– evalJS (default: true)• Response text passed to “eval” if response type is

application/javascript or a similar typepp j p yp– evalJSON (default: true)

• Response text passed to eval (with parens added) and sent to responseJSON if response type is application/json

20

Page 10: Prototype-1

Ajax.Request Parameters Example Code: JavaScriptExample Code: JavaScriptfunction showParams1() {

new Ajax Request(new Ajax.Request("show-params.jsp",{ onSuccess: showAlert,

parameters: "param1=foo&param2=bar" });}

function showAlert(response) {alert(response.responseText);

}}

21

Ajax.Request Parameters Example Code: HTML and JSPExample Code: HTML and JSP<fieldset>

<legend>Ajax Request:<legend>Ajax.Request: The 'parameters' Option</legend>

<form action="#"><input type="button" value="Show Params"

onclick='showParams1()'/></form>

</fieldset>

22

Page 11: Prototype-1

Ajax.Request Parameters Example Code: HTML and JSPExample Code: HTML and JSP

• HTML<fieldset>

<legend>Ajax.Request: The 'parameters' Option</legend>p p g

<form action="#"><input type="button" value="Show Params"

onclick='showParams1()'/>onclick showParams1() /></form>

</fieldset>

• JSP (show-params.jsp)param1 is ${param param1}param1 is ${param.param1}, param2 is ${param.param2}.

23

Ajax.Request Parameters: Results

24

Page 12: Prototype-1

Utilities for Reading and Writing HTML ElementsHTML Elements

• $("id")– Returns element with given id [getElementById("id")]

• Can also take an Element instead of an element id• Can also take multiple arguments, in which case it returnsCan also take multiple arguments, in which case it returns

an array of the Element results• Yes, “$” is really the function name

• $F("id")• $F( id )– Returns value of form element with given ID

• Single value for most elements, array for multi-select listsg , y• For textfields, equivalent to $("id").value

• update("html-string")i i– Inserts into innerHTML property

– E.g., $("result-region").update("<h1>Test</h1>")25

Building Parameter Strings

• The $F function does not escape valuesS hi ld i ld ill l l– So, this could yield illegal results

• { onSuccess: someHandlerFunction,parameters: "param1=" + $F("field1") }

If fi ld 1 t i d t thi bl– If field 1 contains spaces, ampersands, etc., this causes problems– You could do escape($F("field1")), but this gets a bit verbose

• Instead of a parameter string, you can l t bj tsupply parameter object

– { param1: "val1", param2: "val2" ... }– Values (usually from $F(...)) are automatically escaped,Values (usually from $F(...)) are automatically escaped,

then whole thing converted to parameter string– You can also do this explicitly anywhere with $H

function that creates Hash and toQueryString methodfunction that creates Hash, and toQueryString method• $H({p1: "val1", p2: "val2"}).toQueryString() returns

"p1=val1&p2=val2"26

Page 13: Prototype-1

Ajax.Request: Reading/Writing UtilsExample Code: JavaScriptExample Code: JavaScriptfunction showParams2() {

var params =

Original (not escaped) value of textfieldwhose id (not name) is “field1”.

var params ={ param1: $F("field1"),

param2: $F("field2") };new Ajax.Request(

"show-params.jsp",{ onSuccess: updateResult,

parameters: params });} Parameter object is converted

to parameter string with escaped values.

function updateResult(response) {$("result1").update(response.responseText);

}}

27

Finds element whose id is "result1".Inserts into innerHTML property.

Ajax.Request: Reading/Writing UtilsExample Code: HTMLExample Code: HTML<fieldset>

<legend>Ajax Request:<legend>Ajax.Request: Reading/Writing Utilities</legend>

<form action="#">param1:<input type="text" id="field1"/><br/>param2:<input type="text" id="field2"/><br/>/<input type="button" value="Show Params"

onclick='showParams2()'/><h2 id="result1"></h2><h2 id= result1 ></h2>

</form></fieldset>

28

Page 14: Prototype-1

Ajax.Request: Reading/Writing Utils: ResultsUtils: Results

29

© 2009 Marty Hall

Ajax.Updater

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 15: Prototype-1

Ajax.Updater: Basic Syntax

• new Ajax.Updater(result-id, url, options)– Calls URL– Extracts resultText

Puts it into innerHTML of element with result id– Puts it into innerHTML of element with result-id

• Options– An anonymous object just as with Ajax RequestAn anonymous object, just as with Ajax.Request– Most important property: parameters– No onSuccess usually needed

31

Content-Centric Ajax with and without Toolkits (Basic JS Only)without Toolkits (Basic JS Only)

function getRequestObject() { ... }

function ajaxResult(address, resultRegion) {var request = getRequestObject();request.onreadystatechange =

function() { showResponseText(request, resultRegion); };

request.open("GET", address, true);request send(null);request.send(null);

}

function showResponseText(request, resultRegion) {p ( q , g ) {if ((request.readyState == 4) &&

(request.status == 200)) {document.getElementById(resultRegion).innerHTML =

t T trequest.responseText;}

}32

Page 16: Prototype-1

Content-Centric Ajax with and without Toolkits (Ajax Request)without Toolkits (Ajax.Request)

function ajaxResult(address, resultRegion) {new Ajax Request(new Ajax.Request(

address,{ onSuccess:

function(response) {function(response) {showResponseText(response, resultRegion);

}});});

}

function showResponseText(response, resultRegion) {u ct o s o espo se e t( espo se, esu t eg o ) {$(resultRegion).update(response.responseText);

}

33

Content-Centric Ajax with and without Toolkits (Libraries)without Toolkits (Libraries)

• jQueryfunction ajaxResult(address, resultRegion) {

$(resultRegion).load(address);}

• Prototypefunction ajaxResult(address, resultRegion) {

new Ajax.Updater(resultRegion, address);j p ( g , );}

• Dojol f– No explicit support for content-centric Ajax

• Ext-JSfunction ajaxResult(address resultRegion) {function ajaxResult(address, resultRegion) {

Ext.get(resultRegion).load({ url: address});}

34

Page 17: Prototype-1

Ajax.Updater Example Code:JavaScriptJavaScriptfunction showParams3() {

var params =var params ={ param1: $F("param3"),

param2: $F("param4") };new Ajax.Updater(

id of element into whose innerHTMLthe responseText is insertednew Ajax.Updater(

"result2", "show-params.jsp",{ parameters: params });

the responseText is inserted

{ parameters: params });}

• Notes• Notes– No onSuccess normally needed– Can update a single element only. If you need to update more, use

Ajax Request with onSuccessAjax.Request with onSuccess• You could also return script from server, but then server needs

to know name of DOM elements

35

Ajax.Updater Example Code:HTMLHTML<fieldset>

<legend>Ajax Updater</legend><legend>Ajax.Updater</legend><form action="#">

param1:/<input type="text" id="param3"/>

<br/>param2:<input type="text" id="param4"/><br/><input type="button" value="Show Params"p yp

onclick='showParams3()'/><h2 id="result2"></h2>

</form></form></fieldset>

36

Page 18: Prototype-1

Ajax.Updater: Results

37

Ajax.Updater Options

• evalScriptsShould <script> tags in the response be evaluated?– Should <script> tags in the response be evaluated?

– Default is false, so this option is very important if you return <script> tags that set event handlers (e.g. for scriptaculous in-place editors) for elements that are inserted)

• insertion– Where text should be inserted relative to what is already there.– Default is to replace any existing content.Default is to replace any existing content.– Options are 'top', 'bottom', 'before', 'after'

• Standard options still supported– parameters onSuccess etcparameters, onSuccess, etc.

• Example– var params = { param1: "foo", param2: "bar" };

new Ajax Updater("some id" "some address"– new Ajax.Updater( some-id , some-address ,{ evalScripts: true, insertion: 'top', parameters: params });

38

Page 19: Prototype-1

© 2009 Marty Hall

Aj P i di lU d tAjax.PeriodicalUpdater

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.PeriodicalUpdater Example Code: JavaScriptCode: JavaScriptvar updater; // Save ref so can "stop" later

function showTime2() {updater = new Ajax.PeriodicalUpdater(

"result3","show-time.jsp",{ frequency: 5 });

}

40

Page 20: Prototype-1

Ajax.PeriodicalUpdater Example Code: HTMLCode: HTML<fieldset>

<legend>Ajax PeriodicalUpdater</legend><legend>Ajax.PeriodicalUpdater</legend><form action="#">

<h2 id="result3"></h2>/<script type="text/javascript">

showTime2();</script><input type="button" value="Stop Updates"

onclick='updater.stop()'/></form>/

</fieldset>

• Note– Form needed only if you want to let user stop the action

41

Ajax.PeriodicalUpdater: Results

42

Page 21: Prototype-1

© 2009 Marty Hall

H dli JSON D tHandling JSON Data

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.Response Properties

• The arg passed to response handler has these as most important propertiesthese as most important properties– status, statusText

• HTTP status code and corresponding text– responseText

• Same as normal XmlHttpRequest.responseText– responseXMLespo se

• Same as normal XmlHttpRequest.responseXML– responseJSON

• Response text wrapped in parens and passed to "eval"Response text wrapped in parens and passed to eval• Only available if response type is application/json

– headerJSON• Evaluated content of X-JSON response header• Evaluated content of X-JSON response header• Alternative for responseJSON for small amounts of data

44

Page 22: Prototype-1

Ajax.Response Methods

• Can also call these methods on response– getHeader(responseHeaderName)

• Gets header value. • Does not throw exception if header missing (unlike nativeDoes not throw exception if header missing (unlike native

XmlHttpResponse method)

– getAllHeaders()• Returns a string with all headers delimited by newlines• Returns a string with all headers, delimited by newlines• Does not throw exception if there are no headers

– getResponseHeader, getAllResponseHeaders• Native version of above methods• Throws exceptions if headers missing• Used only with preexisting code that handled exeptions. y p g p

Use getHeader and getAllHeaders otherwise

45

Using JSON Data with responseJSON propertyresponseJSON property

• Response object properties – responseText, responseXML, and responseJSON– Response object passed to handler function (designated

with onSuccess etc )with onSuccess, etc.)– For more details see Ajax.Response in online API

• Behavior– Response text wrapped in parens and passed to "eval"

• Server returns { prop1: val1, prop2: val2 } without parens

R i t• Requirements– responseJSON populated only if response type is

application/jsonapplication/json

46

Page 23: Prototype-1

responseJSON Example Code: Core JavaScriptCore JavaScriptfunction showNums() {

new Ajax Request(new Ajax.Request("show-nums",{ onSuccess: showNumberList, Strings

method: "get" });}

function showNumberList(response) {var obj = response.responseJSON;var list = makeList(obj.fg, obj.bg, ( j g, j g,

obj.fontSize, obj.numbers);$("result4").update(list);

}}

47

Integer

Array of doubles

responseJSON Example Code: Auxiliary JavaScriptAuxiliary JavaScriptfunction makeList(fg, bg, fontSize, nums) {

return(return(listStartTags(fg, bg, fontSize) +listItems(nums) +listEndTags());listEndTags());

}

f ti li tSt tT (f b f tSi ) {function listStartTags(fg, bg, fontSize) {return(

"<div style='color:" + fg + "; " +"background-color:" + bg + "; " +"font-size:" + fontSize + "px'>\n" +

"<ul>\n");}

48

Page 24: Prototype-1

responseJSON Example Code: Auxiliary JavaScript (Continued)Auxiliary JavaScript (Continued)function listItems(items) {

var result = "";var result = ;for(var i=0; i<items.length; i++) {

result = result + "<li>" + items[i] + "</li>\n";}}return(result);

}

function listEndTags() {return("</ul></div>");

}

49

responseJSON Example Code: HTMLHTML<fieldset>

<legend>Ajax Request: responseJSON</legend><legend>Ajax.Request: responseJSON</legend><form action="#">

<input type="button" value="Show Nums"/onclick='showNums()'/>

<div id="result4"></div></form>

</fieldset>

50

Page 25: Prototype-1

responseJSON Example Code: ServletServlet

public class ShowNumbers extends HttpServlet {public void doGet(HttpServletRequest request,

HttpServletResponse response)throws ServletException, IOException {

response.setHeader("Cache-Control", "no-cache");response.setHeader("Pragma", "no-cache");p ( g , )String fg = ColorUtils.randomColor();request.setAttribute("fg", fg);String bg = ColorUtils.randomColor();request.setAttribute("bg", bg);request.setAttribute( bg , bg);String fontSize = "" + (10 + ColorUtils.randomInt(30));request.setAttribute("fontSize", fontSize);double[] nums = { Math random() Math random() Math random() };{ Math.random(), Math.random(), Math.random() };

request.setAttribute("nums", nums);response.setContentType("application/json");String outputPage = "/WEB-INF/results/show-nums.jsp";RequestDispatcher dispatcher =RequestDispatcher dispatcher =request.getRequestDispatcher(outputPage);

dispatcher.include(request, response);}}

51

responseJSON Example Code: JSP

{ fg: "${fg}",b "${b }"bg: "${bg}",fontSize: ${fontSize},numbers: [ ${nums[0]}, ${nums[1]}, ${nums[2]}][ { [ ]}, { [ ]}, { [ ]}]

}

Notes• Notes– Client-side code does not need wrap in parens and pass to

“eval”. JSON evaluation handled automatically byeval . JSON evaluation handled automatically by Prototype

– Typesf d b St i• fg and bg: Strings

• fontSize: int• numbers: Array of doubles52

Page 26: Prototype-1

JSON Example Code: Auxiliary Java CodeJava Code

public class ColorUtils {private static String[] colors = {p g[] {"aqua", "black", "blue", "fuchsia", "gray", "green", "lime", "maroon", "navy", "olive", "purple", "red", "silver", "teal", "white", "yellow"

};};

/** One of the official HTML color names, at random. */

public static String randomColor() {return(RandomUtils.randomElement(colors));

}

private ColorUtils() {} // Uninstantiatable class}}

53

JSON Example Code: Auxiliary Java CodeJava Code

public class RandomUtils {private static Random r = new Random();private static Random r = new Random();

public static int randomInt(int range) {return(r nextInt(range));return(r.nextInt(range));

}

public static int randomIndex(Object[] array) {public static int randomIndex(Object[] array) {return(randomInt(array.length));

}

public static <T> T randomElement(T[] array) {return(array[randomIndex(array)]);

}}}

54

Page 27: Prototype-1

responseJSON Example: ResultsResults

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: Prototype-1

“Best” JavaScript Librariesp

• General JS programming • Traditional Ajax support– Leader: Prototype

• Other programming (Java)– Leader (only): GWT

– Tie

• Server communication– Leader: GWTLeader (only): GWT

• DOM manipulation– Leader: jQuery

Oth i jQ h d

Leader: GWT– 2nd tier: DWR, JSON-RPC

• Usage in industry• Others copying jQuery approach and

closing gap. jQuery released CSS matching library separately (http://sizzlejs.com)

– Leader: jQuery– 2nd tier: Ext-JS, Dojo, YUI,

Prototype, Scriptaculous, GWT

• Rich GUIs– Leaders: Ext-JS, YUI, Dojo– 2nd tier: jQuery UI GWT

• Looking ahead– All these entries are likely to

change significantly– 2 tier: jQuery UI, GWT

• Familiarity to JS developers– Lowest: GWT

c ge s g c y– Lurking on the horizon:

Google “Closure” library57

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

58

Page 29: Prototype-1

Summary

• Ajax.RequestAj R (" l" { S h dl })– new Ajax.Request("url", { onSuccess: handler, ... });

• Also has parameters option (string or object)• Don't forget the “new”"

• Ajax.Updater– new Ajax.Updater("id", "url", {options});

• Ajax.PeriodicalUpdaterAjax.PeriodicalUpdater– new Ajax.PeriodicalUpdater("id", "url", { frequency: ...});

• Ajax.ResponseSO– Has responseJSON property

• Utility function– $("some-id") Element with that id( )– $F("some-id") Value of Element with that id– someElement.update("html") – inserts in innerHTML

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.