The document discusses using Java with HTML5 and related technologies like CSS3 and WebSockets. It provides an overview of HTML5 features like Canvas, SVG, CSS3 animations, and WebSockets. It describes how these features can be used to build interactive client-side applications and how Java servers can integrate with HTML5 apps by saving/retrieving application state and graphics from the client. Java servers can generate graphics like SVG dynamically based on data from HTML5 clients.
1. Using Java with
HTML5 and CSS3
(+ the whole HTML5 world:WebSockets, SVG, etc...)
Helder da Rocha
Independent Java & Web professional
Argo Navis Informatica Ltda. São Paulo, Brazil
helder@argonavis.com.br
2. Agenda
• A short introduction to some cool HTML5
features
• Some ideas about how to explore the
power of HTML5 in Java Web apps
4. Java & HTML: old friends
• 1995: Applets running inside HotJava & Netscape
browsers
• Client-side Java
• First attempt at rich interactive interfaces
• Before applets there was no such thing as
animation and interactivity on the Web
• Scripting and Netscape extensions allowed
Java-HTML communication
5. Today
• Proprietary solutions like Flash became de
facto standards for interactive client-side apps
• Java became popular for server-side apps
• Many tasks that would fit better on the client-
side are still done on the server-side because
of inconsistent browser support
6. HTML5
• Still a versioned spec under W3C, but a versionless
dynamic spec under WHAT-WG (Web Hypertext
Application Technology Working Group)
• Has among its goals to simplify HTML code and
drastically reduce the need for scripting and plugins
• Deals not only with graphical aspects and structure, but
also with networking, multithreading, storage, etc. (which
are no longer part of the official spec)
7. HTML5
is not just HTML
• The “HTML5 solution” includes
• CSS, JavaScript, audio & video, vector graphics
• But also Web sockets, geolocation, offline
cache,Web workers, client-side database, local
storage, etc.
• More than just graphical technologies
8. JSF support?
• There is not yet any official support for
HTML5 from HTML-generating frameworks
such as JSF
• HTML5 support is expected for JSF 2.2
(Java EE 7)
• But any server-side Java apps can use data
sent by HTML5 client-side apps
10. HTML5 Canvas
• API-based vector graphics
1. Place the <canvas> element somewhere (or create it
via scripting)
<canvas id=”mycanvas” width=”200″ height=”200″/>
2. Change its style if you wish
<style> canvas {border: solid black 1px} </style>
3. Get the 2D context
var acanvas = document.getElementById("mycanvas");
var ctx = acanvas.getContext("2d");
4. Use the API to paint your canvas
ctx.fillStyle = "rgb(255,0,0)”;
ctx.fillRect(50, 50, 100, 100);
12. Saving and retrieving
graphics
• Server-side applications can be used to save
the state of HTML5 graphics
• Serializing Canvas or SVG to the server
• Saving parameters that were changed by
the user
• Saved state may be recovered later and be
used to restore page
• Ex: collaborative images, signatures, etc.
13. Saving the state of the canvas
• You can use a Java server-side app to save
the state of a canvas drawn by the client
• Canvas can be converter to image via
API methods (toDataUrl())
Canvas
Servlet
14. CSS3 transforms
• 2D and 3D transforms on any element:
scale, translate, rotate, etc.
• Can be combined with animations and
transitions
• Sophisticated effects can be obtained with
no scripting at all
15. CSS3 animations
• Declarative transitions, 3D animations and
effects like shadows, reflections, etc.
• Reduces the need for scripting
#frente {
position:absolute; top: 0px; left: 0px;
-webkit-transform: translateZ(10px) scaleZ(1.2) scale(0.5);
-webkit-transform-style: preserve-3d;
}
#verso {
position:absolute; top: 0px; left: 0px;
-webkit-transform: translateZ(-10px) scaleZ(1.2) scale(0.5);
-webkit-transform-style: preserve-3d;
}
#cena {
-webkit-animation: flip 8s infinite linear;
-webkit-transform-style: preserve-3d;
}
@-webkit-keyframes flip {
from { -webkit-transform: rotateY(0deg);}
to {-webkit-transform: rotateY(-360deg);}
}
16. SVG - ScalableVector Graphics
• W3C XML standard initially based on Microsoft
VML and Adobe PostScript
• Initially supported by Adobe and Microsoft
• Can be embedded in HTML or linked via the
<img> element
<?xml
version="1.0"
encoding="UTF-‐8"?>
<svg
xmlns="http://www.w3.org/2000/svg"
width="100%"
height="100%">
<circle
r="50"
cx="100"
cy="100"
fill="green"/>
<circle
r="50"
cx="125"
cy="125"
fill="green"
fill-‐
opacity="0.5"/>
<circle
r="50"
cx="150"
cy="150"
fill="green"
fill-‐
opacity="0.2"/>
</svg>
17. Saving SVG
• It is not as easy as saving Canvas, since it
requires serializing by third-party client-side
XML processors which are browser-
dependent (need to save the DOM tree)
• But you can easily collect data from the client
side and generate SVG on the server side
• Frameworks like Apache Batik can also
convert SVG to images
18. SVG generation
• Since SVG is XML, it can be generated on
the server-side using XML authoring APIs,
• Can also be generated a a template by
vector software (like Illustrator) and later
modified (inserting DOM nodes, removing,
reordering, etc.)
19. Generating SVG through
XSLT and Java
SVG
template
XSLT
Java
component
javax.xml
APIs
SVG for
embedding
Parameters
PNG,
PDF
21. Other features
• Web database
• Local storage
• Web workers
• Web sockets
• Geolocation
22. Web storage
• Safer local and session storage objects
• Two objects which accept any properties:
localStorage and sessionStorage
• Ex: localStorage.field = “Hi!”;
• localStorage is not shared among tabs
or windows.
• You can’t insert data into them directly
from the server (it has to be via scripting)
23. Client-side database
var db = openDatabase('mydb', '1.0',
'hellodb', 2 * 1024 * 1024);
db.transaction(
function (tx) {
tx.executeSql(
'CREATE TABLE IF NOT EXISTS
mytable(id unique, name)');
tx.executeSql(
'INSERT INTO mytable(id, name)
VALUES (1, ”Jack")');
}
);
• For applications which require a lot of
structured offline data (ex: animations)
24. Web workers
• Threading API for JavaScript
• Create thread code in a JS file, and attach it to a
Worker object
var worker = new Worker(“worker.js”);
• Attach a listener function
worker.onmessage = function(evt) {
alert(evt.data);
};
• Send an asynchronous message
worker.postMessage(“data”);
25. Geolocation
• Uses the navigator object to store
geolocation coordinates
position.coords.latitude & longitude
• Once collected, you can send them
anywhere
• Ex: if you send them to a Java server-side
application, they can be used to generate
an SVG map, for example.
26. Web Sockets
• A completely new protocol that uses HTTP
as a bootstrap
• Also has an IETF spec: RFC 6455
• Allows real-time bidirectional
communication (like Comet)
• Requires support from both the server-side
and the client-side
27. Protocol
• Starts with an HTTP handshake via headers
• After communication is established, data packets can be
exchanged
• Packet format is defined by the protocol spec
GET /mychat HTTP/1.1
Host: server.example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x3JJHMbDL1EzLkh9GBhXDw==
Sec-WebSocket-Protocol: chat
Sec-WebSocket-Version: 13
Origin: http://example.com
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: HSmrc0sMlYUkAGmm5OPpG2HaGWk=
Sec-WebSocket-Protocol: chat
29. Client
JavaScript
API
• How
to
use
it
(client-‐side)
var
ws
=
new
WebSocket("ws://localhost:8080/myapp");
ws.onopen
=
funcLon(event)
{
alert("Opened
connecLon!");
}
ws.onmessage
=
funcLon(event)
{
alert("Message:
"
+
event.data);
}
ws.onclose
=
funcLon(event)
{
alert("Closed
connecLon!");
}
ws.send("Hello
World!");
send()
method
Event
handlers
WebSocket
object
30. What about the server side?
• Still no standard. But there should be one
soon (JSR 356 + Java EE 7)
• You can write your own WebSocket server,
of course (study the protocol and handle it
with a java.net.ServerSocket or
javax.servlet implementation)
• You can use Glassfish+Grizzly, Jetty, JBoss,
or some other proprietary solution
31. Battleship
Client-side
var ws;
function initWS() {
ws = new WebSocket("ws://localhost:8080/../WSBattleship");
ws.onmessage = function(event) {
if (gameStarted) {
var msg = event.data.split(":");
if (msg[0] != playerId) {
hitOrMiss(msg[1], msg[2]);
}
}
alert(event.data);
}
}
function hitOrMiss(coords, event) {
if (event == 0) {
markMiss(coords);
} else {
markHit(coords);
}
}
function shoot(ship) {
if (gameStarted && !gameFinished) {
ws.send(playerId + ":" + shotPosition);
}
}
function addShip(ship) {
if (!gameStarted && totalShips < maxShips) {
ships[totalShips++] = ship.id;
ship.style.fill = "red";
}
if (totalShips == maxShips) {
ready = true;
ws.send(playerId); // ready signal!
}
}
32. WebSockets
app
using
Grizzly
• Write the component & socket
• Register the component using a servlet
public class MyServlet extends HttpServlet {
public void init(ServletConfig config) throws ServletException {
WebSocketEngine.getEngine().register(new BattleShipComponent());
}
}
public class BattleShipComponent extends WebSocketApplication {
public WebSocket createSocket(WebSocketListener... listeners) {
return new BattleShipSocket(listeners);
}
public void onMessage(WebSocket socket, String data) {
String gameData = data.split(":");
...
}
} public class BattleShipSocket extends BaseServerWebSocket {
public BattleShipSocket(WebSocketListener... listeners) {
super(listeners);
}
}
34. Summary
• Although there is no official support for HTML5 in Java
Web technologies such as JSF (expected for Java EE 7), Java
server-side apps can enhance client-side HTML5 apps
• Information collected by HTML5 can be used as parameters
for server-side processing, where many Java APIs can be used
• SVG can be easily generated on the server-side and embedded
into HTML pages
• Canvas (and SVG) can be serialized and stored on the server
• WebSocket applications require server-side support.
Currently there are several Java-based proprietary
solutions. JSR 356 aims to standardize this.
• Of course, browser support is still the main concern