Anda di halaman 1dari 20

18/05/2015

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)

Introduction to the WebSocket API in Java EE 7

IntroducedaspartoftheHTML5initiative,theWebSocketprotocolisastandardwebtechnologythatsimplifiescommunicationandconnectionmanagementbetweenclientsanda
server.Bymaintainingaconstantconnection,WebSocketprovidesfullduplexclient/servercommunication.Italsoprovidesalowlatency,lowlevelcommunicationthatworksonthe
underlyingTCP/IPconnection.
TheJavaAPIforWebSocket(JSR356)simplifiestheintegrationofWebSocketintoJavaEE7applications.
HerearesomeofthefeaturesoftheJavaAPIforWebSocket:
AnnotationdrivenprogrammingthatallowsdeveloperstousePOJOstointeractwithWebSocketlifecycleevents
InterfacedrivenprogrammingthatallowsdeveloperstoimplementinterfacesandmethodstointeractwithWebSocketlifecycleevents
IntegrationwithotherJavaEEtechnologies(YoucaninjectobjectsandEnterpriseJavaBeansbyusingcomponentssuchasContextsandDependencyInjection.)

Creating a Java EE 7 Project

Inthissection,youcreateaJavaEE7webapplication.
1. OpentheNetBeansIDE.
2. FromtheFilemenu,selectNewProject.

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html

1/20

18/05/2015

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

YousuccessfullycreatedaJavaEE7webapplicationbyusingNetBeans.

Creating the Device Model

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

4. AddthefollowingcodetotheDevice.javaclasstodefinetheclassconstructor,anditsgetterandsettermethods:

ViewCode

5. SelectFile>Savetosavethefile.

YousuccessfullycreatedtheDeviceclass.

Creating the WebSocket Server Endpoint

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

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.

Creating the Session Handler

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

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);
}

public void removeSession(Session session) {


sessions.remove(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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

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) {


}

8. Savethefile.
Yousuccessfullycreatedthesessionhandler.

Rendering the User Interface

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

7. Copythefollowingcodeintothestyle.cssfile.

ViewCode

8. Savethefile.
YousuccessfullycreatedtheUIelementsfortheJavaWebSocketHomeapplication.

Creating the WebSocket Client Endpoint

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

3. EnterwebsocketasthefilenameandclickFinish.

Thewebsocket.jsfileisaddedtotheproject.

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html

14/20

18/05/2015

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

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.

Processing WebSocket Events in the Server

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.

Implementing the WebSocket Actions in the Session Handler

Inthissection,youperformoperationsintheDeviceobjectbyusingtheDeviceSessionHandlerclass.
1. OpentheDeviceSessionHandler.javaclass.
2. Defineavariableforstoringthedeviceidentifiersintheserver.

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html

15/20

18/05/2015

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

...
public class DeviceSessionHandler {
private int deviceId = 0;
private final Set sessions = new HashSet<>();
private final Set devices = new HashSet<>();
...
}

3. AddtheforlooptotheaddSessionmethodtosendthelistofdevicestotheconnectedclient.

public void addSession(Session session) {


sessions.add(session);
for (Device device : devices) {
JsonObject addMessage = createAddMessage(device);
sendToSession(session, addMessage);
}
}

4. ImplementtheaddDevicemethodbyaddingthefollowingcode.

public void addDevice(Device device) {


device.setId(deviceId);
devices.add(device);
deviceId++;
JsonObject addMessage = createAddMessage(device);
sendToAllConnectedSessions(addMessage);
}

TheaddDevicemethodperformsthefollowingactions:
CreatesanewDeviceobjectwiththecurrentvalueofthedeviceIDvariableandtheparametersspecifiedbytheuserintheclient.
Sendsamessage,inJSON,toallsessionsoractiveclientsintheWebSocketserver.
5. ImplementtheremoveDevicemethod.

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);
}
}

TheremoveDevicemethodremovesthedeviceobjectspecifiedbytheuserandsendsamessage,inJSON,toallsessionsthatareactiveintheWebSocketserver.
6. ImplementthetoggleDevicemethod.

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);
}
}

ThetoggleDevicemethodtogglesthedevicestatusandsendstheeventtoallsessionsthatarestillactiveintheWebSocketserver.
7. Implementmissingmethods.

ViewCode

8. Savethefile.
YousuccessfullyimplementedtheWebSocketactionsinthesessionhandler.

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html

16/20

18/05/2015

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

Testing the Java WebSocket Home Application

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

AdeviceisaddedtotheJavaWebSocketHomeserveranditisrenderedinbothwebbrowsers.

5. Optional:Addmoredevicesofdifferenttypes.

http://www.oracle.com/webfolder/technetwork/tutorials/obe/java/HomeWebsocket/WebsocketHome.html

18/20

18/05/2015

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

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

Java EE 7: Building Web Applications with WebSocket, JavaScript and HTML5

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

Anda mungkin juga menyukai