Mais conteúdo relacionado Semelhante a Construindo aplicações com HTML5, WebSockets, e Java EE 7 (20) Mais de Bruno Borges (20) Construindo aplicações com HTML5, WebSockets, e Java EE 72. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.3
• Java Evangelist
• Orale Product Manager
• Entusiasta JavaFX e IoT
• Onde me encontrar
• @brunoborges
• plus.google.com/+BrunoBorges
Bruno Borges
3. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.4
Ascenção do Javascript
• O debate cliente ‘leve’ vs cliente ‘pesado’ é antigo...
• Frameworks web server-side mandaram por um tempo (Struts, Spring
MVC, JSF)
• Ajax foi uma mudança suave para o client-side (GWT, Vaadin)
• Rich clients estão voltando voltaram, graças ao Javascript/HTML5
• Motores Javascript melhoraram muito (V8, SpiderMonkey, Nashorn)
• Melhores ferramentas (jQuery, MV* frameworks, Chrome, Firefox, JavaFX)
• Melhores padrões (CSS3, HTML5, WebSockets, Web Components)
Clientes ricos HTML5
4. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.5
Arquitetura Rich Client
• Similar a arquiteturas cliente/servidor
• Cliente responsável pela UI, input, validacao, lógica e estado
• Server responsável pela lógica de negócio, modelo de domínio, persistência
• Web/HTTP é a cola que conecta client e server
• Protocolos de comunicacao comuns
• REST na maioria dos casos
• WebSocket quando precisa de comunicacao full-duplex
• Ferramentas Javascript suportam REST muito bem, mas ainda não WebSocket
• O formato comum (talvez ideal?) de troca de dados é JSON
• Java EE é uma ótima plataforma server-side para esta arquitetura
5. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.6
Java EE + Javascript
Plataforma server-side para suportar apps ricas HTML5/Javascript
Servlet
EJB 3 CDI
BeanValidation
JavaScript/HTML5
JAX-RS WebSockets JSON-P JAXB
JPA JMS JTA JCA
6. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.7
JAX-RS
• API de desenvolvimento REST para Java
• Servidor e Client
• Orientada a Annotations, declarativa
• @Path, @GET, @POST, @PUT, @DELETE, @PathParam, @QueryPara
m, @Produces, @Consumes
• Plugável e extensível
• Providers, filters, interceptors
7. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.8
JAX-RS
@Path("/atm/{cardId}")
public class AtmService {
@GET
@Path("/balance")
@Produces("text/plain")
public String balance(
@PathParam("cardId") String card,
@QueryParam("pin") String pin) {
return Double.toString(getBalance(card, pin));
}
Exemplo 1
8. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.9
JAX-RS
@POST
@Path("/withdrawal")
@Consumes("text/plain")
@Produces("application/json")
public Money withdraw(
@PathParam("card") String card,
@QueryParam("pin") String pin,
String amount) {
return getMoney(card, pin, amount);
}
}
Exemplo 2
9. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.10
Java API for WebSockets
JSR 356
10. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.11
Java API for WebSockets
• Protocolo HTTP é half-duplex
• Gambiarras
• Polling
• Long polling
• Streaming
• WebSocket resolve o problema de uma vez por todas
• Full-duplex
JSR 356
11. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.12
Java API for WebSockets
• API declarativa de alto nivel para WebSockets
• Client e server-side
• Pequena e simples, mas completa
• @ServerEndpoint, @OnOpen, @OnClose, @OnMessage, @OnError, Ses
sion, Remote
• Plugável e extensível
• Encoders, decoders, sub-protocols
12. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.13
Java API for WebSockets
@ServerEndpoint("/chat")
public class ChatBean {
Set<Session> peers = Collections.synchronizedSet(…);
@OnOpen
public void onOpen(Session peer) {
peers.add(peer);
}
@OnClose
public void onClose(Session peer) {
peers.remove(peer);
}
Exemplo 1
13. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.14
Java API for WebSockets
@OnMessage
public void message(String message, Session client) {
peers.forEach(
p -> p.getRemote().sendObject(message)
);
}
14. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.15
Javascript Movers and Shakers
15. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.16
Projeto Avatar
• Javascript framework da Oracle
• Javascript no client e no server-side
• Nashorn/JDK8
• Utiliza algumas capacidades do Java EE
• Roda no GlassFish, e em breve no WebLogic também
• Suporte já integrado para REST, WebSocket, Server-Sent Events
(SSE)
• Suporte a PhoneGap
• Versão 1.0 já disponível. Bom momento para participar!
avatar.java.net
16. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.17
Projetos no NetBeans
• Twitter Bootstrap
• HTML5 Boilerplate
• Initializr
• AngularJS
• Mobile Boilerplate
17. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.18
Demo
•github.com/brunoborges/javaee-javascript
18. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.19
Conclusão
• Cientes JavaScript/HTML5 conquistando desenvolvedores
• Comunicacao entre cliente e servidor em JSON via REST ou WebSocket
• Java EE funciona muito bem como um backend para clientes ricos
Javascript, especialmente com JAX-RS e a Java API para WebSockets, e
JSON-P
• JavaScript framework da Oracle – Projeto Avatar
• Você opde usar o código de demonstracão para comecar a explorar estas
idéias
• E o mais importante, divirta-se programando! :-)
19. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.20
• glassfish.org
• Java EE 7
• Suporte a JDK 8
• Projeto Avatar
GlassFish Nightly Builds
GlassFish 4.0.1
20. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.21
Para saber mais
• Java EE Tutorials
• http://docs.oracle.com/javaee/7/tutorial/doc/home.htm
• Outras páginas para iniciar os estudos
• http://docs.oracle.com/javaee/7/firstcup/doc/home.htm
• https://glassfish.java.net/hol/
• https://java.net/projects/cargotracker/
• Java EE 7 Transparent Expert Groups
• http://javaee-spec.java.net
• The Aquarium (blog Java EE da Oracle)
• http://blogs.oracle.com/theaquarium
21. Copyright © 2014, Oracle and/or its affiliates. All rights reserved.23
The preceding is intended to outline our general product direction. It is intended
for information purposes only, and may not be incorporated into any contract.
It is not a commitment to deliver any material, code, or functionality, and should
not be relied upon in making purchasing decisions. The
development, release, and timing of any features or functionality described for
Oracle’s products remains at the sole discretion of Oracle.
Notas do Editor Richer clients clearly better at some thingsHighly dynamic, interactive interfacesComplex, feature-rich UIs“Single page applications” (“Applets” )But perhaps not a panaceaHeavily form/workflow driven applicationsServer-side rendering still a better bet for performance/reliability?JavaScript/HTML development is not without it’s pains…Server-side frameworks are a strong incumbentCo-existence in the short and long term?Islands of rich client functionality within server-centric UIs?Different strokes for different folks?