Google Web Toolkit
©2000-11 CRS Enterprises Ltd 1
by
Chris Seddon
Google Web Toolkit
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 2
1. Introduction to GWT2. Introduction JavaScript and CSS3. GWT : User Interface4. Events5. Internationalization and Bundles6. AJAX7. Server Communication8. Security
Google Web Toolkit
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 3
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 4
Copyright ©2000-11 CRS Enterprises Ltd 4
Introduction to GWT
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 5
Copyright ©2000-11 CRS Enterprises Ltd 5
Introduction to GWT
1
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 6
Copyright ©2000-11 CRS Enterprises Ltd 6
What is GWT?Development toolkit for building and optimizing com plex
browser-based applicationsyou write in JavaGoogle compiler translates code into JavaScript
No need to be an expert withdifferent browser quirksXMLHttpRequest objectJavaScriptCascading Style Sheets (CSS)
Open sourcecompletely freeused by thousands of developers around the world
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 7
Copyright ©2000-11 CRS Enterprises Ltd 7
Writing CodeGWT SDK provides a set of core Java APIs and Widget s
allows you to write AJAX applications in Javathen compile the source to highly optimized JavaScr ipt
Code runs across all browsersincluding mobile browsers for Android and the iPhon e
GWT is a higher level of abstraction on top of DOMXHR
You can also write directly in JavaScriptif GWT functionality unavailableyou want to interact with existing JavaScript libra ries
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 8
Copyright ©2000-11 CRS Enterprises Ltd 8
DebuggingDebug debug AJAX applications
in your favorite IDE (we are using Eclipse)using your favorite browser
GWT developer plugin (development mode)no compiling code to JavaScriptdebug in Java not JavaScript
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 9
Copyright ©2000-11 CRS Enterprises Ltd 9
OptimizeGWT compiler performs comprehensive optimizations
across your codebasein-lining methodsremoving dead codeoptimizing stringsset split-points in the code, so you can segment yo ur download into
multiple JavaScript fragments, splitting up large a pplications for faster startup time
Speed Tracer (Chrome)diagnose performance bottlenecks
in JavaScript and CSS
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 10
Copyright ©2000-11 CRS Enterprises Ltd 10
RunWhen you're debugged ...
GWT compiler translates your Java source code into optimized, stand-alone JavaScript files automatically run on all major browsers
as well as mobile browsers for Android and the iPho ne
Application automatically packaged as a WAR filemakes it easy to deploy to Glassfish, Tomcat ...
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 11
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 12
Copyright ©2000-11 CRS Enterprises Ltd 12
Introduction JavaScript and CSS
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 13
Copyright ©2000-11 CRS Enterprises Ltd 13
Introduction JavaScript and CSS
2
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 14
Copyright ©2000-11 CRS Enterprises Ltd 14
What is JavaScript?Scripting language
Usually associated with web client scriptinggenerally embedded in [X]HTML
Dynamic web pagesThe 'J' in AjaxCan be used as a general purpose scripting language
Server sidedirect support included in Java 6
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 15
Copyright ©2000-11 CRS Enterprises Ltd 15
JavaScript HistoryOriginally developed by Netscape
LiveScript
Name changed to JavaScript with the advent of Javabasically for marketing
JavaScript is not Javasome syntactic similaritiesvery different type systems
Standardised via ECMAECMAScript
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 16
Copyright ©2000-11 CRS Enterprises Ltd 16
Example JavaScript ProgramJavaScript is normally embedded in web pages using
<script> element
<html><head><script language="Javascript">function goodbye() { alert("Goodbye, thanks for calling");
} </script>
</head> <body onunload="goodbye()"><script language="Javascript">document.write("<h2>Hello, world</h2>");
</script></body>
</html>
<html><head><script language="Javascript">function goodbye() { alert("Goodbye, thanks for calling");
} </script>
</head> <body onunload="goodbye()"><script language="Javascript">document.write("<h2>Hello, world</h2>");
</script></body>
</html>
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 17
Copyright ©2000-11 CRS Enterprises Ltd 17
Variables and TypesJavaScript is dynamically typed
no need to declare variablesvariable name syntax similar to Java
Types: Number 3.14159String "Hello, world"Boolean true or falseNull nullObject collection of properties and possibly functio ns (methods)Functionblock of code
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 18
Copyright ©2000-11 CRS Enterprises Ltd 18
JavaScript and the WebMost JavaScript runs in Web Browsers
original purpose of the language
Adds many facilities to web pagesdynamic content generationclient side validation of user input through formsdisplaying messages to usersresponse to web page lifetime events
With CSS…dynamically changing pages possible
animation
Ajax…communication with server without page refresh
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 19
Copyright ©2000-11 CRS Enterprises Ltd 19
JavaScript ObjectsBrowser provides execution context for JavaScriptTo p
level object hierarchyeach object has properties and methodscan change page characteristics
e.g. assign to window.location to redirect to anoth er page
windowwindow
screenscreen historyhistory navigatornavigator toptop
documentdocument locationlocation frames []frames []
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 20
Copyright ©2000-11 CRS Enterprises Ltd 20
Dialog BoxesMethods on window object
appear as global methods
<script language="Javascript">prompt ("Enter the amount you wish to transfer")confirm ("Are you sure you want to move that much?")alert ("Something really bad just happened")
</script>
<script language="Javascript">prompt ("Enter the amount you wish to transfer")confirm ("Are you sure you want to move that much?")alert ("Something really bad just happened")
</script>
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 21
Copyright ©2000-11 CRS Enterprises Ltd 21
Document ObjectRoot of hierarchy of page content
each element represented by an object
<html><head><title>My Document</title>
</head><body><h1>My Document</h1><p>It's <i>very</i> simple!</p>
</body></html>
<html><head><title>My Document</title>
</head><body><h1>My Document</h1><p>It's <i>very</i> simple!</p>
</body></html>
documentdocument
<html><html>
<head><head> <body><body>
<title><title> <h1><h1> <p><p>
<i><i>
It'sIt's veryvery simple!simple!
My DocumentMy Document My DocumentMy Document
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 22
Copyright ©2000-11 CRS Enterprises Ltd 22
Cross Browser CompatibilityNot all browsers use exactly the same DOM model for
pagesattributes may be different
Difficult to write JavaScript that works across all browsersJavaScript may not even be supported
<noscript>…</noscript> can be added to page if no J avaScript
Applications will be required to support a defined set of browsers
IE, Firefox, Safari, Operatoolkits and libraries of JavaScript code make this easier
GWTDojoJQuery
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 23
Copyright ©2000-11 CRS Enterprises Ltd 23
The Need for CSSTraditional HTML is a hybrid markup language
specifies content and structure of pages<p>, <img>, <ul>, <ol>, <table>, etc
also specifies appearance<font>, <i>, <b>, etccolor, padding, spacing attributes
Over large websites with many pages ...consistency can become a problemchanges very difficult to implement
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 24
Copyright ©2000-11 CRS Enterprises Ltd 24
History of CSSW3C standardInitially proposed in 1996CSS2 defined in 1998
supported by most modern browsersallows specification of styles of elements to be ga thered together
in one place: "the style sheet"
Cascading Stylesstyle applied to element may include components fro m enclosing
elements
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 25
Copyright ©2000-11 CRS Enterprises Ltd 25
CSS ExampleStyles can be embedded
in HTMLor placed in a separate file
<html><head>
<title>First Look At CSS</title><style type="text/css">body {
background: aqua;font-family: Helvetica, Arial, Vendana;
}h1 {
color: darkblue;font-style: italic;
}</style>
</head><body>
<h1>Hello, CSS!</h1><p>Here we go with our first page styled with CSS</p>
</body></html>
<html><head>
<title>First Look At CSS</title><style type="text/css">body {
background: aqua;font-family: Helvetica, Arial, Vendana;
}h1 {
color: darkblue;font-style: italic;
}</style>
</head><body>
<h1>Hello, CSS!</h1><p>Here we go with our first page styled with CSS</p>
</body></html>
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 26
Copyright ©2000-11 CRS Enterprises Ltd 26
CSS in Linked File
<html><head>
<title>First Look At CSS</title><link rel="stylesheet" type="text/css"href="…/mystyle.css" />
</head><body><h1>Hello, CSS!</h1><p>
Here we go with our first page styled with CSS</p></body></html>
<html><head>
<title>First Look At CSS</title><link rel="stylesheet" type="text/css"href="…/mystyle.css" />
</head><body><h1>Hello, CSS!</h1><p>
Here we go with our first page styled with CSS</p></body></html>
body {background: aqua;
font-family: Helvetica, Arial, Vendana;}h1 {color: darkblue;font-style: italic;}
body {background: aqua;
font-family: Helvetica, Arial, Vendana;}h1 {color: darkblue;font-style: italic;}
myfile.htmlmyfile.html
mystyle.cssmystyle.css
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 27
Copyright ©2000-11 CRS Enterprises Ltd 27
SelectorsDifferent forms of selector
selector{property:value;property:value;…}selector{property:value;property:value;…}
which elements this style applies to properties and values
E { … }.c { … }#i { … } E1 E2 { … }E.c { … } E:pc { … }
E { … }.c { … }#i { … } E1 E2 { … }E.c { … } E:pc { … }
apply to all E elements apply to all elements with "class='c'" apply to all elements with "id='i'" apply to all E2 elements nested within E1 elements apply to all E elements with "class='c'" apply to all E elements with pseudoclass "pc"
apply to all E elements apply to all elements with "class='c'" apply to all elements with "id='i'" apply to all E2 elements nested within E1 elements apply to all E elements with "class='c'" apply to all E elements with pseudoclass "pc"
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 28
Copyright ©2000-11 CRS Enterprises Ltd 28
CSS ReferenceUse the w3schools site
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 29
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 30
Copyright ©2000-11 CRS Enterprises Ltd 30
GWT : User Interface
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 31
Copyright ©2000-11 CRS Enterprises Ltd 31
GWT : User Interface
3
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 32
Copyright ©2000-11 CRS Enterprises Ltd 32
GWT Showcasehttp://gwt.google.com/samples/Showcase/Showcase.htm l
examples for all common widgets
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 33
Copyright ©2000-11 CRS Enterprises Ltd 33
Viewing CSSCSS examples
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 34
Copyright ©2000-11 CRS Enterprises Ltd 34
Viewing CodeExample code to create widgets
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 35
Copyright ©2000-11 CRS Enterprises Ltd 35
Panels ...RootPanel
top-most panel to which all other widgets are ultim ately attachedwraps <body> tag
FlowPanelcreates a single <div> element and attaches childre n directly to it
HTMLPanelprovides a simple way to define an HTML structure, within which widgets
will be embedded at defined pointsyou may use it directly, but it is most commonly us ed in UiBinder
templates
FormPanelfor reproducing the behavior of an HTML formwraps <form> element
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 36
Copyright ©2000-11 CRS Enterprises Ltd 36
... PanelsScrollPanel
creates a scrollable area within another panel
PopupPanel and DialogBoxthese two panels create simple popups and modal dia logs
they overlap existing content in browser window and can be stacked
Grid and FlexTablethese two widgets are used to create traditional HT ML <table> elementscan also be used as panels
arbitrary widgets may be added to their cells
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 37
Copyright ©2000-11 CRS Enterprises Ltd 37
Welcome FileInitial Page to be displayed (see web.xml)
Creates skeleton for the UI
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 38
Copyright ©2000-11 CRS Enterprises Ltd 38
Default Welcome Page
RootPanel panel1 = RootPanel.get("nameFieldContaine r")RootPanel panel1 = RootPanel.get("nameFieldContaine r")
RootPanel panel1 = RootPanel.get("nameFieldContaine r")RootPanel panel1 = RootPanel.get("nameFieldContaine r")
RootPanel panel1 = RootPanel.get( )RootPanel panel1 = RootPanel.get( )
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 39
Copyright ©2000-11 CRS Enterprises Ltd 39
CSS
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 40
Copyright ©2000-11 CRS Enterprises Ltd 40
Applying StylesCSS styles can be added using addStyleName
widgets can have multiple stylesthe first is calleed the Primary style
public void onModuleLoad() {final Button sendButton = new Button("Send");
// We can add style names to widgetssendButton.addStyleName ("sendButton ");...
}
public void onModuleLoad() {final Button sendButton = new Button("Send");
// We can add style names to widgetssendButton.addStyleName ("sendButton ");...
}
.sendButton {display: block;font-size: 16pt;
}
.sendButton {display: block;font-size: 16pt;
}
MyApp.javaMyApp.java
MyApp.cssMyApp.css
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 41
Copyright ©2000-11 CRS Enterprises Ltd 41
Application ConfigurationConfiguration file is XML
defines entry pointmodules to be loadedclasses to be compiled to JavaScript
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 42
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 43
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 44
Copyright ©2000-11 CRS Enterprises Ltd 44
Events
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 45
Copyright ©2000-11 CRS Enterprises Ltd 45
Events
4
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 46
Copyright ©2000-11 CRS Enterprises Ltd 46
InterfacesBase interface for all Events
Click events
Mouse Move events
Key Press events
public interface EventHandler { }public interface EventHandler { }
public interface ClickHandler extends EventHandler {void onClick(ClickEvent event);
}
public interface ClickHandler extends EventHandler {void onClick(ClickEvent event);
}
public interface MouseMoveHandler extends EventHand ler {void onMouseMove(MouseMoveEvent event);
}
public interface MouseMoveHandler extends EventHand ler {void onMouseMove(MouseMoveEvent event);
}
public interface KeyPressHandler extends EventHandl er {void onKeyPress(KeyPressEvent event);
}
public interface KeyPressHandler extends EventHandl er {void onKeyPress(KeyPressEvent event);
}
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 47
Copyright ©2000-11 CRS Enterprises Ltd 47
Event HandlersUse an anonymous class to define a class derived fr omClickHandler
Use the handler when you define each button
ClickHandler CreateClickHandler() {ClickHandler handler = new ClickHandler() {
public void onClick (ClickEvent event) {Button button = (Button) event.getSource() ;Window.alert(button.getText() + " clicked");
}};return handler;
}
ClickHandler CreateClickHandler() {ClickHandler handler = new ClickHandler() {
public void onClick (ClickEvent event) {Button button = (Button) event.getSource() ;Window.alert(button.getText() + " clicked");
}};return handler;
}
final Button button = new Button("My Button", clickHandler);final Button button = new Button("My Button", clickHandler);
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 48
Copyright ©2000-11 CRS Enterprises Ltd 48
Event BubblingEvents bubble up through DOM hierarchy
can be cancelled if desired
RootPanelRootPanel
public void onClick(ClickEvent event) {event.stopPropagation();
}
public void onClick(ClickEvent event) {event.stopPropagation();
}
VerticalPanelVerticalPanel
WidgetWidget
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 49
Copyright ©2000-11 CRS Enterprises Ltd 49
DOM EventsHandlers are often shared
e.g. DOM handlers
class MyClickHandler implements ClickHandler {
public void onClick(ClickEvent event) {boolean bubble = Window.confirm(message.toString()) ;if(!bubble) event.stopPropagation();
}}
class MyClickHandler implements ClickHandler {
public void onClick(ClickEvent event) {boolean bubble = Window.confirm(message.toString()) ;if(!bubble) event.stopPropagation();
}}
root.addDomHandler(clickHandler, ClickEvent. getType ());panelA.addDomHandler(clickHandler, ClickEvent. getType ());panelB.addDomHandler(clickHandler, ClickEvent. getType ());child1.addDomHandler(clickHandler, ClickEvent. getType ());
root.addDomHandler(clickHandler, ClickEvent. getType ());panelA.addDomHandler(clickHandler, ClickEvent. getType ());panelB.addDomHandler(clickHandler, ClickEvent. getType ());child1.addDomHandler(clickHandler, ClickEvent. getType ());
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 50
Copyright ©2000-11 CRS Enterprises Ltd 50
EfficiencyBe wary of using too many anonymous handlers
try to share handlers
Some composite widgets have restrictive handlerscomponents do not have handlers only the composite
FlexTable flexTable = new FlexTable();flexTable.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {FlexTable table = (FlexTable) event.getSource();Cell cell = table.getCellForEvent(event);int row = cell.getRowIndex();int col = cell.getCellIndex();if (cellFormatter.getStyleName(row, col).equals("li ght"))
cellFormatter.setStyleName(row, col, "dark");else
cellFormatter.setStyleName(row, col, "light");}
});
FlexTable flexTable = new FlexTable();flexTable.addClickHandler(new ClickHandler() {
public void onClick(ClickEvent event) {FlexTable table = (FlexTable) event.getSource();Cell cell = table.getCellForEvent(event);int row = cell.getRowIndex();int col = cell.getCellIndex();if (cellFormatter.getStyleName(row, col).equals("li ght"))
cellFormatter.setStyleName(row, col, "dark");else
cellFormatter.setStyleName(row, col, "light");}
});
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 51
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 52
Copyright ©2000-11 CRS Enterprises Ltd 52
Internationalization and Bundles
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 53
Copyright ©2000-11 CRS Enterprises Ltd 53
Internationalization and Bundles
5
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 54
Copyright ©2000-11 CRS Enterprises Ltd 54
InternationalizationApplication can abstract constants and messages
independent of locale
Locale bindings are provided using property files
Write1) Property file2) Interface file to represent properties
FrenchFrench (France)
French (Canada)EnglishGerman
FrenchFrench (France)
French (Canada)EnglishGerman
frfr_FRfr_CA
ende
frfr_FRfr_CA
ende
MyMessages_fr.propertiesMyMessages_fr_FR.propertiesMyMessages_fr_CA.propertiesMyMessages_en.propertiesMyMessages_de.properties
MyMessages_ fr .propertiesMyMessages_ fr_FR.propertiesMyMessages_ fr_CA .propertiesMyMessages_ en.propertiesMyMessages_ de.properties
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 55
Copyright ©2000-11 CRS Enterprises Ltd 55
Property Files (Constants)Define constants for each locale
MyConstants_de.propertiesMyConstants_de.properties
day1=Montagday2=Dienstagday3=Mittwochday4=Donnerstagday5=Freitagday6=Samstagday7=Sonntag
day1=Montagday2=Dienstagday3=Mittwochday4=Donnerstagday5=Freitagday6=Samstagday7=Sonntag
MyConstants_fr.propertiesMyConstants_fr.properties
day1=Liundiday2=Mardiday3=Mercrediday4=Jeudiday5=Vendrediday6=Samdiday7=Dimanche
day1=Liundiday2=Mardiday3=Mercrediday4=Jeudiday5=Vendrediday6=Samdiday7=Dimanche
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 56
Copyright ©2000-11 CRS Enterprises Ltd 56
Interface (Constants)Define an interface for the constants
define a method for each constantGWT will generate implementations
public interface MyConstants extends Constants {String day1();String day2();String day3();String day4();String day5();String day6();String day7();
}
public interface MyConstants extends Constants {String day1();String day2();String day3();String day4();String day5();String day6();String day7();
}
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 57
Copyright ©2000-11 CRS Enterprises Ltd 57
Property Files (Messages)Define messages for each locale
{0} - first parameter{1} - second parameter{2} - third parameter, etc
MyMessages_fr.propertiesMyMessages_fr.properties
greeting=Aujourd'hui, c'est {0}, mais demain est un {1}.greeting=Aujourd'hui, c'est {0} , mais demain est un {1} .
MyMessages_de.propertiesMyMessages_de.properties
greeting=Heute ist {0}, aber morgen ist {1}greeting=Heute ist {0} , aber morgen ist {1}
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 58
Copyright ©2000-11 CRS Enterprises Ltd 58
Interface (Messages)Define an interface for the messages
define a method for each messageGWT will generate implementations
public interface MyMessages extends Messages {String greeting(String today, String tomorrow);
}
public interface MyMessages extends Messages {String greeting(String today, String tomorrow);
}
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 59
Copyright ©2000-11 CRS Enterprises Ltd 59
Using Constants and Messages
private Widget BuildVerticalPanel() {MyConstants constants = GWT. create (MyConstants.class);MyMessages messages = GWT. create (MyMessages.class);
VerticalPanel vPanel = new VerticalPanel();vPanel.add(new Label(constants.day1()));vPanel.add(new Label(constants.day2()));vPanel.add(new Label(constants.day3()));vPanel.add(new Label(constants.day4()));vPanel.add(new Label(constants.day5()));vPanel.add(new Label(constants.day6()));vPanel.add(new Label(constants.day7()));String today = constants.day1();String tomorrow = constants.day2();vPanel.add(new Label(messages.greeting(today, tomor row)));
private Widget BuildVerticalPanel() {MyConstants constants = GWT.create (MyConstants.class);MyMessages messages = GWT.create (MyMessages.class);
VerticalPanel vPanel = new VerticalPanel();vPanel.add(new Label( constants .day1()));vPanel.add(new Label( constants .day2()));vPanel.add(new Label( constants .day3()));vPanel.add(new Label( constants .day4()));vPanel.add(new Label( constants .day5()));vPanel.add(new Label( constants .day6()));vPanel.add(new Label( constants .day7()));String today = constants.day1();String tomorrow = constants.day2();vPanel.add(new Label( messages .greeting(today, tomorrow)));
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 60
Copyright ©2000-11 CRS Enterprises Ltd 60
Selecting the LocaleAdd all locales to project configuartion file
Choose actual locale in HTML file
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"><meta name="gwt:property" content="locale=de"><link type="text/css" rel="stylesheet" href="Consta ntsAndMessages.css"><title>Constants and Messages</title> <script type="text/javascript" language="javascript "
src="constantsandmessages/constantsandmessages.noca che.js"></script></head> ...
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"><meta name="gwt:property" content="locale=de"><link type="text/css" rel="stylesheet" href="Consta ntsAndMessages.css"><title>Constants and Messages</title> <script type="text/javascript" language="javascript "
src="constantsandmessages/constantsandmessages.noca che.js"></script></head> ...
<module rename-to= 'constantsandmessages' >...<extend-property name= "locale" values= "fr" /><extend-property name= "locale" values= "fr_FR" /><extend-property name= "locale" values= "fr_CA" /><extend-property name= "locale" values= "en" /><extend-property name= "locale" values= "de" /><set-property-fallback name= "locale" value= "en" />...</module>
<module rename-to= 'constantsandmessages' >...<extend-property name= "locale" values= "fr" /><extend-property name= "locale" values= "fr_FR" /><extend-property name= "locale" values= "fr_CA" /><extend-property name= "locale" values= "en" /><extend-property name= "locale" values= "de" /><set-property-fallback name= "locale" value= "en" />...</module>
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 61
Copyright ©2000-11 CRS Enterprises Ltd 61
Image BundlesAn image bundle
used to improve application performancereduces HTTP round trips
GWT can package many image files into a single filedownloaded from the server and managed as a Java ob jectin a standard web application
HTTP request has to be sent to the server for each image
Useless freshness checkseven when the images have been cached by the client
a 304 ("Not Modified") request is still sent to che ck if image has changed
images change infrequently, these freshness checks wasteful
Blocking HTTP connectionsHTTP 1.1 requires browsers to limit connections to two per domain/port
many image requests will tie up the browser's avail able connections
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 62
Copyright ©2000-11 CRS Enterprises Ltd 62
Image BundlesDefine a ClientBundle
Instantiate resoucesthen use methods to create individual resources
public interface MyResources extends ClientBundle {@Source("images/rabbit.gif")ImageResource rabbit();
@Source("images/warning.png")ImageResource warning();}
public interface MyResources extends ClientBundle {@Source("images/rabbit.gif")ImageResource rabbit();
@Source("images/warning.png")ImageResource warning();}
MyResources resources = GWT.create(MyResources.class);Image rabbit = new Image(resources.rabbit());
MyResources resources = GWT.create(MyResources.class);Image rabbit = new Image(resources.rabbit());
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 63
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 64
Copyright ©2000-11 CRS Enterprises Ltd 64
AJAX
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 65
Copyright ©2000-11 CRS Enterprises Ltd 65
6
AJAX
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 66
Copyright ©2000-11 CRS Enterprises Ltd 66
What is Ajax?"Asynchronous JavaScript and XML"
Originally described in 2005Essentially distills existing technologies
Modified way of handling communication between web client and server
Partial screen update availableReplaces traditional click-wait-redraw modelFaster responsesRemaining page context available during refresh
Updates can be triggered on different eventsNo longer necessary to click on link or button
Enables "push" style data driven applications
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 67
Copyright ©2000-11 CRS Enterprises Ltd 67
Ajax In ActionMany popular web apps using Ajax
Google Office ApplicationsCreation of thick client look and feel
Google MapsBackground fetch of map data
FlickrBackground fetch of photos for display
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 68
Copyright ©2000-11 CRS Enterprises Ltd 68
The Ajax Web Application Model
WebServer
DataStore,
Backendprocessing
UserInterface
HTTP(S)
HTML + CSS
WithoutAjax
WebServer
DataStore,
Backendprocessing
UserInterface
AjaxEngine
HTTP(S)
XML / text data
JavaScript
HTML + CSS
WithAjax
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 69
Copyright ©2000-11 CRS Enterprises Ltd 69
The Ajax Web Application Model - 2
data data data datatime
Client
Server
input display
data data data datatime
Client
Server
Browser UI
Ajax Engine
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 70
Copyright ©2000-11 CRS Enterprises Ltd 70
Steps in an Ajax InteractionExample - to validate input
Database
ValidateServlet
george Submit
<script>
</script>
XMLHttpRequest
function callback() {// Update HTML DOM with result
}
<message>Bad id
</message>
1
2
3
4
56
7"onkeyup" event
validate?id=george
…invalid…
isgeorge valid?
no
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 71
Copyright ©2000-11 CRS Enterprises Ltd 71
1. XHttpRequest Object
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 72
Copyright ©2000-11 CRS Enterprises Ltd 72
Introducing XMLHttpRequestJavaScript object
encapsulates making HTTP request from browser to se rver
Supported in modern browsersMozilla, Firefox, Safari, Operaequivalent support in Internet Explorer with XMLHTT P object
Supports standard HTTP operationsGET, POST, HEAD
Synchronous and asynchronous operationasynchronous operation allows request status to be examined
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 73
Copyright ©2000-11 CRS Enterprises Ltd 73
XMLHttpRequest Methodsopen(http-method, url, synch-or-asynch)
initialisation, with URL, HTTP method and synchrono us or asynchronous flag
send(content)make the call, including text or XML content
setRequestHeader(label, value)before sending
abort( )abort current call
getAllResponseHeaders( )getResponseHeader(header)
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 74
Copyright ©2000-11 CRS Enterprises Ltd 74
XMLHttpRequest Propertiesonreadystatechange
event handler called whenever readyState changes
readyStatecurrent status of request
statusHTTP status
responseTextresponse as text
responseXMLresponse as XML
statusTextstatus as text
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 75
Copyright ©2000-11 CRS Enterprises Ltd 75
The readyState PropertyFor asynchronous operation
Value is integer between 0 and 4
Use event handler to be notified of changes to valu e
Some browser inconsistencies with state 3e.g. Firefox
0 not initialised - open() not yet called
1 initialised but send() not called
2 send() called but no response from server
3 data being received from server
4 request is complete
0 not initialised - open() not yet called
1 initialised but send() not called
2 send() called but no response from server
3 data being received from server
4 request is complete
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 76
Copyright ©2000-11 CRS Enterprises Ltd 76
Request Timeouts What if the server does not respond?
Synchronous requests block entire browser
Asynchronous requests can be timed outUse Window.setTimeout() with
XMLHttpRequest.abort()If response arrives before timeout,
use Window.clearTimeout()
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 77
Copyright ©2000-11 CRS Enterprises Ltd 77
2. Sending and Receiving Data
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 78
Copyright ©2000-11 CRS Enterprises Ltd 78
Sending and Receiving DataGET vs. POST requestsPlain textXML JSON
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 79
Copyright ©2000-11 CRS Enterprises Ltd 79
HTTP GET vs. POST RequestsGET
"Fetch me this resource"May have parameter values attached to URL
Used for links or direct buttons, not recommended f or forms
POST"Pass this data to the resource and fetch back any response"Parameter values passed as body of HTTP requestRecommended with formsPossible to pass large amounts of data
e.g. Webmail messages
http://www.foo.com/clever_resource?var1=val1&var2=val2http://www.foo.com/clever_resource?var1=val1&var2=val2
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 80
Copyright ©2000-11 CRS Enterprises Ltd 80
Response Encodings – Plain TextResponses may be sent in different forms
Plain text"text/plain" resp.setContentType("text/plain");
resp.setHeader("Cache-Control", "no-cache");resp.getWriter().write("…message…");
resp.setContentType("text/plain");resp.setHeader("Cache-Control", "no-cache");resp.getWriter().write("…message…");
function setUIDMsg(msg) {var msgEl = document.getElementById("userIdMsg");if ( req.getResponseHeader() == "text/plain" ) {msgEl.innerHTML = msg;
}}
function setUIDMsg(msg) {var msgEl = document.getElementById("userIdMsg");if ( req.getResponseHeader() == "text/plain" ) {msgEl.innerHTML = msg;
}}
Get reference to elementwhere we want to putthe message text
serverserver
clientclient
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 81
Copyright ©2000-11 CRS Enterprises Ltd 81
Response Encodings - XMLFor structured or more
complex data, XML is often used"text/xml"Requires more work
in responsehandling at client side
resp.setContentType("text/xml");resp.setHeader("Cache-Control", "no-cache");resp.getWriter().write("
<book><author>John Doe</author><title>All About Ajax</title>
</book>");
resp.setContentType("text/xml");resp.setHeader("Cache-Control", "no-cache");resp.getWriter().write("
<book><author>John Doe</author><title>All About Ajax</title>
</book>");
serverserver
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 82
Copyright ©2000-11 CRS Enterprises Ltd 82
Response Encodings - JSONJavaScript Object
Notation (JSON)serialization of JavaScript
object and array structures"text/json"
"text/javascript""application/javascript""application/x-javascript"
[ "author": "John Doe","title": "All About Ajax"
]
[ "author": "John Doe","title": "All About Ajax"
]
resp.setContentType("text/javascript");resp.setHeader("Cache-Control", "no-cache");resp.getWriter().write("
["author": "John Doe","title": "All About Ajax"
]");
resp.setContentType("text/javascript");resp.setHeader("Cache-Control", "no-cache");resp.getWriter().write("
["author": "John Doe","title": "All About Ajax"
]");
serverserver
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 83
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 84
Copyright ©2000-11 CRS Enterprises Ltd 84
Server Communication
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 85
Copyright ©2000-11 CRS Enterprises Ltd 85
Server Communication
7
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 86
Copyright ©2000-11 CRS Enterprises Ltd 86
RPC Mechanisms1. GWT RPC - Remote Procedure Calls (AJAX)
mechanism for passing Java objects to and from a se rver over HTTPGWT RPC to transparently makes call to Java servlet s
takes care of low-level details like object seriali zation
2. Asynchronous HTTP (AJAX)if your application talks to a server that cannot h ost Java servletsor uses another data format like JSON or XML
use RequestBuilder class
3. Form Submissionconvention form submission with submit buttonessentially synchronous
page refreshes do occur
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 87
Copyright ©2000-11 CRS Enterprises Ltd 87
1. GWT RPCClient Side
interfacesservice interface (extends RemoteService)async service interface
implementationclick handler (subclass of ClickHandler)callback (AsyncCallback<T>)
Server Sideimplementation of client service interface
extends RemoteServiceServlet
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 88
Copyright ©2000-11 CRS Enterprises Ltd 88
Client InterfacesService Interface
Async Interfacevoid returnAsyncCallback<T>
@RemoteServiceRelativePath("average")public interface MyService extends RemoteService {
Double average(Double x, Double y) throws IllegalArgumentException;}
@RemoteServiceRelativePath("average")public interface MyService extends RemoteService {
Double average(Double x, Double y) throws IllegalArgumentException;}
public interface MyServiceAsync {void average(Double x, Double y, AsyncCallback<Double> callback )throws IllegalArgumentException;
}
public interface MyServiceAsync {void average(Double x, Double y, AsyncCallback<Double> callback )throws IllegalArgumentException;
}
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 89
Copyright ©2000-11 CRS Enterprises Ltd 89
public class GWT_RPC implements EntryPoint {private final MyServiceAsync myService = GWT.create(MyService.class);
class MyHandler implements ClickHandler {public void onClick(ClickEvent event) {...myService .average(x, y, new AsyncCallback<Double> () {public void onFailure (Throwable e) {Window.alert(e.toString());
}public void onSuccess (Double result) {Window.alert("" + result);
}});
}}public void onModuleLoad() { ... }
}
public class GWT_RPC implements EntryPoint {private final MyServiceAsync myService = GWT.create(MyService.class);
class MyHandler implements ClickHandler {public void onClick(ClickEvent event) {...myService .average(x, y, new AsyncCallback<Double> () {public void onFailure (Throwable e) {Window.alert(e.toString());
}public void onSuccess (Double result) {Window.alert("" + result);
}});
}}public void onModuleLoad() { ... }
}
Client Implementation
MyHandler handler = new MyHandler();averageButton.addClickHandler(handler);
MyHandler handler = new MyHandler();averageButton.addClickHandler(handler);
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 90
Copyright ©2000-11 CRS Enterprises Ltd 90
Server ImplementationMust be a servlet
RemoteServiceServlet is a subclass of GenericServle t
public class MyServiceImpl extends RemoteServiceServlet implements MyService {
public Double average (Double x, Double y) throws IllegalArgumentException {
return (x + y)/2.0;}
}
public class MyServiceImpl extends RemoteServiceServlet implements MyService {
public Double average (Double x, Double y) throws IllegalArgumentException {
return (x + y)/2.0;}
}
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 91
Copyright ©2000-11 CRS Enterprises Ltd 91
2. Asynchronous HTTPClient Side
Create a RequestBuilderto define what gets sent to server
Use RequestBuilder.sendRequest() to deliver dataspecify data to be sent (name, value pairs)callback for results
Server Sideprovide an implementation that process request and provides a response
doesn't have to be a servletif servlet
use request.getParameter() to extract data
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 92
Copyright ©2000-11 CRS Enterprises Ltd 92
Setting up RequestBuilderMust use POSTMust use application/x-www-form-urlencoded as the
Content-typeor the server won't process the data
public void setupCommunicationWithServer() {myBuilder = new RequestBuilder(
RequestBuilder.POST , "/MyRequestBuilder/MyServlet");myBuilder.setHeader("Content-type ",
"application/x-www-form-urlencoded ");myBuilder.setUser("Tom");myBuilder.setPassword("MOT");myBuilder.setTimeoutMillis(20 * 1000);
}
public void setupCommunicationWithServer() {myBuilder = new RequestBuilder(
RequestBuilder.POST , "/MyRequestBuilder/MyServlet");myBuilder.setHeader("Content-type ",
"application/x-www-form-urlencoded ");myBuilder.setUser("Tom");myBuilder.setPassword("MOT");myBuilder.setTimeoutMillis(20 * 1000);
}
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 93
Copyright ©2000-11 CRS Enterprises Ltd 93
Sending the DataUse sendRequest inside a UI handler
private MouseOverHandler createHandler() {MouseOverHandler handler = new MouseOverHandler() {
public void onMouseOver(MouseOverEvent event) {try {Label label = (Label) event.getSource();String requestData = "x=" + xText.getValue() +
"&y=" + yText.getValue() +"&op=" + label.getText();
myBuilder.sendRequest (requestData, callback );} catch (RequestException e) {e.printStackTrace();
}}
};return handler;
}
private MouseOverHandler createHandler() {MouseOverHandler handler = new MouseOverHandler() {
public void onMouseOver(MouseOverEvent event) {try {Label label = (Label) event.getSource();String requestData = "x=" + xText.getValue() +
"&y=" + yText.getValue() +"&op=" + label.getText();
myBuilder.sendRequest (requestData, callback );} catch (RequestException e) {e.printStackTrace();
}}
};return handler;
}
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 94
Copyright ©2000-11 CRS Enterprises Ltd 94
Creating the CallbackUse an anonymous class to define the callback:
public class MyRequestBuilder implements EntryPoint {private RequestCallback callback ;
private void setupCallback() {callback = new RequestCallback() {
public void onResponseReceived (Request request, Response response) {resultLabel.setText(response.getText());
}
public void onError (Request request, Throwable exception) {Window.alert(exception.toString());
}
};}
public class MyRequestBuilder implements EntryPoint {private RequestCallback callback ;
private void setupCallback() {callback = new RequestCallback() {
public void onResponseReceived (Request request, Response response) {resultLabel.setText(response.getText());
}
public void onError (Request request, Throwable exception) {Window.alert(exception.toString());
}
};}
successsuccess
failurefailure
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 95
Copyright ©2000-11 CRS Enterprises Ltd 95
3. Form SubmissionClient Side
Use a FormPanelneeds an action and method to be defined
Provide a submit button with two handlersSubmitHandler
to send request to serverSubmitCompleteHandler
to recieve response from server
Server Sideprovide an implementation that process request and provides a response
doesn't have to be a servletif servlet
use request.getParameter() to extract data
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 96
Copyright ©2000-11 CRS Enterprises Ltd 96
Configure a FormPanel
public class MyForm implements EntryPoint {public void onModuleLoad() {// Create a FormPanel and point it at a service.final FormPanel form = new FormPanel();form.setAction ("/MyForm/MyServlet");form.setMethod (FormPanel.METHOD_POST);Grid grid = new Grid(4,2);
// Add a 'submit' buttongrid.setWidget(3, 0, new Button("Submit", new ClickHandler() {public void onClick(ClickEvent event) {form.submit();
}}));RootPanel.get().add(form);
}}
public class MyForm implements EntryPoint {public void onModuleLoad() {// Create a FormPanel and point it at a service.final FormPanel form = new FormPanel();form.setAction ("/MyForm/MyServlet");form.setMethod (FormPanel.METHOD_POST);Grid grid = new Grid(4,2);
// Add a 'submit' buttongrid.setWidget(3, 0, new Button("Submit", new ClickHandler() {public void onClick(ClickEvent event) {form.submit();
}}));RootPanel.get().add(form);
}}
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 97
Copyright ©2000-11 CRS Enterprises Ltd 97
Submit HandlersAdd an submit handler for validation before submit
Add an submit complete handler for getting results
form.addSubmitHandler(new SubmitHandler() {public void onSubmit (SubmitEvent event) {
if (nameBox.getText().length() == 0) {Window.alert("name must not be empty");event.cancel();
}}
});
form.addSubmitHandler(new SubmitHandler() {public void onSubmit (SubmitEvent event) {
if (nameBox.getText().length() == 0) {Window.alert("name must not be empty");event.cancel();
}}
});
form.addSubmitCompleteHandler(new SubmitCompleteHandler() {public void onSubmitComplete (SubmitCompleteEvent event) {Window.alert(event.getResults());
}});
form.addSubmitCompleteHandler(new SubmitCompleteHandler() {public void onSubmitComplete (SubmitCompleteEvent event) {Window.alert(event.getResults());
}});
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 98
Copyright ©2000-11 CRS Enterprises Ltd 98
4. Working with JSON ...Server Side
Create JSONObject and send to client
JSONObject responseObj = new JSONObject();List<JSONObject> productObjects = new LinkedList<JS ONObject>();
for (Product product : products) {JSONObject productObj = new JSONObject();productObj.put("name", product.getName());productObj.put("company", product.getCompany());productObj.put("serialNumber", product.getSerialNum ber());productObjects.add(productObj);
}responseObj.put("products", productObjects);PrintWriter writer = response.getWriter();writer.write(responseObj.toString());
JSONObject responseObj = new JSONObject();List<JSONObject> productObjects = new LinkedList<JS ONObject>();
for (Product product : products) {JSONObject productObj = new JSONObject();productObj.put("name", product.getName());productObj.put("company", product.getCompany());productObj.put("serialNumber", product.getSerialNum ber());productObjects.add(productObj);
}responseObj.put("products", productObjects);PrintWriter writer = response.getWriter();writer.write( responseObj.toString() );
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 99
Copyright ©2000-11 CRS Enterprises Ltd 99
... Working with JSONServer Side
JSONObject's can contain structure
List<JSONObject> pricesObjects = new LinkedList<JSO NObject>();for (Double price : product.getPrices()) {
JSONObject priceObj = new JSONObject();priceObj.put("price", price);pricesObjects.add(priceObj);
}
List<JSONObject> pricesObjects = new LinkedList<JSO NObject>();for (Double price : product.getPrices()) {
JSONObject priceObj = new JSONObject();priceObj.put("price", price);pricesObjects.add(priceObj);
}
{ "products":[
{ "company":"Company1", "name":"Prod1", "prices":[
{"price":123.2},{"price":123.6}],
"serialNumber":"12345"},{ "company":"Company2", "name":"Prod2", "prices":
[{"price":234.2},{"price":234.6}
],"serialNumber":"67890"
}]
}
{ "products":[
{ "company":"Company1", "name":"Prod1", "prices":[
{"price":123.2},{"price":123.6}],
"serialNumber":"12345"},{ "company":"Company2", "name":"Prod2", "prices":
[{"price":234.2},{"price":234.6}
],"serialNumber":"67890"
}]
}
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 100
Copyright ©2000-11 CRS Enterprises Ltd 100
... Working with JSONClient Side
private void parseJsonData(String json) {
JSONValue value = JSONParser.parseStrict(json);JSONObject productsObj = value.isObject();JSONArray productsArray = productsObj.get("products ").isArray();
if (productsArray != null) {for (int i=0; i<=productsArray.size()-1; i++) {
JSONObject productObj = productsArray.get(i).isObje ct();
String name = productObj.get("name").isString().str ingValue();}
}};
private void parseJsonData(String json) {
JSONValue value = JSONParser.parseStrict(json);JSONObject productsObj = value.isObject();JSONArray productsArray = productsObj.get("products ").isArray();
if (productsArray != null) {for (int i=0; i<=productsArray.size()-1; i++) {
JSONObject productObj = productsArray.get(i).isObje ct();
String name = productObj.get("name").isString().str ingValue();}
}};
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 101
Copyright ©2000-11 CRS Enterprises Ltd 101
5. Working with XMLXML is more verbose than JSON
but more common in industry
Client SideParse XMLUse DOM programming model
Server SideMany techniques for producing XML on server side
serialize to client
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 102
Copyright ©2000-11 CRS Enterprises Ltd 102
... Working with XMLServer Side
servlet can get XML file from WARbut normally would generate from database
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {try {
ServletContext ctx = config.getServletContext();InputStream is =
ctx.getResourceAsStream("/WEB-INF/resources/test.xm l"); PrintWriter writer = response.getWriter();writer.write(convertStreamToString(is));
} catch (Exception e) {e.printStackTrace();throw new ServletException(e);
}}
public void doPost(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {try {
ServletContext ctx = config.getServletContext();InputStream is =
ctx.getResourceAsStream( "/WEB-INF/resources/test.xml" ); PrintWriter writer = response.getWriter();writer.write(convertStreamToString(is));
} catch (Exception e) {e.printStackTrace();throw new ServletException(e);
}}
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 103
Copyright ©2000-11 CRS Enterprises Ltd 103
... Working with XMLClient Side Document doc = XMLParser. parse (xml);
OutputAttribute(doc, "to", "displayName", panelTo);OutputAttribute(doc, "from", "displayName", panelFr om);OutputElement(doc, "sent", panelSent);OutputElement(doc, "subject", panelSubject);OutputElement(doc, "body", panelContents);
Document doc = XMLParser. parse (xml);OutputAttribute(doc, "to", "displayName", panelTo);OutputAttribute(doc, "from", "displayName", panelFr om);OutputElement(doc, "sent", panelSent);OutputElement(doc, "subject", panelSubject);OutputElement(doc, "body", panelContents);
private void OutputAttribute(Document doc, String e lement, String attribute, Panel panel) {
Element node = (Element) doc.getElementsByTagName(e lement).item(0);String text = node.getAttribute(attribute);panel.add(new Label(text));
}
private void OutputElement(Document doc, String ele ment, Panel panel) {String text = doc.getElementsByTagName(element).ite m(0)
.getFirstChild().getNodeValue();panel.add(new Label(text));
}
private void OutputAttribute(Document doc, String e lement, String attribute, Panel panel) {
Element node = (Element) doc.getElementsByTagName(e lement).item(0);String text = node.getAttribute(attribute);panel.add(new Label(text));
}
private void OutputElement(Document doc, String ele ment, Panel panel) {String text = doc.getElementsByTagName(element).ite m(0)
.getFirstChild().getNodeValue();panel.add(new Label(text));
}
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 104
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 105
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 106
Copyright ©2000-11 CRS Enterprises Ltd 106
Security
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 107
Copyright ©2000-11 CRS Enterprises Ltd 107
Security
8
Google Web Toolkit
©2000-11 CRS Enterprises Ltd 108