AJAX & Google Web Toolkit

unalaskaweepingInternet and Web Development

Jul 19, 2012 (4 years and 11 months ago)

249 views

AJAX & Google Web Toolkit
What, Why, and How
Sascha Häberling
Fulda University of Applied Sciences
2
Agenda

Introduction

Motivation: Why we love Web Apps

Traditional HTML Applications - “Web 1.0”

What AJAX can do better and how

The pain of AJAX: JavaScript

How the GWT solves this

XML11: Another approach
3
Introduction
Sascha Häberling

Applied Computer Science at FH Fulda 2001-2005

San Francisco State University 2005

Master of Science in eBusiness at HS Fulda since 2005

XML11 Core Developer since 2005

Internship at Google in Atlanta in 2006
4
Motivation
: Why we love Web Apps ...
No installation / Always re-install
Every application is just a URL away
No such thing as DLL Hell
Secure… the mantra we teach our parents
Installing things = mostly unsafe
Surfing the web = mostly safe
Simple
Pages have a simple, friendly look and feel
Not much to learn: back, forward, buttons, links, URLs
5
Agenda

Introduction

Motivation: Why we love Web Apps

Traditional HTML Applications - “Web 1.0”

What AJAX can do better and how

The pain of AJAX: JavaScript

How the GWT solves this

XML11: Another approach
6
Developing Traditional HTML Applications
Advantage: The architecture is simple
UI is always stateless HTML
Server handles everything
Browsers are HTML dumb terminals
Browser
Server
User action
New HTML page
01100110
01111001
01101011
011001101101
111110010100
011010111101
110011010110
7
Developing Traditional HTML Applications
Disadvantage: The architecture is
too
simple
UI is always stateless HTML
Cannot change interactively within the client
The concept of “a session” is actually complex in this model
Server handles everything
Big strain on servers
Affinity between clients and servers reduces scalability and failover
Browsers are HTML dumb terminals
Apps are sluggish and bandwidth-hungry

Transfer complete HTML pages even on small changes
Severely limits app functionality
For example, impossible to auto-save drafts in web-based email
8
Conclusion so far:
We want to bring applications to the web
BUT
Traditional web technology doesn't work
=
We need a
new
technology?
9
Agenda

Introduction

Motivation: Why we love Web Apps

Traditional HTML Applications - “Web 1.0”

What AJAX can do better and how

The pain of AJAX: JavaScript

How the GWT solves this

XML11: Another approach
10
Traditional App Cycle
11
AJAX App Cycle
12
Traditional vs. AJAX: Response Time
AJAX: Asynchronous JavaScript and XML
Browser
Web Server
Browser
Web Server
JavaScript
Time
Event
HTTP Request
HTTP Response
User activity
by Jesse James Garrett
13
Traditional vs. AJAX: Bandwidth
0
10000
20000
30000
40000
50000
60000
70000
80000
90000
Page 1
Page 2
Page 3
Page 4
Page 5
Page 6
Page 7
By
tes Transferred
Traditional HTML
GWT First Run
GWT Other Runs
Demo
DynaTable
15
Events & DOM Manipulations
Input from user to AJAX using events:

No URL links

No direct POSTs or GETs
<div id="ID_1" style="position: absolute; top: 10px;left: 5px"

onMouseOver
= "..."
onKeyPressed
= "...">

<img src="..."/>
</div>
<html>

<head>

<title></title>

</head>

<body>

<div>

<img ... />

</div>

</body>
</html>
Output to user using DOM Manipulations
Demo
DOM manipulations
using JavaScript
17
Conclusion so far:
We want to bring applications to the web
BUT
Traditional web technology doesn't work
BUT
AJAX can help to achieve our goals
=
Let's start using AJAX!?
18
Agenda

Introduction

Motivation: Why we love Web Apps

Traditional HTML Applications - “Web 1.0”

What AJAX can do better and how

The pain of AJAX: JavaScript

How the GWT solves this

XML11: Another approach
19
The AJAX Slippery Slope
Product management and engineering decide to add script…
I begin experimenting with JavaScript
Cool! The boss loves it. I’m even having a bit of fun writing it.
All is well in the world now…maybe I’ll get a bonus!
The salespeople love it
We’re an AJAX shop?
Oh yeah, we can’t just support Internet Explorer
Wait, this is hard
I hate browsers with all my heart
I quit – find another sucker to maintain this big ball of mud
20
Hello? Software Engineering?
Hey, what happened to all that software engineering
stuff we figured out in the last few decades?
Static type checking?
Design patterns?
Unit testing?
Code reuse?
IDEs?!?!
Debugging?!?!
21
Have Your Cake XOR Eat It?
Why aren't there great JavaScript tools already?
Aren't they just around the corner?
"Powerful" Languages
with Dynamic Typing
"Weaker" Languages
with Static Typing
JavaScript
Java
22
What no static type checking means
Imagine this gem on line 5912 of your script
x.
compnent
= document.getElementById("x");
// a "spelling bug" that will bite much later
There’s a reason static type checking was invented!
23
Don't Hold Your Breath For Code Completion
Imagine you want to write a JavaScript IDE…
Hard (impossible, actually) in the general case
But I would never write code like that!
Yes, but would that new guy on your team write code like that?
And if he did, when would you find out?
// JavaScript
function enhanceString() {

String.prototype.usefulMethod = myUsefulMethod;
}
var str = window.prompt("Method name?");
eval(str)();
str.
usefulMethod()
; // hmmmm...
24
JavaScript dynamic typing: powerful, flexible, and scary
This seems innocent enough…
function createEmployee(name, isVolunteer) {

var emp = new Employee();

emp.name = name;

if (!isVolunteer) emp.salary = STARTING_SALARY;

return emp;
}
Elsewhere in your code base…
var jim = createEmployee("Jim Bloch", true);
showNewUser(jim.name);
if (jim.salary > 100000)

window.alert("Jim is paid well!");
Any guesses?
New Kinds of Bugs!
25
JavaScript dynamic typing: powerful, flexible, and scary
This seems innocent enough…
function createEmployee(name, isVolunteer) {

var emp = new Employee();

emp.name = name;

if (!isVolunteer) emp.salary = STARTING_SALARY;

return emp;
}
Elsewhere in your code base…
var jim = createEmployee("Jim Bloch", true);
showNewUser(jim.name);
if (jim.salary > 100000)

window.alert("Jim is paid well!");
That's
why IDEs can't do code real completion for JS
New Kinds of Bugs!
Runtime error!
jim.salary

does not exist
26
Cross-Browser “Fun”
Mouse Click
Event Bubbling (IE)
Mouse Click
Event Capturing (Mozilla)
Imagine some nested div element
Only one example of many
27
Conclusion so far:
We want to bring applications to the web
BUT
Traditional web technology doesn't work
BUT
AJAX can help to achieve our goals
BUT
JavaScript is hard to learn and maintain
=
It's either painful or not gonna happen?
28
Agenda

Introduction

Motivation: Why we love Web Apps

Traditional HTML Applications - “Web 1.0”

What AJAX can do better and how

The pain of AJAX: JavaScript

How the GWT solves this

XML11: Another approach
29
What is Google Web Toolkit (GWT)?
What is GWT?
A set of tools for building AJAX apps in the Java language
What makes GWT interesting?
Write, run, test, and debug
everything
in Java, both client-side UI
code and server-side business logic
Isn’t that called an applet?
No JVM required
GWT converts your working Java source into pure JavaScript
GWT is a compiler?
GWT’s Java-to-JavaScript compiler is a big part of it, but there’s
really a lot more to the story than that…
30
Code Sample – Hello, AJAX
public class HelloAjax implements EntryPoint {

public void onModuleLoad() {

Button b = new Button("Click me", new ClickListener() {

public void onClick(Widget sender) {

Window.alert("Hello, AJAX");

}

});

RootPanel.get().add(b);

}
}
Demo
Hello, AJAX
32
To JavaScript compiled code
// from class Hello
function _$onModuleLoad(_this$static){

var _b = _$Button(new _Button(), 'Click me',

_$Hello$1(new _Hello$1(), _this$static));

_$add(_get(), _b);
}
// from anonymous ClickListener class
function _onClick(_sender){

_alert('Hello, AJAX');
}
33
Obfuscated JS Code
function ne(oe){var pe=qe(new re(),'Click
me',se(new te(),oe));ue(ve(),pe);}
function xe(ye){ze('Hello, AJAX');}
34
GWT Architecture
GWT
Tools
Client
Server
Java to JavaScript

Compiler
Hosted Mode
Widget Framework
JRE Emulation
Browser Abstraction
Serialization
Framework
Deferred Binding
Java Servlet
Other Servers
35
Code Reuse and Quality
Ripe for building frameworks
Share AJAX libraries as JARs
Share RPC interfaces with a Java vocabulary
Mature OO patterns in your AJAX designs
JUnit for testing AJAX code
Reclaim your inner software engineer
36
Use Case: Widgets and Layout
Build cross-browser widgets in straight Java
Constraint-based layout with panels
Create new widgets from existing ones
public class InboxWidget extends Composite {
private EmailList list = new EmailList();
private EmailPreview pvw = new EmailPreview();
// combine them together in a simple panel to
// create a new, reusable composite
widget
}
Styled with CSS
Demo
Widgets and Layout
Mail
38
Many solutions out there (JSON, XML-RPC, …)
GWT provides you a Java RPC interface
interface SpellService extends RemoteService {
String[] suggest(String word)
}
Client and server can speak the same language
Inner classes make it easy to deal with asynchronous RPCs
Use Case: Remote Procedure Calls
39
Use Case: Remote Procedure Calls
SpellServiceAsync spell = GWT.create(
SpellService
.class);
spell.suggest(
"compnent"
, new
AsyncCallback
() {

void onSuccess(Object result) {

String[] alts =
(String[])result
;

if (alts.length > 0)

showSuggestionsInGui(alts);

}

void onFailure(Throwable e) {

reportProblemInGui(e);

}
});
40
Have Your Cake AND Eat It!
"Powerful" Languages
Dynamic Typing
"Weaker" Languages
Static Typing
JavaScript Native Interface (JSNI)
Include JavaScript directly in your Java source!
And you can still debug
Write no-compromise JS and make it reusable
Expose existing JavaScript libraries into Java projects
JSNI
41
Tough decision not to support reflection and class loading
And I'm so glad! Three words: Whole program optimization
For example, type tightening to eliminate polymorphism
Shape s = new Circle(2); // radius of 2
double a = s.getArea();
becomes
Circle
s = new Circle(2); // radius of 2
double a =
(s.radius * s.radius * Math.PI)
;
Inlining lets us discard the entire
getArea()
method!
Imagine those sorts of optimizations across your entire app
In JavaScript, reducing size and increasing speed are
complementary goals, which makes optimizations
really
fun
Optimize Like Crazy
42
Deferred Binding
Replace classes at compile time
DOM dom = (DOM)GWT.create(DOM.class);
dom.doSomethingPlatformSpecific();
At runtime,
dom
actually refers to the most appropriate
subclass
DOM
Interface
InternetExplorer
Class
Mozilla
Class
Application code
Deferred binding compiles in
the correct subclass based on
selection rules.
Safari
Class
43
Compilation: Optimized Per Client
Single Java
Code Base
Download exactly what you
need in a single
can't-go-wrong chunk
Then cache it on the client
until the sun explodes

Firefox 1.0.x
Your Code
en_US
1D04ADDA.cache.html
Safari 2.0.x
Your Code
fr_FR

7EFE4D24.cache.html
IE 6
Your Code
en_UK

15F361BB.cache.html
Opera 9
Your Code
fr_CA

D415D917.cache.html
44
Startup Time
Absolutely crucial
Should be measured in milliseconds
If startup time isn't acceptable, nothing else matters
Very hard to do well
Loading code with synchronous XHR is out of the question
GZip your script ahead of time? Good idea, but…
Some versions of IE6 fail on gzipped .js files
Script versioning vs. cacheability
GWT gives you leverage
Compiled output includes only what a particular user needs
Output is JS wrapped in HTML, which is safely gzip'able
Loads code in an <iframe> in parallel with the page
Scripts are named uniquely and are perfectly cacheable
45
Agenda

Introduction

Motivation: Why we love Web Apps

Traditional HTML Applications - “Web 1.0”

What AJAX can do better and how

The pain of AJAX: JavaScript

How the GWT solves this

XML11: A different approach
Different Approach: XML11
Comparison XML11 & GWT
Q&A
49
Did I Mention Tools?
Instantiations GWT Designer
WYSIWYG Layout
50
Did I Mention Tools?
Instantiations GWT Designer
Internationalization