gwt = easy ajax

76
GWT = Easy AJAX CONFOO.CA 11/3/2010

Upload: olivier-gerardin

Post on 08-May-2015

6.526 views

Category:

Technology


3 download

TRANSCRIPT

Page 1: GWT = easy AJAX

GWT = Easy AJAX

CONFOO.CA11/3 /2010

Page 2: GWT = easy AJAX

Who am I?

Olivier GérardinTechnical Director, Sfeir Benelux (groupe

Sfeir)Java / Web architect13+ years Java3 years GWT

Page 3: GWT = easy AJAX

Agenda

Little GWT showcaseWhy GWT?How does it work?Key featuresMyths & misconceptionsPointers, Conclusion, Q&A

Page 5: GWT = easy AJAX

MANDATORY AND OVERSIMPLIFIED HISTORY OF THE DYNAMIC WEB

Why GWT?

Page 6: GWT = easy AJAX

Web 0.0

Or “The Link Era” A web page is just a bunch of images and text with

links Pages are usually stored (not generated) Links take you to a new page

1. Click on link2. HTTP request is built (from static link URL) and sent3. Wait for server to reply4. Server replies with HTML page (usually from file)5. Response received blank screen6. Wait for entire page to load

Page 7: GWT = easy AJAX

Web 1.0

Or “The Form Era” In addition to images and text, a web page can contain

fields and other widgets A designated button submits the form Pages are build

1. Fill in form2. Submit3. HTTP request is built (from form parameters and field values)

and sent4. Wait for server to reply5. Server replies with HTML page (usually generated on server)6. Response received blank screen7. Wait for entire page to load

Page 8: GWT = easy AJAX

Server side processing

CGI Basic bridge to OS commands Very ineffective (1 request = 1 process)

Web server / application server PHP, JSP, ASP, perl, whatever Performance improvements

On-demand compilation Thread pooling

Page is totally reconstructed for every request

Page 9: GWT = easy AJAX

1995: here comes JavaScript

Client-side scriptingFirst usage: client-side form validation

Avoid server round-trip when invalid Instant feedback

With DOM: polymorphic client page (DHTML) Menus, animations, etc.

Cross-browser (almost)No server interaction without submit/reload

Page 10: GWT = easy AJAX

2000: XHTTPR and AJAX

MS introduces Outlook Web Access Web “clone” of desktop client (Outlook) Fetches data from server without reloading page!

How is that possible? New class: XmlHttpRequest Allows server interaction without page reload Response received asynchronously Interface updated through DOM

AJAX is born!

Page 11: GWT = easy AJAX

The first AJAX app: Outlook Web Access

Page 12: GWT = easy AJAX

JavaScript frenzy

JS becomes hype… Cool-looking, nice to use web UIsEveryone wants to do JavaScriptAny serious web site must have dynamic

content, auto-completion or other AJAX goodies

Widget sets / frameworks begin to emerge Scriptaculous, YUI, dojo, jScript, …

Anything seems possible in JavaScript JavaScript OS, AjaxSwing (WebCream), …

Page 13: GWT = easy AJAX

JavaScript hangover

Serious JavaScript hurts… Cross-browser compatibility nightmare

Fix in one, break in another JavaScript Guru required!

Developing/Debugging nightmare Weird runtime errors No static typing No refactoring

And.. Memory leaks Heavy pages Security issues

Page 14: GWT = easy AJAX

JavaScript confusion

Source: BrowserBook © Visibone

Page 15: GWT = easy AJAX

What to do?

Option 1: leave the hard work to others Build the demo with AJAX Win the contract Leave the team…

Option 2: Give up AJAX For what? Flex? Silverlight? JavaFX? Plugin required SEO unfriendly Learning curve AJAX is too cool!

Page 16: GWT = easy AJAX

Google is in the same boat

Google is a heavy producer of AJAX appsHad to come up with a solution…

Page 17: GWT = easy AJAX

GWT solves all your problems

GWT gives you AJAX without the pain of JavaScript development Takes care of cross-browser issues Allows full debugging (breakpoints, step by step,

inspecting/watching variables) Strong static typing early error detection Full refactoring options No browser plugin or mandatory IDE Short learning curve Simple RPC mechanism built in

But can communicate with any server technology

Page 18: GWT = easy AJAX

Program in Java…

GWT allows developing client-side web apps in full Java (with only a few restrictions) Leverage existing Java tools and skills Use any IDE (Eclipse, NetBeans, IntelliJ, …)

Program like a traditional graphical client (Swing, SWT, …) Widgets, containers, listeners, etc. Use OO patterns (MVC, MVP, observer, composite, etc.)

Test like any Java app Use standard Java debuggers Test with JUnit

Page 19: GWT = easy AJAX

… deploy in JavaScript

JavaScript is only generated: For deployment To test in actual web mode

GWT guarantees that the generated JavaScript app behaves exactly like the Java app And it does (most of the time)

Page 20: GWT = easy AJAX

How does it work?

Page 21: GWT = easy AJAX

4 easy pieces

1) Java-to-JavaScript compiler2) JRE emulation library3) Java libraries4) Hosted Development mode

Page 22: GWT = easy AJAX

GWT compiler

Generates JS code from Java sourcePerforms numerous optimizations

In most cases better than hand coding Can generate obfuscated (ultra-compact) code

JS plays a role similar to bytecode for compiled Java applications Shocking!

Page 23: GWT = easy AJAX

JRE Emulation library

Provides a GWT-compatible version of Java core classes Most of java.lang Most of java.util Some classes of java.io and java.sql

For convenience only! No real I/O or JDBC!

Used when running in web mode Hosted mode runs in a JVM with standard JRE

Page 24: GWT = easy AJAX

GWT Java libraries

Utility classes RPC, I18N, …

Widget set Simple widgets (Button, TextField, …)

Base building blocks In most cases map to native HTML object

Composites = widgets built from other widgets Panels = widget containers

Panels enforce a layout (vertical, horizontal, grid, …)

Page 25: GWT = easy AJAX

GWT widgets: Simple widgets

Page 26: GWT = easy AJAX

GWT widgets: Composites

Page 27: GWT = easy AJAX

GWT widgets: Panels

Page 28: GWT = easy AJAX

Development mode

Allows running GWT apps without converting them to JavaScript Code runs as Java bytecode in a standard JVM Development mode shell emulates JS runtime

Actual rendering done by real browser Performs extensive checks to make sure the code is

compilable to JavaScriptBottom line: if a GWT application performs as

expected in development mode, it will perform identically in web mode 99,9% of the time…

Page 29: GWT = easy AJAX

LUXEMBOURG INTERESTING FACTS

Cultural break

Page 30: GWT = easy AJAX

Luxembourg is very small

Fits inside a 82 x 67 km rectanglePopulation < 500k (Montréal: 1.6 m)

Page 31: GWT = easy AJAX

Luxembourg City is beautiful

Page 32: GWT = easy AJAX

Luxembourg has a lot of castles

Page 33: GWT = easy AJAX

Luxembourg Trivia

World’s only Grand-DuchyMore than 150k cross-border workers

50% of the capital city’s population during working hours

3 official languages (fr, de, lu)Highest GDP per capitaImportant financial center (funds)Home of Europe’s largest TV/radio company

(RTL group)2 hours away from Paris by TGV / international

airport

Page 34: GWT = easy AJAX

Back to GWT:Key features

Page 35: GWT = easy AJAX

Easy development

During development, you are writing and running a classic Java app Use your favorite IDE All IDE features available (code completion, code

analysis, refactoring, links, Javadoc, …) Plugins help GWT-specific tasks

launching development mode compiling refactoring creating projects, modules, RPC services, … even design GUI (GWT Designer from Instantiations)

Page 36: GWT = easy AJAX

Easy RPC implementation

RPC mechanism based on Java servletsEasy as:

1. Define service interface

int add (int x, int y);

2. Derive asynchronous interface

void add (int x, int y, AsyncCallback<Integer> callback);

3. Implement service interface

public int add (int x, int y) {return x + y;

}

Page 37: GWT = easy AJAX

Easy RPC consumption

Easy as:1. Obtain service proxy

AddServiceAsync addService = GWT.create(AddService.class);

2. Call method

addService.add(x, y, new AsyncCallback<Long>() {public void onFailure(Throwable caught) {

// handle failure}public void onSuccess(Integer result) {

// handle success}

});

Page 38: GWT = easy AJAX

Easy RPC deployment

RPC services are actually POJS (plain old Java servlets) Can be deployed without changes in any servlet

engine Integrated test server uses standard web.xml format

for declaring services

Page 39: GWT = easy AJAX

Easy JSON generation

Easy as:

JSONObject livre = new JSONObject();

livre.put("Titre", new JSONString("GWT"));livre.put("Pages", new JSONNumber(123));

JSONArray chapitres = new JSONArray();chapitres.set(0, new JSONString("Introduction"));

Page 40: GWT = easy AJAX

Easy JSON parsing

Easy as:

JSONObject livre = new JSONObject(json);

String titre = livre.get("Titre").isString().stringValue();double pages = livre.get("Pages").isNumber().doubleValue();

JSONArray chapitres = livre.isArray();String chap0 = chapitres.get(0).isString().stringValue();

Page 41: GWT = easy AJAX

Deferred binding

Appropriate code for user environment (browser, locale) is chosen at application startup time ≠ dynamic binding (implementation chosen at runtime) ≠ static binding (implementation chosen at compile time)

Code for every combination is generated at compile time Advantages:

Allows app-wide optimizations Compensates for the lack of dynamic (runtime) loading

Disadvantages: Increases compilation time

Page 42: GWT = easy AJAX

Deferred Binding (explicit)

Deferred binding can be called explicitly:

Foo foo = GWT.create(Foo.class);

Implementation is provided by either: Substitution: an existing class is designated Generation: class is generated during compilation

Page 43: GWT = easy AJAX

Easy native JavaScript integration

Implement a method directly in JavaScript:

public static native void alert(String msg) /*-{$wnd.alert(msg);

}-*/;

Call back Java methods from JavaScript Pass objects back and forth

Useful to Wrap legacy JavaScript libraries Access browser functionality not exposed by GWT

Dangerous! Easily breaks cross-browser compatibility

Page 44: GWT = easy AJAX

Easy Widget reuse

Create your own widgets: Extend existing widget

Works but not the most efficient Might expose unwanted methods from superclass

Extend Composite Recommended method

Use JSNI To wrap existing JavaScript widgets

Page 45: GWT = easy AJAX

Easy history support

AJAX app = single page “back” button catastrophe…

GWT solution: Encode app state in URL as “fragment”

E.g. http://myserver/myGwtApp#x=1;y=2

Save state:History.newItem(token);

React to state change (“back” button)History.addValueChangeHandler(…);

Page 46: GWT = easy AJAX

I18n: constant substitution

1. Define interfacepublic interface AppConstants extends Constants { String title();}

2. “Implement” interfaceAppConstants.properties: title = Hello, WorldAppConstants_fr_CA.properties: title = Salut, Monde

3. UseAppConstants appConstants = GWT.create(AppConstants.class);String title = appConstants.title();

Page 47: GWT = easy AJAX

I18n: template substitution

1. Define interfacepublic interface AppMessages extends Messages { String mailStatus(int n, String s);}

2. “Implement” interface (AppMessages.properties)mailStatus = You have {0} messages in folder {1}

3. Use:AppMessages msgs = GWT.create(AppMessages.class);String status = msgs.mailStatus(15, “Inbox”);

Page 48: GWT = easy AJAX

Easy debugging

In development mode, application runs as bytecode (just like any old Java app…)

So you can debug it just like any classic Java app: Set breakpoints Step through code Inspect variables Change variables …

Page 49: GWT = easy AJAX

Short dev cycle

Change client code: press “Reload”.. Done!

Change server code: Embedded server: press “Restart”.. Done! External server: hotswap /redeploy if needed

Page 50: GWT = easy AJAX

Easy client-server testing

Integrated application server for testing RPC services Can be disabled to use external server

JUnit integration to run client-side test cases Hosted mode or web mode Full access to RPC services GWTTestCase, GWTTestSuite for automation

Selenium for automated GUI testing

Page 51: GWT = easy AJAX

Easy scaling

All session data resides on client Similar to classic fat client

No session information on server-side Forget session affinity Add/remove servers on the fly Restart server without losing clients

Page 52: GWT = easy AJAX

“Easy” styling

Styling relies entirely on CSS Widgets have well-known style names Programmer can add custom styles

No shift from traditional HTML styling HTML/DOM build page “skeleton” Appearance tuned with CSS

Separate UI construction from styling With well thought styles, it’s possible to reskin completely

an application without changing one line of codeGWT styling has all the benefits of CSS with all

problems of CSS Be careful with brower dependencies!

Page 53: GWT = easy AJAX

Easy Google AJAX APIs

Project gwt-google-apis http://code.google.com/p/gwt-google-apis Libraries that wrap Google JavaScript APIs

Maps Gears (storage, obsoleted by HTML5) Gadgets (embedable applets) AJAX search (embedded google search) Visualization (charts) Language (translation, language detection)

Standalone libraries (do not require JavaScript libraries)

Page 54: GWT = easy AJAX

[new in 2.0] in-browser development mode

Before 2.0: hosted mode uses customized browser engine Heavily customized

Only one supported browser per platform (IE on Windows, WebKit on Mac, Mozilla on Linux)

Difficult to keep up-to-date Includes platform-specific code (SWT)

Browser and hosted application share the same process

Most plugins don’t work (including Google Gears…)

Page 55: GWT = easy AJAX

[new in 2.0] in-browser development mode

now: Hosted mode shell runs outside browser Communicates with browser using plugin through

TCP

Page 56: GWT = easy AJAX

[new in 2.0] in-browser development mode

Benefits Use any (supported) browser/version on any platform Behavior closer to web mode No interference with browser plugins No more platform-specific stuff in GWT (one jar for

all!) Network protocol cross-platform possible

Dev mode shell on machine X, slave browser on machine Y

E.g. dev on Linux, test in IE on Windows…

Page 57: GWT = easy AJAX

[new in 2.0] speed tracer

Performance analysis toolVisualize where your app spends time:

JS execution Browser rendering CSS handling (style selection/calculation) DOM handling (event processing) Resource loading

Page 58: GWT = easy AJAX

[new in 2.0] code splitting

Before: monolithic download can become very big Slow startup times

After: Programmer can insert “split points” in code Hints for the compiler to place everything not required up to

split point in separate download Compiler divides code in several “chunks”, which are loaded

on-demandBenefits:

Initial loading time reduced 50% on average with a single split point

Allows on-demand module loading (provider pattern)

Page 59: GWT = easy AJAX

[new in 2.0] declarative UI

Declarative construction of GUI using XML grammar

Allows automatic binding with Java code (through annotations) Automatically assign references to dynamically created

widgets to designated Java fields (@UiField) Automatically attach methods as event handlers

(@UiHandler)Benefits:

Clearly separate: Static UI construction (XML) Dynamic UI behavior (Java)

Page 60: GWT = easy AJAX

[new in 2.0] resource bundle

Download multiple heterogeneous resources from server in a single request Images (already possible in pre-2.0) CSS Text Any binary resource

Benefits: Fewer round trips to the server Less overhead More responsive interface

Page 61: GWT = easy AJAX

[new in 2.0] and also…

Compiler optimizations Mostly generated JS size

Draft compile mode Faster builds Not for deployment!

Layout panels Predictable, consistent layout Constraint based system built on top of CSS Plays nice with custom CSS styles

HtmlUnit No native code / browser required

Page 62: GWT = easy AJAX

Myths & misconceptions

Page 63: GWT = easy AJAX

Myth: GWT is a JS library/framework/widget set

GWT is not for JavaScript developersProvides only Java classes

Page 64: GWT = easy AJAX

Myth: GWT is a framework

GWT is a toolkit (set of tools)Frameworks may be built on top of it

Page 65: GWT = easy AJAX

Myth: GWT is applets

A GWT application is 100% JavaScriptNo runtime/pluginNo JRE required

Page 66: GWT = easy AJAX

Myth: GWT is only for Java programmers

Yes, GWT uses Java as programming language…

BUT you can also see it this way:

GWT lets you write/debug/test/refactor AJAX apps with state-of-the-art IDEs and tools using a statically-typed object-oriented language

GWT makes it worth learning Java!

Page 67: GWT = easy AJAX

Myth: GWT generates poorly performing JS

The GWT compiler generates highly optimized and compact code

Hand written JavaScript might be marginally faster in some cases, but it’s not worth the trouble

Page 68: GWT = easy AJAX

Myth: GWT only works with a Java backend

GWT includes a simple and efficient RPC mechanism that relies on Java servlets

BUT it plays nice with any server-side technology that can handle HTTP requests (even PHP) Includes XML encoding/decoding library Includes JSON encoding/decoding library

Page 69: GWT = easy AJAX

Myth: GWT has poor UI components

Yes, GWT’s builtin widgets are minimalistic…

BUT GWT’s point is not to provide a complete and beautiful widget set

GWT provides the basis for rich and good-looking components

Create your own or use 3rd party See Ext-GWT, SmartGWT

Page 70: GWT = easy AJAX

Myth: GWT apps have long startup times

Not longer than any JavaScript appObfuscation reduces sizeDeferred binding loads just the necessary

code for the platform/languageGWT 2.0’s code splitting can split code in

several chunks Smaller initial download On-demand downloading

Page 71: GWT = easy AJAX

Myth: GWT doesn’t integrate with existing sites

GWT was designed from the beginning with the goal to integrate well into existing sites

GWT can build the UI from a blank HTML page or alter existing elements

Very easy to add GWT to an existing page Only a few lines of HTML to load the module Can “hook up” to any DOM element (through its ID)

Page 72: GWT = easy AJAX

Myth: GWT has poor skinning possibilities

GWT uses CSS for stylingCan reskin a whole application without

changing a line of code (done that!)Can split work between developer (behavior)

and designer (appearance)Caution: CSS can introduce browser

dependencies

Page 73: GWT = easy AJAX

Conclusion

Is GWT the future of web development?

GWT has passed reality checkGive it a try!

GWT = easy AJAX now !

=

Page 74: GWT = easy AJAX

Pointers

GWT home (downloads, docs, FAQs, guides, etc.) http://code.google.com/toolkit

Google groups “GWT” group http://groups.google.com/group/Google-Web-Toolkit

onGWT: fresh news about GWT http://www.ongwt.com

LinkedIn “GWT Users” group http://www.linkedin.com/groups?gid=129889

Page 75: GWT = easy AJAX

Shameless self-promotion