Sei sulla pagina 1di 20

AJAX & Rich Internet Applications

Bringing Interactivity & Intuitiveness Into Web Applications

AJAX Defined

• Asynchronous Javascript and XML


– Term coined by Jesse James Garrett
– www.adaptivepath.com
• Ajax is not a new technology
– Google calls their technique: Javascript
– Also known as XMLHTTP technique Mr. Ajax
– In use since at least 1997
• A bundle of techniques
– Some are pure – XML data interchange only
– Some are not – Passing Javascript methods to client
– Some are cool – DHTML widgets
– Some are not – XML & XSLTs
– Ok..they’re all cool…
• Core techniques are centered around asynchronous
communication to the server without a page refresh

1
Traditional Web Applications…

Action
Pick An Item Review Cart
‘Add To Cart’
Validation Action Enter
Persistence Enter Data Validation
Forwarding Submit Persistence
Shipping
Enter Data
Forwarding Submit

Pages & Actions


Action
Validation
Error Page Persistence
‘Can’t Order 500’
Forwarding

Unit of work is a page Enter Billing


Enter Data
Client code concerned with validation Submit

Submits sent to actions


Actions perform work and then forward to next page
Page refresh for each submit

AJAX Changes How Web Apps are Built

Components & Events


Item List
Order Entry Component
ErrorViewer Events/Actions
Item List (DIV) (DIV)
Validation Shopping Cart
Component
AJAX

Persistence
Shopping Cart (DIV)
Event Handlers
Shipping Form (DIV) Shipping
GUI Creation
Component
Billing Form (DIV)
Billing
Component

Unit of work is a component


Three-Tier Client/Server Model
Client code has validation, flow, layout, data interchange
No submit buttons—save buttons
Only parts of pages are updated at a time

2
AJAX Enabled Master Detail Form

No screen flicker.
Individual regions or fields updated.
Client sends data to server asynchronously.
Server returns data, messages, gui, or code.

Two ways of talking to the server…


• XMLHTTPRequest object
– Allows for asynchronous GETs + POSTs to the server
– Does not show the user anything—no status messages
– Can have multiple XMLHTTPRequest active at one time
– Allows you to specify a handler method for state changes
– Handler notified when request is:
• Initialized
• Started
• In the process of being returned
• Completely finished
– Originally only available for Microsoft IE
• IFRAME
– IFRAME is a “mini-browser” window in an HTML document
– Can be hidden (0 width, 0 height)
– IFRAME can call a URL
– Javascript can read the contents of the IFRAME
– User sees messages on status bar
– Hears a click as server submits request
– Much slower than XMLHTTPRequest

3
XMLHttpRequest Object: Methods

• open(“method”, “URL”)
• open(“method”, “URL”, async, username, password)
– Assigns destination URL, method, etc.
• send(content)
– Sends request including postable string or DOM object data
• abort()
– Terminates current request
• getAllResponseHeaders()
– Returns headers (labels + values) as a string
• getResponseHeader(“header”)
– Returns value of a given header
• setRequestHeader(“label”,”value”)
– Sets Request Headers before sending

XMLHttpRequest Properties

• onreadystatechange
– Event handler that fires at each state change
– You implement your own function that handles this
• readyState – current status of request
– 0 = uninitialized
– 1 = loading
– 2 = loaded
– 3 = interactive (some data has been returned)
• This is broken in IE right now
– 4 = complete
• status
– HTTP Status returned from server: 200 = OK
• responseText
– String version of data returned from server
• responseXML
– XML DOM document of data returned
• statusText
– Status text returned from server

4
Message Flow
<script type=“text/javascript”>
Message
Validation Servlet
name=steve
Or
<name>Steve</name> ValidateName( req, res…) {
XMLHttpRequest parse request
lookup name in database
is it valid?
if so, return OK
function handleResponse() {
otherwise
…read response from server
return error message
…get a handle to the DIV
If Not OK
Replace DIV contents with msg
}

function checkName( name ) { Message


…initialize request (url, parms) status=999
…register callback function msg=Not a valid name
…call the server
}

Database
Steve Save <div
Not id=status
a Valid Name >

Client/Browser Server

Message Flow

<script type=“text/javascript”>
Validation Servlet: /validate
_ajax.send( some data ) Get parameters…do some work
Return something…
XMLHttpRequest a text message
an XML document
an HTML snippet
function doResp() { a javascript method
if _ajax.readyState == 4 and whatever you want…
_ajax.status != 200 {
div=document.getElementById(‘status’)
div.innerHTML = _ajax.responseText;

Message
Save button onchange event: status=999
_ajax = new XMLHTTPRequest(); msg=Not a valid name
_ajax.onreadystatechange = doResp;
url = ‘./validate?field=’
+this.name+‘&value=’+this.value;
_ajax.open(‘GET’, url, true )

Database
Steve Save <div
Not id=status
a Valid Name >

Client/Browser Server

5
Security Issues

• You can only hit the domain that the original web
page came from

• Because of this, the AJAX technique cannot normally


be used to access a Web Service of a 3rd party server
– You can wrap those requests through your own server
– You can allow XMLHTTPRequest to access specific sites in
your browser security settings

• IFRAME can be used to access any site if needed

Lets Look at Some Code!

• Ping Example
• 10 Sequential Pings
• Big File Example
• onchange Example
• onkeypress Example
• DropDown handling
– Auto Form Filling
• Form Handling
– Retrieving Form Data
– Form Posting via AJAX
• DIV replacement
– via text
– via XML
• Google Suggest Example

6
Wow..I didn’t
know soccer
teams did web
programming..

How It Works

• Fires roughly every keystroke


– Uses a timer to determine when to send a request to the server
– If you type at “typical” user typing speed—every keystroke
– If you type at “programmer” typing speed—every few keystrokes
• Creates a hidden DIV that is shown when you start typing
• DIV is populated with return results from server
• Text field is set to include the next word from the server list and
everything to the right of the cursor position is highlighted
– If you hit the right arrow, it assumes you want that text and
positions you at the end of the text field
• Results cached; if you backspace, server is not called again
• Has a timer adjustment to increase or slow down server calls
– Slow dialup sessions hit server fewer times
– Fast broadband hits a lot

7
JavaScript Returned

sendRPCDone( frameElement, "the k", new


Array("the killers", "the knot", "the
killers lyrics", "the keg", "the kills",
"the kinks", "the killers band", "the
kite runner", "the king and i", "the
killers hot fuss"), new Array("5,980,000
results", "5,050,000 results", "339,000
results", "1,580,000 results",
"10,800,000 results", "1,350,000
results", "876,000 results", "204,000
results", "25,100,000 results", "388,000
results"), new Array(""));

So…is this here to stay?

They said go
EJBs…then they
said WSDL…now
AJAX?

8
So why is AJAX so hot—NOW?

• Demand for richer applications is growing


– Broadband means we can—and want to—do more

• It has a name
– Think LAMP

• Recent Google applications have sparked people’s imagination


– Google gmail, Google suggests, Google Maps

• Every year for the past 3 or 4 years has been the “year of the
rich client”
– I think its time…

• People are thinking of building APPLICATIONS…not just sites

• The Tipping Point


– All of this has made rich internet apps reach its tipping point—
where adoption spreads rapidly and dramatically

Rich Internet Apps Will Be Around A Long Time

Users Like It

A LOT

9
Some people don’t like AJAX…

What’s Not to Like…

• You have to program in Javascript


– Need libraries + frameworks to make it easier
• You have to program against the browser DOM
– Differences between browser implementations
• Lots of HTTP requests to server
– Requests are smaller however
– Total bandwidth may not go up
• If you want client/server, why not use a real
client/server system?
– .NET can access Web Services on your Java boxes
– Why not Flash/Flex?
– Tons of good third-party rich client systems
• Testing
– Cross-browser quirks
– New browser versions
• No Back Button
– Is this a bad thing?

10
Things To Consider…
• AJAX requires a different way of thinking about how you build your application

• Requires thinking about interface and interaction


– No cool GUI tricks for the sake of doing cool GUI tricks
– Usability is the key—and is what you should strive for
• How do you handle state + sessions?
– The issues we had in the client/server world are back
– Decision on where to put state information gets trickier
– Can all be on the client so you can have truly stateless servers
– Requires a lot more client code for state – server already has mechanism for clustered
state synchronization
– What happens if the server or network dies?
• Navigation Issues
– Refresh button can kill your app – open your application with minimal chrome
– Back button is meaningless unless you code ‘undo’ functionality to it
– Bookmarking doesn’t work unless you manually change the URL
• Don’t assume the server is going to respond instantly
– Sending each keystroke for field validation is a pretty dumb idea actually
– Even sending each field—wait till the user is ready to send with a SUBMIT or SAVE
button

What about the Back button?

Next topic please

11
What about the Refresh button?

Next topic please

Back & Refresh Buttons

• Back Button
– Make it work as an undo?
• Refresh Button
– Save state in <body onload> method?

• Or, make it a non-problem


– Open your “application” in a window without toolbars
– Capture the F5 Key
– Capture Control-R

• You will hear people get hysterical about this


– “Browser is the user’s domain—work around it—code for it”
– If your site is a public site then this is basically valid
– If you are building an application for users to run then strict
web rules are off the table

12
AJAX will be around for a long time…

Users are demanding Rich Internet Applications


AJAX + Tools + Framework + Controls = Rich Internet Apps

• No new infrastructure needed


– Utilize existing skills
• Much richer GUI than today
– Meets most users needs for responsiveness
– Much faster response times
• No distribution hassles
• Cross-Platform Browser Support
• Reduced bandwidth utilization
• Grass roots developer interest & support
• Vendors implementing AJAX frameworks
– ThinkCAP has it now…as you will see later…
• Developer sites + open source frameworks

AJAX Patterns

• Change Browser Content with the DOM


– Return HTML or XML and change named items
• Usually DIVs or SPANs
• Remote Scripting
– Execute business functions on the server from the client
• Events & Scheduling
– Using Timers to ping server on regular basis
• Specialized Functions to perform common GUI tasks
– Populate SELECT list
– Pass target DIV to replace to the server
– Instant Validation as User Works
– SAVE instead of SUBMIT
– CANCEL instead of BACK
• DHTML Techniques
– CSS, Drag & Drop
• Server-Side Code Generation
– Return Javascript to client

13
Common Widgets

• Form Validation
• Interactive Grids
• Drilldowns TreeViews
• Auto Completion
• Application Status Area
• Progress Bars
• Dynamic Lists
• Tabs
• AJAX’ed Portlets
• Predictive Fetch

AJAX Frameworks

• Pure JavaScript Framework


– Infrastructure
• Provides basic piping & portable browser abstractions
• Content up to developer
• Typical Functionality:
– Wrapper around XMLHttpRequest
– XML manipulation & interrogation
– DOM manipulations based on responses from XMLHttpRequest
– Application Framework
• Includes basic Infrastruture functionality

• Server-Side Framework
– HTML/JavaScript Generation
• Server provides complete HTML/JS code generation and
browser server coordination
• Browser-side coding is for customization
– Remote Invocation
• JavaScript calls routed directly to server-side functions (Java
Methods) and returned back to Javascript callback handlers

14
• Pure JavaScript
– DOJO (9/04)



Prototype (2001)
Open Rico (5/05)
Qooxdoo (5/05)
Pick a
• Pure JavaScript Infrastructural


AjaxJS (5/05)
HTMLHttpRequest (2001)
Framework…



Interactive Website Framework (5/05)
LibXMLHttpRequest (6/03)
RSLite
any Framework
– Sack (5/05)
– Sarissa (2/03)
– XHConn (4/05)
• Server-Side (Multi Language)
– Cross-Platform Asynchronous Interface Toolkit (5/05)
– SAJAX (3/05)
– Javascript Object Notation (JSON) & JSON-RPC
– Javascript Remote Scripting (2000)
• Server-Side (Java)
– Echo2 (3/05)
– Direct Web Remoting (DWR) (2005)]
– ThinkCAP Minerva (04/2005)
• Server-Side (Lisp)
– CL-Ajax
• Server-Side (.NET)
– Ajax.NET (305)
• Server-Side (PHP)
– AjaxAC (4/05)

www.ajaxpatterns.org
– JPSpan
– XAJAX
• Server-Side (Ruby)
– Ruby-On-Rails (3/05)

Sites of Interest

• www.ajaxmatters.com
• www.ajaxian.com
• www.ajaxpatterns.org

• Foundational Libraries
– Prototype
• very OO foundation to manipulate XMLHTTPRequest
• Core of “Ruby on Rails” AJAX implementation
– OpenRico
• Builds on Prototype, adds some controls
• Nice “effects” library to zoom/fade/shrink GUI elements
– Sarissa
• Heavy duty XML library for XSLT
– SAJAX & XAJAX
• PHP libraries with some good ideas
• Server driven JS creation

15
Our AJAX Implementation & Experience

AJAX will change web development

AJAX represents a fundamental shift in


how web applications are built

We’ll be building 3-Tier Client/Server


applications with AJAX
• Users want enhanced, interactive functionality
• They want their data easily accessible and maintainable
• They don’t want screen flicker
• They don’t want over-the-top GUI—just functional
• Once they see an AJAX application—they want it now

16
What is needed to build real AJAX apps?

• AJAX needs tools for productive development


– Lots of moving parts needing organization
– Javascript, DHTML, Async Communications, Server Code
– Event driven coding benefits greatly from visual environment
– Need to reduce amount of Javascript to write

• AJAX needs libraries


– Javascript communication library
– Cross-platform compatibility
– AJAX data marshalling library
– Visual controls & effects libraries
– Server support & data binding libraries
– Error handling

ThinkCAP: Transactional AJAX Framework

• Problem
– Developers hand code data access
– No provisions for error handling
– No data binding mechanism
– Need to handle nested transactions

• ThinkCAP Solution
– Built to support transactional
business applications
– Data binding & form generation
– Master/detail record linkage
– Declarative transaction
boundaries on components
– Standard error handling routine
– TransactionSafe™ eliminates
database connection leaks
– Javascript generation for most
common tasks

17
ThinkCAP: 3-Tier Client/Server Event Model

• Problem
– Developers hand code
Javascript events

• ThinkCAP Solution
– Integrated & tested three-tier client/server event model
– Executes event logic on client or server
– Over 25 response methods minimize hand-crafted Javascript
– Advanced context & response management
– Drag & Drop Events
public ClientResponse zipcode_change(ClientContext con) {
ClientResponse response = new ClientResponse();
String zipCode = con.getFieldValue();
if ( !isValidZip(zipCode) ) {
response.alert(‘Zip Code is not valid.’);
response.select(‘zipcode’);
response.setFocus(‘zipcode’);
… more code …

ThinkCAP: Advanced Controls & Effects

• Problem
– Rich Internet Apps need controls
for richness. DHTML Javascript is
complex and tedious.

• ThinkCAP Solution
– Library of customizable data-
aware GUI control & effects

• Advanced Controls
– Outlook Bar
– Dynamic Tabs
– Accordion
– TreeView
– Updateable DataView
– Edit Masks
– Autocomplete Field
• Effects
– Fade in, out
– Slide up, down

18
ThinkCAP: Best of Breed Open Source

• Problem
– Integrating open source frameworks
is time consuming and expensive
– Many RAD frameworks & libraries
are completely proprietary

• ThinkCAP Solution
– ThinkCAP integrates over 20 open source libraries
– Based on Struts
• You to rapidly AJAX enable Struts applications
• Existing Struts apps run ThinkCAP w/o modification Hibernate/Castor Designer
• TagLibs for ThinkCAP components
• Struts XML/Page Flow Designer
– Visual designers for metadata
• Hibernate & Castor Designers
• Business Chart Designer (JFreeChart)
– Declarative logging through Log4J
– Apache Commons Validator Server Validation
– Prototype.js and OpenRico used for core client framework
– Integrates with Eclipse; via plug-in

ThinkCAP: Integrated Visual Workbench

• Problem
– Tedious coding of HTML and Javascript is non-productive
– High levels of expertise needed to hand-craft
– Most tools focus on low-level J2EE features vs. productivity

• ThinkCAP Visual Workbench


– Highly Productive & Intuitive
– Built for Business App Developers
– Robust Page Layout Designer
– Drag & Drop Form Designer
– Advanced DataView/Grid Designer
– Eclipse IDE Integration

19
A complete environment for web development

• Visual Design Environment


• Page Flow Designer
• Smart Data Binding
• Integrated Persistence Engines
• 3-Tier Client/Server Event Model
• Advanced Controls & Visual Effects
• Struts & Open Source Based
• Eclipse Integration
• Runs on any application server

www.clearnova.com

20

Potrebbero piacerti anche