Java EE 7 - Building Web Applications With WebSocket, JavaScript and HTML5
Java EE 7 - Building Web Applications With WebSocket, JavaScript and HTML5
JavaEE7:BuildingWebApplicationswithWebSocket,JavaScriptandHTML5
Overview
Purpose
ThistutorialshowsyouhowtocreateanapplicationthatusestheWebSocketAPIforrealtimecommunicationbetweenaclientandaserver.Youlearnhowto:
CreateaJavaPlatform,EnterpriseEdition7(JavaEE7)applicationthatusestheWebSocketAPI
UsetheOnOpenandOnMessageWebSocketlifecycleeventstoperformdifferentactionsontheJavaEE7application.
DefineaclientsideWebSocketendpointbyusingJavaScript
OperateonPlainOldJavaObjects(POJOs),inrealtime,withactionsinvokedfromawebbrowserclient
TimetoComplete
Approximately1hour
Introduction
Modernwebapplicationsrequiremoreinteractivitythaneverbeforeforclient/servercommunications.HTTP,however,wasn'tbuilttodeliverthekindofinteractivityneededtoday.
"Push"orComettechniques,suchaslongpolling,emergedasawaytoallowaservertopushdatatoabrowser.BecausethesetechniquesusuallyrelyonHTTP,theypresent
somedisadvantagesforclient/servercommunications,suchasHTTPoverhead.Thesedisadvantagesresultinlessefficientcommunicationbetweentheserverandtheweb
browser,especiallyforrealtimeapplications.
WebSocketprovidesanalternativetothislimitationbyprovidingbidirectional,fullduplex,realtime,client/servercommunications.Theservercansenddatatotheclientatany
time.BecauseWebSocketrunsoverTCP,italsoreducestheoverheadofeachmessage.WebSocketalsoprovidesgreaterscalabilityformessageintensiveapplicationsbecause
onlyoneconnectionperclientisused(whereasHTTPcreatesonerequestpermessage).Finally,WebSocketispartofJavaEE7,soyoucanuseothertechnologiesintheJava
EE7stack.
Scenario
Inthistutorial,youcreateJavaWebSocketHome,asmarthomecontrolwebapplicationbasedonJavaEE7.JavaWebSocketHomehasauserinterfaceforconnectingand
controllingfictitiousdevicesfromawebbrowsertoaJavaapplication.ThisapplicationprovidesrealtimeupdatestoallclientsthatareconnectedtotheJavaWebSocketHome
server.
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:
KnowledgeoftheJavaprogramminglanguage
BasicknowledgeofJavaEE7
BasicknowledgeofHTML5,JavaScript,andcascadingstylesheets(CSS)
IntroducedaspartoftheHTML5initiative,theWebSocketprotocolisastandardwebtechnologythatsimplifiescommunicationandconnectionmanagementbetweenclientsanda
server.Bymaintainingaconstantconnection,WebSocketprovidesfullduplexclient/servercommunication.Italsoprovidesalowlatency,lowlevelcommunicationthatworksonthe
underlyingTCP/IPconnection.
TheJavaAPIforWebSocket(JSR356)simplifiestheintegrationofWebSocketintoJavaEE7applications.
HerearesomeofthefeaturesoftheJavaAPIforWebSocket:
AnnotationdrivenprogrammingthatallowsdeveloperstousePOJOstointeractwithWebSocketlifecycleevents
InterfacedrivenprogrammingthatallowsdeveloperstoimplementinterfacesandmethodstointeractwithWebSocketlifecycleevents
IntegrationwithotherJavaEEtechnologies(YoucaninjectobjectsandEnterpriseJavaBeansbyusingcomponentssuchasContextsandDependencyInjection.)
Inthissection,youcreateaJavaEE7webapplication.
1. OpentheNetBeansIDE.
2. FromtheFilemenu,selectNewProject.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
1/20
18/05/2015
3. IntheNewProjectdialogbox,performthefollowingsteps:
a. SelectJavaWebfromCategories.
b. SelectWebApplicationfromProjects.
c. ClickNext.
4. EnterWebsocketHomeastheprojectnameandclickNext.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
2/20
18/05/2015
5. IntheNewWebApplicationdialogbox,performthefollowingsteps:
a. SelectGlassFishServerfromtheServerlist.
b. EnterWebsocketHomeasthecontextpath.
c. ClickFinish.
TheWebsocketHomeprojecthasbeencreated.
6. RightclicktheWebsocketHomeprojectandselectRuntotestyourapplication.
AbrowserwindowdisplaysaTODOwritecontentmessage.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
3/20
18/05/2015
YousuccessfullycreatedaJavaEE7webapplicationbyusingNetBeans.
Inthissection,youcreatetheclassthatcontainsadevice'sattributes.
1. SelectFile>NewFile.
2. IntheNewFiledialogbox,performthefollowingsteps:
a. SelectJavafromCategories.
b. SelectJavaClassfromFileTypes.
c. ClickNext.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
4/20
18/05/2015
3. IntheNewJavaClassdialogbox,performthefollowingsteps:
a. EnterDeviceastheclassname.
b. Enterorg.example.modelasthepackage.
c. ClickFinish.
TheDeviceclassisaddedtotheproject.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
5/20
18/05/2015
4. AddthefollowingcodetotheDevice.javaclasstodefinetheclassconstructor,anditsgetterandsettermethods:
ViewCode
5. SelectFile>Savetosavethefile.
YousuccessfullycreatedtheDeviceclass.
Inthissection,youcreateaWebSocketendpoint.
1. SelectFile>NewFile.
2. IntheNewFiledialogbox,performthefollowingsteps:
a. SelectJavafromCategories.
b. SelectJavaClassfromFileTypes.
c. ClickNext.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
6/20
18/05/2015
3. IntheNewJavaClassdialogbox,performthefollowingsteps:
a. EnterDeviceWebSocketServerastheclassname.
b. Enterorg.example.websocketasthepackage.
c. ClickFinish.
TheDeviceWebSocketServerclassisaddedtotheproject.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
7/20
18/05/2015
4. DefinetheWebSocketserverendpointpathbyaddingthefollowingcode:
package org.example.websocket;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/actions")
public class DeviceWebSocketServer {
}
5. DefinetheWebSocketlifecycleannotationsbyaddingthefollowingmethodsandimportstotheDeviceWebSocketServerclass:
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) {
}
TheWebSocketlifecycleannotationsaremappedtoJavamethods.Inthisexample,the@OnOpenannotationismappedtotheopen()methodthe@OnMessageannotation
ismappedtothehandleMessage()methodthe@OnCloseannotationtotheclose()methodandthe@OnErrorannotationtotheonError()method.
6. Specifythattheclassisapplicationscopedbyaddingthe@ApplicationScopedannotationandimportingitspackage.
...
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
@ServerEndpoint("/actions")
public class DeviceWebSocketServer {
...
}
7. Savethefile.
YousuccessfullycreatedtheWebSocketserverendpoint.
Inthissection,youcreateaclassforhandlingthesessionsthatareconnectedtotheserver.
1. SelectFile>NewFile.
2. IntheNewFiledialogbox,performthefollowingsteps:
a. SelectJavafromCategories.
b. SelectJavaClassfromFileTypes.
c. ClickNext.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
8/20
18/05/2015
3. IntheNewJavaClassdialogbox,performthefollowingsteps:
a. EnterDeviceSessionHandlerastheclassname.
b. Enterorg.example.websocketasthepackage.
c. ClickFinish.
TheDeviceSessionHandlerclassisaddedtotheproject.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
9/20
18/05/2015
4. Specifythattheclassisapplicationscopedbyaddingthe@ApplicationScopedannotationandimportingitscorrespondingpackage.
package org.example.websocket;
import javax.enterprise.context.ApplicationScoped;
@ApplicationScoped
public class DeviceSessionHandler {
}
5. DeclareaHashSetforstoringthelistofdevicesaddedtotheapplicationandtheactivesessionsintheapplication,andimporttheirpackages.
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;
@ApplicationScoped
public class DeviceSessionHandler {
private final Set sessions = new HashSet<>();
private final Set devices = new HashSet<>();
}
Note:Eachclientconnectedtotheapplicationhasitsownsession.
6. Definethefollowingmethodsforaddingandremovingsessionstotheserver.
package org.example.websocket;
...
@ApplicationScoped
public class DeviceSessionHandler {
...
public void addSession(Session session) {
sessions.add(session);
}
7. DefinethemethodsthatoperateontheDeviceobject.
Thesemethodsare:
addDevice()Addadevicetotheapplication.
removeDevice()Removeadevicefromtheapplication.
toggleDevice()Togglethedevicestatus.
getDevices()Retrievethelistofdevicesandtheirattributes.
getDeviceById()Retrieveadevicewithaspecificidentifier.
createAddMessage()BuildaJSONmessageforaddingadevicetotheapplication.
sendToSession()Sendaneventmessagetoaclient.
sendToAllConnectedSessions()Sendaneventmessagetoallconnectedclients.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
10/20
18/05/2015
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) {
}
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.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
11/20
18/05/2015
6. IntheNewCascadingStyleSheetdialogbox,performthefollowingsteps:
a. Enterstyleasthefilename.
b. SelectWeb Pagesasthelocation.
c. ClickFinish.
Thestyle.cssfileisaddedtotheproject.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
12/20
18/05/2015
7. Copythefollowingcodeintothestyle.cssfile.
ViewCode
8. Savethefile.
YousuccessfullycreatedtheUIelementsfortheJavaWebSocketHomeapplication.
Inthissection,youspecifytheclientendpointbyusingJavaScript.
1. SelectFile>NewFile.
2. IntheNewFiledialogbox,performthefollowingsteps:
a. SelectWebfromCategories.
b. SelectJavaScriptFilefromFileTypes.
c. ClickNext.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
13/20
18/05/2015
3. EnterwebsocketasthefilenameandclickFinish.
Thewebsocket.jsfileisaddedtotheproject.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
14/20
18/05/2015
Thefileperformsthefollowingactions:
MapstheWebSocketserverendpointtotheURIdefinedin"CreatingtheWebSocketServerEndpoint".
CapturestheJavaScripteventsforadding,removing,andchangingadevice'sstatusandpushesthoseeventstotheWebSocketserver.Thesemethodsare
addDevice(),removeDevice(),andtoggleDevice().TheactionsaresentinJSONmessagestotheWebSocketserver.
DefinesacallbackmethodfortheWebSocketonmessageevent.TheonmessageeventcapturestheeventssentfromtheWebSocketserver(inJSON)and
processesthoseactions.Inthisapplication,theseactionsareusuallyrenderingchangesintheclientUI.
TogglesthevisibilityofanHTMLformforaddinganewdevice.
4. Addthefollowingcodetothewebsocket.jsfile.
ViewCode
5. Savethefile.
YousuccessfullycreatedtheWebSocketclientendpointandthedefinedactionsforhandlingWebSocketeventsintheclient.
Inthissection,youprocessWebSocketlifecycleeventsintheDeviceWebSocketServerclass.
1. OpentheDeviceWebSocketServerclass.
2. InjectaDeviceSessionHandlerobjecttoprocesstheWebSocketlifecycleeventsineachsessionandimportitscorrespondingpackage.
ViewCode
3. ProcesstheOnMessageWebSocketlifecycleeventbyaddingthefollowingcodetotheopenmethod.
ViewCode
TheOnMessagemethodperformsthefollowingactions:
Readsdeviceactionsandattributessentfromtheclient.
InvokesthesessionhandlertoperformtheproperoperationsonthespecifiedDeviceobject.Inthisapplication,theaddactionsentfromtheclientinvokesthe
addDevicemethod,theremoveactioninvokestheremoveDevicemethod,andthetoggleactioninvokesthetoggleDevicemethod.
4. ProcesstheOnOpenWebSocketeventandaddthemissingimports.
ViewCode
TheOnOpeneventreadstheattributessentfromtheclientinJSONandcreatesanewDeviceobjectwiththespecifiedparameters.
5. ImplementtheOnCloseandOnErroractionsandaddthemissingimports.
ViewCode
6. Savethefile.
YousuccessfullyprocessedWebSocketlifecycleeventsintheDeviceWebSocketServerclass.
Inthissection,youperformoperationsintheDeviceobjectbyusingtheDeviceSessionHandlerclass.
1. OpentheDeviceSessionHandler.javaclass.
2. Defineavariableforstoringthedeviceidentifiersintheserver.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
15/20
18/05/2015
...
public class DeviceSessionHandler {
private int deviceId = 0;
private final Set sessions = new HashSet<>();
private final Set devices = new HashSet<>();
...
}
3. AddtheforlooptotheaddSessionmethodtosendthelistofdevicestotheconnectedclient.
4. ImplementtheaddDevicemethodbyaddingthefollowingcode.
TheaddDevicemethodperformsthefollowingactions:
CreatesanewDeviceobjectwiththecurrentvalueofthedeviceIDvariableandtheparametersspecifiedbytheuserintheclient.
Sendsamessage,inJSON,toallsessionsoractiveclientsintheWebSocketserver.
5. ImplementtheremoveDevicemethod.
TheremoveDevicemethodremovesthedeviceobjectspecifiedbytheuserandsendsamessage,inJSON,toallsessionsthatareactiveintheWebSocketserver.
6. ImplementthetoggleDevicemethod.
ThetoggleDevicemethodtogglesthedevicestatusandsendstheeventtoallsessionsthatarestillactiveintheWebSocketserver.
7. Implementmissingmethods.
ViewCode
8. Savethefile.
YousuccessfullyimplementedtheWebSocketactionsinthesessionhandler.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
16/20
18/05/2015
Inthissection,youtesttheJavaWebSocketHomeapplication.
1. RightclicktheWebsocketHomeprojectandclickRuntobuildanddeploytheproject.
AWebbrowserdisplaystheJavaWebSocketHomeindexpage.
2. Openanotherwebbrowserandplaceitnexttothefirstone.
3. Ineitherwindow,clickAddadevicetodisplaythe"Addanewdevice"form.
4. Inthe"Addanewdeviceform,"performthefollowingsteps:
a.
b.
c.
d.
EnterMicrowaveasthename.
SelectApplianceasthetype.
EnterKitchenasthedescription.
ClickAdd.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
17/20
18/05/2015
AdeviceisaddedtotheJavaWebSocketHomeserveranditisrenderedinbothwebbrowsers.
5. Optional:Addmoredevicesofdifferenttypes.
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
18/20
18/05/2015
6. Onanydevice,clickTurnon.
ThedevicestatuschangestoOffintheserverandallclients.
7. Onanydevice,clickRemovedevice.
Thedeviceisremovedfromtheserverandallclients.
Summary
Congratulations!YoucreatedasmarthomecontrolwebapplicationbyusingJavaEE7andtheWebSocketAPI.
Youalsolearnedhowto:
DefineaWebSocketserverendpointinaJavaclassbyusingtheWebSocketAPIannotations
SendmessagestoandfromtheclienttotheWebSocketserverinJSON
UsetheWebSocketAPIlifecycleannotationstohandleWebSocketevents
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
19/20
18/05/2015
UsetheWebSocketAPIlifecycleannotationstohandleWebSocketevents
ProcessWebSocketlifecycleeventsintheclientbyusingHTML5andJavaScript
Resources
Formoreinformationaboutthetopicsinthistutorial,see:
JavaEE7:NewFeatures,anOracleinstructedcourseonthenewfeaturesofJavaEE7
JavaEE7Tutorial
TheJavaEE7TutorialchapteronWebSocket
UsingWebSocketforRealTimeCommunicationinJavaPlatform,EnterpiseEdition7,atutorialaboutWebSocketforJavaEE7.
TheAquariumBlog
JSR356:JavaAPIforWebSocket
WebSocket.org,aWebSocketcommunity
"JavaEE7EmbracingHTML5"articleinJavaMagazine
TolearnmoreaboutJavaEE7,refertoadditionalOBEsintheOracleLearningLibrary.
Credits
LeadCurriculumDeveloper:MiguelSalazar
OtherContributors:EduardoMoranchel
http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html
20/20