Java Reference
In-Depth Information
After clicking on
Finish
, NetBeans generates a WebSocket server endpoint for us:
package com.ensode.websocket;
import javax.websocket.OnMessage;
import javax.websocket.server.ServerEndpoint;
@ServerEndpoint("/defaultdataendpoint")
public class DefaultDataEndpoint {
@OnMessage
public String onMessage(String message) {
return null;
}
}
Notice how the value attribute of the
@ServerEndpoint
annotation matches the
value we entered when creating the class with the wizard. NetBeans also generates
a dummy method annotated with
@OnMessage
for us to modify. We will modify this
method to return a JSON string that will be parsed by the client side. The modified
onMessage()
method looks like this:
@OnMessage
public String onMessage(String message) {
String retVal;
if (message.equals("get_defaults")) {
retVal = new StringBuilder("{").
append("\"firstName\":\"Auto\",").
append("\"lastName\":\"Generated\"").
append("}").toString();
} else {
retVal = "";
}
return retVal;
}
In this example, we are generating a simple JSON string by hand.
JSON can be generated with the Java API for JSON-P. Refer to
Chapter 8
,
Java API for JSON Processing
, for details.