Java Platform, Enterprise Edition: The Java EE Tutorial

18.4 Annotated Endpoints

The following example shows how to create the same endpoint from Programmatic Endpoints using annotations instead:

public class EchoEndpoint {
   public void onMessage(Session session, String msg) {
      try {
      } catch (IOException e) { ... }

The annotated endpoint is simpler than the equivalent programmatic endpoint, and it is deployed automatically with the application to the relative path defined in the ServerEndpoint annotation. Instead of having to create an additional class for the message handler, this example uses the OnMessage annotation to designate the method invoked to handle messages.

Table 18-1 lists the annotations available in the javax.websocket package to designate the methods that handle lifecycle events. The examples in the table show the most common parameters for these methods. See the API reference for details on what combinations of parameters are allowed in each case.

Table 18-1 WebSocket Endpoint Lifecycle Annotations

Annotation Event Example


Connection opened

public void open(Session session, 
                 EndpointConfig conf) { }


Message received

public void message(Session session, 
                    String msg) { }


Connection error

public void error(Session session, 
                  Throwable error) { }


Connection closed

public void close(Session session, 
                  CloseReason reason) { }

Close Window

Table of Contents

Java Platform, Enterprise Edition: The Java EE Tutorial

Expand | Collapse