HTML5 for Java Developers AJUG June 2011 v2
Transcript of HTML5 for Java Developers AJUG June 2011 v2
Burr Sutter Sr. Product Manager, JBoss
Wes Hales Sr. Engineer, JBoss June 20 2011
www.jboss.org/webinars [email protected]
Twitter: @burrsutter [email protected]
HTML5 for the Java Developer
Demo
UI Tier/Layer Innovates faster than other application tiers
Dozens of libs/frameworks always trying to outdo each other
The most dynamic & exciting place to focus on for Web-oriented Java developers
Involves some of the most challenging programming – cross-browser RIA support
It is a matter of taste – no obvious single winner (beyond Struts).
DB
UI
Web
Browser
HTML5 CSS3
JavaScript JSON
?
Stored Procedures
NoSQL Cloud-based
Services
and RDBMS
HTML HTML
+ AJAX
Struts
JSF1+Richfaces3* or
SpringMVC or
GWT
Stored Procedures
JSF2+RichFaces4* or
SpringMVC or GWT or
RESTful UI Engine
2002 2006 2012-13+
HTML + AJAX
Struts
Stored Procedures
2010 Mid-2011
HTML + AJAX
JSF2+Richfaces4* or
SpringMVC or
GWT
Stored Procedures
Mobile + Cloud
Impact?
Bus Logic
EJB2
Struts Action
Spring +
Hibernate
Spring or Seam2 +
Hibernate/JPA
EJB 3.1 or Spring +
Hibernate/JPA
JAX-RS? +
Hibernate & NoSQL
* Or IceFaces/Primefaces
JPA/Hibernate
JTA
Messaging
Jobs
Cache
Clustering
Spring
CDI*
Security
EJB
JSF2+RichFaces4
SpringMVC
RESTEasy
Adobe Flex
GWT
HTML5 via + REST & JSON + jQuery Mobile or + Sencha or + SproutCore
JBoss Focus for UI
RichFaces 3 – JSF 1 Components RichFaces 4 – JSF 2 Components
GWT at JBoss
Future Web = HTML5+REST
HTML5+CSS3+jQuery/EXT JS
? DB
JSON REST
Websocket
Cloud Service
NoSQL
SpringMVC RESTEasy
Play! Rails
jQuery + RESTEasy $(function() {
$("#listOfCustomObjects").click(function() { console.log("listOfCustomObjects clicked"); $.getJSON("collectionjson/customers", function(returnedCustomers) { console.log("returned are " + returnedCustomers); alert("returned: " + returnedCustomers); $.each(returnedCustomers, function(index, aCustomer) { console.log(aCustomer.firstName); console.log(aCustomer.lastName); console.log(aCustomer.state); console.log(aCustomer.status); }); });
});
@GET @Path("customers") @Produces("text/json") public List<Customer> getCustomers() { Customer myCustomer = new Customer(); myCustomer.setFirstName("Burr"); myCustomer.setLastName("Sutter"); myCustomer.setState("GA"); myCustomer.setStatus(1); myCustomer.setUserName("dude"); List<Customer> customers = new ArrayList<Customer>(); customers.add(myCustomer); System.out.println("getCustomers: " + customers); return customers; }
Demo: jQuery RESTEasy
What is HTML5?
* From HTML5Rocks.com
W3C – www.w3.org/TR/html5 WHAT - whatwg.org/html
Why the hype now?
• Chrome Browser Happened • WHAT Working Group – standard based on reality
www.whatwg.org • iPhone vs Adobe (no Flash) • Smartphones outship Desktops • 10s of millions of tablets sold • Fading Internet Explorer - no longer controls 80+% of the market • We are ready
http://www.w3counter.com/globalstats.php
HTML5 for Designers
• <article>, <aside>, <footer> • Hue/saturation/luminance • @font-face • Border-radius (rounded corners) • Tranforms, transitions • Canvas 2D & 3D • Video • Audio
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum id sapien at purus adipiscing tempus. Sed accumsan nisi sed leo convallis tristique. Praesent dignissim mi ac felis tempus accumsan faucibus urna porta. Nulla sit amet urna vel lectus dignissim semper. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum id sapien at purus adipiscing tempus. Sed accumsan nisi sed leo convallis tristique. Praesent dignissim mi ac felis tempus accumsan faucibus urna porta. Nulla sit amet urna vel lectus dignissim semper. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum id sapien at purus adipiscing tempus. Sed accumsan nisi sed leo convallis tristique. Praesent dignissim mi ac felis tempus accumsan faucibus urna porta. Nulla sit amet urna vel lectus dignissim semper. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum id sapien at purus adipiscing tempus. Sed accumsan nisi sed leo convallis tristique. Praesent dignissim mi ac felis tempus accumsan faucibus urna porta. Nulla sit amet urna vel lectus dignissim semper. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Phasellus in faucibus tortor. Integer nec augue
mi. In elit mauris, vulputate quis viverra ut,
hendrerit nec elit. Maecenas vel turpis id augue fringilla ornare nec vel dui. In at mi at arcu cursus venenatis.
Nulla facilisi. Sed elementum scelerisque
ipsum, nec adipiscing leo feugiat ultrices.
<footer>
<header>
<nav>
<aside>
<article>
90s: <tr><th colspan=2><td> 00s: <div id=“article1” class=“article”> 10s: Above
HTML5 Canvas Games
HTML5 Canvas
HTML5 Video
HTML5 for Programmers
• Web Sockets
• Web Storage – localStorage, Web SQL Database*, IndexedDB
• Web Workers
• Form Fields type=email, date, range, search, tel, color, number
• <meter>, <progress>
• Application Cache – offline application components
• Notifications
• Geolocation
• Device Orientation
• Server Side Events
* Web SQL Database is no longer an active specification
What about browser support today?
• Feature Detection with tools like Modernizr and other forms of browser testing
• ChromeFrame • html5boilerplate
9 4 10 5
HTML 5 Support for Desktop Browsers
Html5test.com or fmbip.com http://fmbip.com/litmus
Modernizr.com no longer displays this on the home page
* *
* *
*
*
iOS 4.3 iPad 2 iPod 4
*
*
*
*
Android
Android 2.3.3 Android 2.2.1
* *
* *
* *
Android 2.2.1 iPod 4 – iOS 4.3 VS
Html5test.com iOS 4.3 via iPad2
Android 2.2 via DroidX
HTML5 Forms
HTML5 Form Fields - html5test.com Android 2.2 via DroidX
iOS 4.3 via iPhone 3G
Application Cache
iOS 4.3 on iPhone 3G Android 2.2.1 Droid X
Websockets or SSE
Android 2.2.1 Droid X iOS 4.3 on iPhone 3G
Storage & Workers
iOS 4.3 on iPhone 3G
Android 2.2.1 Droid X
WebGL? http://learningwebgl.com/blog/?page_id=1217
http://learningwebgl.com/lessons/lesson09/index.html
WebGL Support
Android SDK 3 Emulator
Android 2.x
Tweetstream Demo
HTML5 Semantic Markup
• You app lives or dies by the UI • Using the correct tag to accurately describe markup • Focus on machine readable meta-data • <nav>,<footer>, <and others> "can be" styled for positioning or
clearfix but aren't intended to be aesthetically styled (eg. border, shadow, etc...)
Modernizr What is does...
• <html class="js canvas canvastext no-geolocation rgba hsla multiplebgs borderimage borderradius boxshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions video audio localstorage sessionstorage webworkers applicationcache fontface">
• Javascript Object: Modernizr (boolean values for each feature)
if (Modernizr.localstorage) { console.log(“localStorage is available – let’s cache”); } else { console.log(“no localStorage – retrieve from server”); }
Feature Detection Using CSS
• Creating graceful fallbacks for all browsers • Modernizr “Cascading” detection (see next slide) • Other mechanisms like HTML5 shiv - Inserting HTML5
elements before body tag in IE document.createElement(“aside”)
Feature Detection Using CSS
“Cascading” the detection: #nice {
background: url(background-one.png) top left repeat-x;
background: url(background-one.png) top left repeat-x,
url(background-two.png) bottom left repeat-x;
}!!Using Modernizr: !#nice { background: url(background-one.png) top left repeat-x; } .multiplebgs #nice { background: url(background-one.png) top left repeat-x, url(background-two.png) bottom left repeat-x; } !
Modernizr
• What is does not do....Modernizr doesn’t actually magically enable these properties for browsers that don’t support them.
• polyfill (n): a JavaScript shim that replicates the standard API for older browsers
Modernizr Modernizr.load({test:Modernizr.geolocation, yep : 'geo.js', nope: 'geo-polyfill.js' });!
The All-In-One Entirely-Not-Alphabetical No-Bullshit Guide to HTML5 Fallbacks http://bit.ly/html5shims
Modernizr + Polyfills
Modernizr + Polyfills
IE6+ Firefox 3.6+ Safari 4+ Safari for iOS 4.2+ Chrome 11.0+ Opera 11+
Capable of supporting...
ChromeFrame • No admin-rights needed (comes with MSI) • Easy redirect with... http://www.google.com/chromeframe/?redirect=http://ur.site • Enterprise Installation • Early adopters include Yahoo, Wordpress.com, and several Google properties
html5boilerplate
• An HTML5 project config tool for the front and back-end
• Front end:CSS resets, cachebusting
• Configures Modernizr, Initialzr (templates)
• Optimizes and minifies *everything*
• Back end:
• htaccess - Apacheserver or (subsystem in JBoss AS7)
• web.config – IIS
• nginx.conf & mime.types - nginxlighttpd.conf - lighttpdnode.jsapp.yaml and gae.py - Google App Engine
HTML5 Today...
• What's the best option?Modernizr + PolyfillsWell known, first to marketRedundant CSS will need to be re-written laterChromeFrame Good for the IE6 folkshtml5boilerplateNeeds more polish, but very cool conceptTried to retrofit into a Java EE app but was painful
Starting small...
• After you take the leap and start an HTML5 project:HTML5 Forms
• Web Storage /Offline Access
• Mobile Web
Feature Detection Using CSS
Specific feature added to XMLHttpRequest
var formData = new FormData(); formData.append("part_num", "123ABC"); formData.append("part_price", 7.95); formData.append("part_image", somefile) var xhr = new XMLHttpRequest(); xhr.open("POST", "http://some.url/"); xhr.send(formData); or modify an existing form...
new FormData(document.getElementById("foo"));!
Offline & Storage
What's available? • Application Cache - Quickest way to get started.
• Speeds up initial load
• Allows users to read fairly static content (.html) offline
• IndexedDB - is the replacement for WebSQL Database
• Transactional with object stores, not tables
• Used to store and index data on client side
• Asynchronous API - non-blocking, data is delivered to callback function
• WebStorage - key/value based storage (no TX)
• localStorage - maintains data across restarts – writes to local disk
• sessionStorage - related to users browsing session (think cookies)
• Web SQL Database – RDBMS in the browser
Web SQL Database
http://www.w3.org/TR/webdatabase/
Offline & Storage (Basics)
Checking the users connectivity (e.g. online or offline)if (navigator.onLine) { alert('online') } else { alert('offline'); }!
Events...
window.addEventListener("offline", function(e) { alert("offline"); }, false); window.addEventListener("online", function(e) { alert("online"); }, false);!
Offline & Storage Application Cache Define in markup:
<html manifest="example.appcache">
File Structure:
CACHE MANIFEST index.html stylesheet.css images/logo.png scripts/main.js
Advanced usage:
# Resources that require the user to be online. NETWORK: login.php /myapi http://api.twitter.com
!
http://www.html5rocks.com/en/tutorials/appcache/beginner/
Offline & Storage IndexedDB Opening the database
var demo = {}; demo.indexedDB = {}; demo.indexedDB.db = null; demo.indexedDB.open = function() { var request = indexedDB.open("todos"); request.onsuccess = function(e) { demo.indexedDB.db = e.target.result; // Do some more stuff when opened }; request.onfailure = demo.indexedDB.onerror; };
Creating an object store
var store = db.createObjectStore("todo", {keyPath: "timeStamp"});
!
http://www.html5rocks.com/en/tutorials/indexeddb/todo/
Gotchas - http://www.davidflanagan.com/2011/01/indexeddb-statu.html
Offline & Storage localStorage if (Modernizr.localstorage) { console.log("see if we have a cached copy "); var fromStorage = localStorage.getItem("customers"); var listOCustomers = JSON.parse(fromStorage); if (listOCustomers == null) { console.log("customers are null, fetch from server"); $.getJSON("collectionjson/customers", function(listOCustomers) { console.log("returned are " + listOCustomers); localStorage.setItem("customers", JSON.stringify(listOCustomers)); }); } else { // listOCustomers not null console.log("not Null - cached copy"); } } else { alert("Modernizr no HTML5 localStorage."); }
Offline & Storage Web SQL Database var shortName = 'DEMODB'; var version = '1.0'; var displayName = 'DEMO Database'; var maxSize = 100000; DEMODB = openDatabase(shortName, version, displayName, maxSize);
!
http://www.html5rocks.com/en/tutorials/webdatabase/todo/
Offline & Storage Web SQL Database function createTables(){ DEMODB.transaction( function (transaction) { transaction.executeSql( 'CREATE TABLE IF NOT EXISTS page_settings(id INTEGER NOT NULL PRIMARY KEY, fname TEXT NOT NULL,bgcolor TEXT NOT NULL, font TEXT, favcar TEXT);',
[], nullDataHandler, errorHandler); } ); prePopulate(); }
Top 5 Best Practices
When working with HTML5....
1) Use client side DBs instead of server round trips
2) Use CSS transitions instead of javascript animations (Enable hardware acceleration) 3) Boost performance with javascript 1.6 (no more "for loops") 4) Use cache manifests for live sites, not just offline apps 5) HTML5 Form attributes and input styles
Demo: Websockets, HornetQ, TagCanvas
Alternatives Websockets
• Meta-data Refresh • AJAX Polling – Javascript in the browser, polling a
particular URL for updates every N seconds • Long Polling (Comet) – two connections • GWT has something “built-in” • RichFaces 4 has a push component • Errai for extending CDI to GWT-based clients • Atmosphere
Demo: client-side web storage
Questions?
Additional Resources • Html5rocks.com • Modernizr.com • Diveintohtml5.org • www.hongkiat.com/blog/48-excellent-html5-demos/ • www.chromeexperiments.com • Html5demos.com • Html5test.com
[email protected] Twitter: @burrsutter
[email protected] Twitter: @wesleyhales
-webkit-border-radius: 10px; -khtml-border-radius: 10px; -moz-border-radius: 10px; border-radius: 10px; border: 2px #0687FF; box-shadow: inset 0px 0px 50px #777; background: #0687FF; padding: 5px; color: #fff; cursor: pointer;
Custom CSS
jQuery Mobile (out of the box)
jQuery Mobile Examples