java ee 7_ building web applications with websocket, javascript and html5
DESCRIPTION
java ee7 web socketsTRANSCRIPT
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 1/20
Purpose
ThistutorialshowsyouhowtocreateanapplicationthatusestheWebSocketAPIforrealtimecommunicationbetweenaclientandaserver.Youlearnhowto:
CreateaJavaPlatform,EnterpriseEdition7(JavaEE7)applicationthatusestheWebSocketAPIUsetheOnOpenandOnMessageWebSocketlifecycleeventstoperformdifferentactionsontheJavaEE7application.DefineaclientsideWebSocketendpointbyusingJavaScriptOperateonPlainOldJavaObjects(POJOs),inrealtime,withactionsinvokedfromawebbrowserclient
TimetoComplete
Approximately1hour
Introduction
Modernwebapplicationsrequiremoreinteractivitythaneverbeforeforclient/servercommunications.HTTP,however,wasn'tbuilttodeliverthekindofinteractivityneededtoday."Push"orComettechniques,suchaslongpolling,emergedasawaytoallowaservertopushdatatoabrowser.BecausethesetechniquesusuallyrelyonHTTP,theypresentsomedisadvantagesforclient/servercommunications,suchasHTTPoverhead.Thesedisadvantagesresultinlessefficientcommunicationbetweentheserverandthewebbrowser,especiallyforrealtimeapplications.
WebSocketprovidesanalternativetothislimitationbyprovidingbidirectional,fullduplex,realtime,client/servercommunications.Theservercansenddatatotheclientatanytime.BecauseWebSocketrunsoverTCP,italsoreducestheoverheadofeachmessage.WebSocketalsoprovidesgreaterscalabilityformessageintensiveapplicationsbecauseonlyoneconnectionperclientisused(whereasHTTPcreatesonerequestpermessage).Finally,WebSocketispartofJavaEE7,soyoucanuseothertechnologiesintheJavaEE7stack.
Scenario
Inthistutorial,youcreateJavaWebSocketHome,asmarthomecontrolwebapplicationbasedonJavaEE7.JavaWebSocketHomehasauserinterfaceforconnectingandcontrollingfictitiousdevicesfromawebbrowsertoaJavaapplication.ThisapplicationprovidesrealtimeupdatestoallclientsthatareconnectedtotheJavaWebSocketHomeserver.
SoftwareRequirements
Thefollowingisalistofsoftwarerequirementsneededforthistutorial:
DownloadandinstalltheJavaEE7softwaredevelopmentkit(SDK)fromhttp://www.oracle.com/technetwork/java/javaee/downloads/index.html.DownloadandinstalltheJavaNetBeans7.3.1integrateddevelopmentenvironment(IDE)fromhttp://www.netbeans.org/downloads/index.html.DownloadandinstallOracleGlassFishServer4.0fromhttp://www.oracle.com/us/products/middleware/cloudappfoundation/glassfishserver/overview/index.html.
Prerequisites
Beforestartingthistutorial,youshouldhave:
KnowledgeoftheJavaprogramminglanguageBasicknowledgeofJavaEE7BasicknowledgeofHTML5,JavaScript,andcascadingstylesheets(CSS)
IntroducedaspartoftheHTML5initiative,theWebSocketprotocolisastandardwebtechnologythatsimplifiescommunicationandconnectionmanagementbetweenclientsandaserver.Bymaintainingaconstantconnection,WebSocketprovidesfullduplexclient/servercommunication.Italsoprovidesalowlatency,lowlevelcommunicationthatworksontheunderlyingTCP/IPconnection.
TheJavaAPIforWebSocket(JSR356)simplifiestheintegrationofWebSocketintoJavaEE7applications.
HerearesomeofthefeaturesoftheJavaAPIforWebSocket:
AnnotationdrivenprogrammingthatallowsdeveloperstousePOJOstointeractwithWebSocketlifecycleeventsInterfacedrivenprogrammingthatallowsdeveloperstoimplementinterfacesandmethodstointeractwithWebSocketlifecycleeventsIntegrationwithotherJavaEEtechnologies(YoucaninjectobjectsandEnterpriseJavaBeansbyusingcomponentssuchasContextsandDependencyInjection.)
Inthissection,youcreateaJavaEE7webapplication.
1. OpentheNetBeansIDE.
2. FromtheFilemenu,selectNewProject.
Overview
Introduction to the WebSocket API in Java EE 7
Creating a Java EE 7 Project
JavaEE7:BuildingWebApplicationswithWebSocket,JavaScriptandHTML5
http://www.oracle.com/us/products/middleware/cloud-app-foundation/glassfish-server/overview/index.htmlhttp://netbeans.org/downloads/http://www.oracle.com/technetwork/java/javaee/downloads/index.htmlhttp://jcp.org/en/jsr/detail?id=356 -
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 2/20
3. IntheNewProjectdialogbox,performthefollowingsteps:
a. SelectJavaWebfromCategories.b. SelectWebApplicationfromProjects.c. ClickNext.
4. EnterWebsocketHomeastheprojectnameandclickNext.
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 3/20
5. IntheNewWebApplicationdialogbox,performthefollowingsteps:
a. SelectGlassFishServerfromtheServerlist.b. EnterWebsocketHomeasthecontextpath.c. ClickFinish.
TheWebsocketHomeprojecthasbeencreated.
6. RightclicktheWebsocketHomeprojectandselectRuntotestyourapplication.
AbrowserwindowdisplaysaTODOwritecontentmessage.
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 4/20
YousuccessfullycreatedaJavaEE7webapplicationbyusingNetBeans.
Inthissection,youcreatetheclassthatcontainsadevice'sattributes.
1. SelectFile>NewFile.
2. IntheNewFiledialogbox,performthefollowingsteps:
a. SelectJavafromCategories.b. SelectJavaClassfromFileTypes.c. ClickNext.
Creating the Device Model
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 5/20
3. IntheNewJavaClassdialogbox,performthefollowingsteps:
a. EnterDeviceastheclassname.b. Enterorg.example.modelasthepackage.c. ClickFinish.
TheDeviceclassisaddedtotheproject.
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 6/20
4. AddthefollowingcodetotheDevice.javaclasstodefinetheclassconstructor,anditsgetterandsettermethods:
ViewCode
5. SelectFile>Savetosavethefile.
YousuccessfullycreatedtheDeviceclass.
Inthissection,youcreateaWebSocketendpoint.
1. SelectFile>NewFile.
2. IntheNewFiledialogbox,performthefollowingsteps:
a. SelectJavafromCategories.b. SelectJavaClassfromFileTypes.c. ClickNext.
Creating the WebSocket Server Endpoint
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 7/20
3. IntheNewJavaClassdialogbox,performthefollowingsteps:
a. EnterDeviceWebSocketServerastheclassname.b. Enterorg.example.websocketasthepackage.c. ClickFinish.
TheDeviceWebSocketServerclassisaddedtotheproject.
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 8/20
4. DefinetheWebSocketserverendpointpathbyaddingthefollowingcode:
5. DefinetheWebSocketlifecycleannotationsbyaddingthefollowingmethodsandimportstotheDeviceWebSocketServerclass:
TheWebSocketlifecycleannotationsaremappedtoJavamethods.Inthisexample,the@OnOpenannotationismappedtotheopen()methodthe@OnMessageannotationismappedtothehandleMessage()methodthe@OnCloseannotationtotheclose()methodandthe@OnErrorannotationtotheonError()method.
6. Specifythattheclassisapplicationscopedbyaddingthe@ApplicationScopedannotationandimportingitspackage.
7. Savethefile.
YousuccessfullycreatedtheWebSocketserverendpoint.
Inthissection,youcreateaclassforhandlingthesessionsthatareconnectedtotheserver.
1. SelectFile>NewFile.
2. IntheNewFiledialogbox,performthefollowingsteps:
a. SelectJavafromCategories.b. SelectJavaClassfromFileTypes.c. ClickNext.
package org.example.websocket;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/actions")public class DeviceWebSocketServer { }
import javax.websocket.OnClose;import javax.websocket.OnError;import javax.websocket.OnMessage;import javax.websocket.OnOpen;import javax.websocket.Session;import javax.websocket.server.ServerEndpoint; @ServerEndpoint("/actions")public class DeviceWebSocketServer {
@OnOpen public void open(Session session) { }
@OnClose public void close(Session session) { }
@OnError public void onError(Throwable error) { }
@OnMessage public void handleMessage(String message, Session session) { }}
...import javax.websocket.OnOpen;import javax.websocket.Session;import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped@ServerEndpoint("/actions")public class DeviceWebSocketServer {...}
Creating the Session Handler
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 9/20
3. IntheNewJavaClassdialogbox,performthefollowingsteps:
a. EnterDeviceSessionHandlerastheclassname.b. Enterorg.example.websocketasthepackage.c. ClickFinish.
TheDeviceSessionHandlerclassisaddedtotheproject.
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 10/20
4. Specifythattheclassisapplicationscopedbyaddingthe@ApplicationScopedannotationandimportingitscorrespondingpackage.
5. DeclareaHashSetforstoringthelistofdevicesaddedtotheapplicationandtheactivesessionsintheapplication,andimporttheirpackages.
Note:Eachclientconnectedtotheapplicationhasitsownsession.
6. Definethefollowingmethodsforaddingandremovingsessionstotheserver.
7. DefinethemethodsthatoperateontheDeviceobject.
Thesemethodsare:
addDevice()Addadevicetotheapplication.removeDevice()Removeadevicefromtheapplication.toggleDevice()Togglethedevicestatus.getDevices()Retrievethelistofdevicesandtheirattributes.getDeviceById()Retrieveadevicewithaspecificidentifier.createAddMessage()BuildaJSONmessageforaddingadevicetotheapplication.sendToSession()Sendaneventmessagetoaclient.sendToAllConnectedSessions()Sendaneventmessagetoallconnectedclients.
package org.example.websocket;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScopedpublic class DeviceSessionHandler { }
package org.example.websocket;
import javax.enterprise.context.ApplicationScoped;import java.util.HashSet;import java.util.Set;import javax.websocket.Session;import org.example.model.Device;
@ApplicationScopedpublic class DeviceSessionHandler { private final Set sessions = new HashSet(); private final Set devices = new HashSet();}
package org.example.websocket;
...
@ApplicationScopedpublic class DeviceSessionHandler { ... public void addSession(Session session) { sessions.add(session); }
public void removeSession(Session session) { sessions.remove(session); }}
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 11/20
8. Savethefile.
Yousuccessfullycreatedthesessionhandler.
Inthissection,youcreatetheJavaWebSocketHomeuserinterface(UI)byusingHTML5andCSS.
1. Opentheindex.htmlfile.
2. Enterthefollowingcodetoaddtheproperelementsforaddinganddisplayingdevicesonthewebbrowserclient.
ViewCode
3. Savethefile.
4. SelectFile>NewFile.
5. IntheNewFiledialogdialogbox,performthefollowingsteps:
a. SelectWebfromCategories.b. SelectCascadingStyleSheetfromFileTypes.c. ClickNext.
package org.example.websocket; ... public class DeviceSessionHandler { ... public List getDevices() { return new ArrayList(devices); }
public void addDevice(Device device) { }
public void removeDevice(int id) { }
public void toggleDevice(int id) { }
private Device getDeviceById(int id) { return null; }
private JsonObject createAddMessage(Device device) { return null; }
private void sendToAllConnectedSessions(JsonObject message) { }
private void sendToSession(Session session, JsonObject message) { }}
Rendering the User Interface
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 12/20
6. IntheNewCascadingStyleSheetdialogbox,performthefollowingsteps:
a. Enterstyleasthefilename.b. SelectWeb Pagesasthelocation.c. ClickFinish.
Thestyle.cssfileisaddedtotheproject.
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 13/20
7. Copythefollowingcodeintothestyle.cssfile.
ViewCode
8. Savethefile.
YousuccessfullycreatedtheUIelementsfortheJavaWebSocketHomeapplication.
Inthissection,youspecifytheclientendpointbyusingJavaScript.
1. SelectFile>NewFile.
2. IntheNewFiledialogbox,performthefollowingsteps:
a. SelectWebfromCategories.b. SelectJavaScriptFilefromFileTypes.c. ClickNext.
Creating the WebSocket Client Endpoint
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 14/20
3. EnterwebsocketasthefilenameandclickFinish.
Thewebsocket.jsfileisaddedtotheproject.
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 15/20
Thefileperformsthefollowingactions:
MapstheWebSocketserverendpointtotheURIdefinedin"CreatingtheWebSocketServerEndpoint".CapturestheJavaScripteventsforadding,removing,andchangingadevice'sstatusandpushesthoseeventstotheWebSocketserver.ThesemethodsareaddDevice(),removeDevice(),andtoggleDevice().TheactionsaresentinJSONmessagestotheWebSocketserver.DefinesacallbackmethodfortheWebSocketonmessageevent.TheonmessageeventcapturestheeventssentfromtheWebSocketserver(inJSON)andprocessesthoseactions.Inthisapplication,theseactionsareusuallyrenderingchangesintheclientUI.TogglesthevisibilityofanHTMLformforaddinganewdevice.
4. Addthefollowingcodetothewebsocket.jsfile.
ViewCode
5. Savethefile.
YousuccessfullycreatedtheWebSocketclientendpointandthedefinedactionsforhandlingWebSocketeventsintheclient.
Inthissection,youprocessWebSocketlifecycleeventsintheDeviceWebSocketServerclass.
1. OpentheDeviceWebSocketServerclass.
2. InjectaDeviceSessionHandlerobjecttoprocesstheWebSocketlifecycleeventsineachsessionandimportitscorrespondingpackage.
ViewCode
3. ProcesstheOnMessageWebSocketlifecycleeventbyaddingthefollowingcodetotheopenmethod.
ViewCode
TheOnMessagemethodperformsthefollowingactions:
Readsdeviceactionsandattributessentfromtheclient.InvokesthesessionhandlertoperformtheproperoperationsonthespecifiedDeviceobject.Inthisapplication,theaddactionsentfromtheclientinvokestheaddDevicemethod,theremoveactioninvokestheremoveDevicemethod,andthetoggleactioninvokesthetoggleDevicemethod.
4. ProcesstheOnOpenWebSocketeventandaddthemissingimports.
ViewCode
TheOnOpeneventreadstheattributessentfromtheclientinJSONandcreatesanewDeviceobjectwiththespecifiedparameters.
5. ImplementtheOnCloseandOnErroractionsandaddthemissingimports.
ViewCode
6. Savethefile.
YousuccessfullyprocessedWebSocketlifecycleeventsintheDeviceWebSocketServerclass.
Inthissection,youperformoperationsintheDeviceobjectbyusingtheDeviceSessionHandlerclass.
1. OpentheDeviceSessionHandler.javaclass.
2. Defineavariableforstoringthedeviceidentifiersintheserver.
Processing WebSocket Events in the Server
Implementing the WebSocket Actions in the Session Handler
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 16/20
3. AddtheforlooptotheaddSessionmethodtosendthelistofdevicestotheconnectedclient.
4. ImplementtheaddDevicemethodbyaddingthefollowingcode.
TheaddDevicemethodperformsthefollowingactions:
CreatesanewDeviceobjectwiththecurrentvalueofthedeviceIDvariableandtheparametersspecifiedbytheuserintheclient.Sendsamessage,inJSON,toallsessionsoractiveclientsintheWebSocketserver.
5. ImplementtheremoveDevicemethod.
TheremoveDevicemethodremovesthedeviceobjectspecifiedbytheuserandsendsamessage,inJSON,toallsessionsthatareactiveintheWebSocketserver.
6. ImplementthetoggleDevicemethod.
ThetoggleDevicemethodtogglesthedevicestatusandsendstheeventtoallsessionsthatarestillactiveintheWebSocketserver.
7. Implementmissingmethods.
ViewCode
8. Savethefile.
YousuccessfullyimplementedtheWebSocketactionsinthesessionhandler.
... public class DeviceSessionHandler {
private int deviceId = 0; private final Set sessions = new HashSet(); private final Set devices = new HashSet(); ...
}
public void addSession(Session session) { sessions.add(session); for (Device device : devices) { JsonObject addMessage = createAddMessage(device); sendToSession(session, addMessage); }
}
public void addDevice(Device device) { device.setId(deviceId); devices.add(device); deviceId++; JsonObject addMessage = createAddMessage(device); sendToAllConnectedSessions(addMessage); }
public void removeDevice(int id) { Device device = getDeviceById(id); if (device != null) { devices.remove(device); JsonProvider provider = JsonProvider.provider(); JsonObject removeMessage = provider.createObjectBuilder() .add("action", "remove") .add("id", id) .build(); sendToAllConnectedSessions(removeMessage); } }
public void toggleDevice(int id) { JsonProvider provider = JsonProvider.provider(); Device device = getDeviceById(id); if (device != null) { if ("On".equals(device.getStatus())) { device.setStatus("Off"); } else { device.setStatus("On"); } JsonObject updateDevMessage = provider.createObjectBuilder() .add("action", "toggle") .add("id", device.getId()) .add("status", device.getStatus()) .build(); sendToAllConnectedSessions(updateDevMessage); } }
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 17/20
Inthissection,youtesttheJavaWebSocketHomeapplication.
1. RightclicktheWebsocketHomeprojectandclickRuntobuildanddeploytheproject.
AWebbrowserdisplaystheJavaWebSocketHomeindexpage.
2. Openanotherwebbrowserandplaceitnexttothefirstone.
3. Ineitherwindow,clickAddadevicetodisplaythe"Addanewdevice"form.
4. Inthe"Addanewdeviceform,"performthefollowingsteps:
a. EnterMicrowaveasthename.b. SelectApplianceasthetype.c. EnterKitchenasthedescription.d. ClickAdd.
Testing the Java WebSocket Home Application
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 18/20
AdeviceisaddedtotheJavaWebSocketHomeserveranditisrenderedinbothwebbrowsers.
5. Optional:Addmoredevicesofdifferenttypes.
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 19/20
6. Onanydevice,clickTurnon.
ThedevicestatuschangestoOffintheserverandallclients.
7. Onanydevice,clickRemovedevice.
Thedeviceisremovedfromtheserverandallclients.
Congratulations!YoucreatedasmarthomecontrolwebapplicationbyusingJavaEE7andtheWebSocketAPI.
Youalsolearnedhowto:
DefineaWebSocketserverendpointinaJavaclassbyusingtheWebSocketAPIannotationsSendmessagestoandfromtheclienttotheWebSocketserverinJSONUsetheWebSocketAPIlifecycleannotationstohandleWebSocketevents
Summary
-
18/05/2015 Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html 20/20
UsetheWebSocketAPIlifecycleannotationstohandleWebSocketeventsProcessWebSocketlifecycleeventsintheclientbyusingHTML5andJavaScript
ResourcesFormoreinformationaboutthetopicsinthistutorial,see:
JavaEE7:NewFeatures,anOracleinstructedcourseonthenewfeaturesofJavaEE7JavaEE7TutorialTheJavaEE7TutorialchapteronWebSocketUsingWebSocketforRealTimeCommunicationinJavaPlatform,EnterpiseEdition7,atutorialaboutWebSocketforJavaEE7.TheAquariumBlogJSR356:JavaAPIforWebSocketWebSocket.org,aWebSocketcommunity"JavaEE7EmbracingHTML5"articleinJavaMagazineTolearnmoreaboutJavaEE7,refertoadditionalOBEsintheOracleLearningLibrary.
Credits
LeadCurriculumDeveloper:MiguelSalazarOtherContributors:EduardoMoranchel
http://docs.oracle.com/javaee/7/tutorial/doc/home.htmhttp://www.websocket.org/http://docs.oracle.com/javaee/7/tutorial/doc/websocket.htm#GKJIQ5https://blogs.oracle.com/theaquarium/http://www.oracle.com/webfolder/technetwork/tutorials/obe/java//WebSocket/WebSocket.htmlhttp://jcp.org/en/jsr/detail?id=356http://www.oraclejavamagazine-digital.com/javamagazine_open/20130506#pg67http://education.oracle.com/pls/web_prod-plq-dad/db_pages.getCourseDesc?dc=D77640GC10http://www.oracle.com/goto/oll