Using encoders
In the previous examples, we exchanged messages only of type string
. Sometimes, we may need to transfer more complex objects to the client, a Movie
instance, for example, holding information such as the movie title, actors, and so on. From a RESTful background, the most popular solution is to convert the object to a JSON string. Rather than doing this manually before using the sendText(String)
method, we can define a custom encode that automatically converts the object to the desired format.
Let's look at the following example:
@ServerEndpoint(value = "/movie/{movieId}", encoders = {MovieEncoder.class}) public class MoviesEndpoint{ public void onOpen(Session session, EndpointConfig endpointConfig) { Movie movie = new Movie(); try { // fill with some data session.getBasicRemote().sendObject(movie); } catch (IOException | EncodeException ex) { ex.printStackTrace(); } } ...