Close

Using WebSockets in Spring MVC application

[Updated: Dec 19, 2017, Created: Dec 19, 2017]

Following example shows how to use Spring's HTML5 based WebSocket support. We need to implement WebSocketHandler interface to define our server endpoint. We will implement our WebSocket in a Spring MVC application.

Example

Maven Dependencies

pom.xml

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-websocket</artifactId>
   <version>5.0.2.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.0.2.RELEASE</version>
</dependency>
<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-messaging</artifactId>
   <version>5.0.2.RELEASE</version>
</dependency>
<dependency>
   <groupId>javax.servlet</groupId>
   <artifactId>javax.servlet-api</artifactId>
   <version>3.1.0</version>
</dependency>

WebSocketHandler Implementation

package com.logicbig.example;

import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

public class MyHandler extends TextWebSocketHandler {
  @Override
  protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
      session.sendMessage(new TextMessage("echo: "+message.getPayload()));
  }
}

A JavaScript WebSocket Client

ws-client.html

<html>
<body style="margin: 35px">
<input id="messageField" type="text">
<input onclick="sendMsg();" value="send" type="button">
<div id="msg-box" style="width:500px; height: 400px; background: #eee; overflow:auto;"></div>

<script>
    var webSocket = new WebSocket("ws://localhost:8080/myHandler");
    var msgField = document.getElementById("messageField");
    var divMsg = document.getElementById("msg-box");
    function sendMsg() {
        var msgToSend = msgField.value;
        webSocket.send(msgToSend);
        divMsg.innerHTML += "<div style='color:green'>Client> " + msgToSend +
                            "</div>"
        msgField.value = "";
    };
    webSocket.onmessage = function(message) {
                divMsg.innerHTML += "Server> : " + message.data;
    };
    webSocket.onopen = function() {
        console.log("connection opened");
    };
    webSocket.onclose = function() {
        console.log("connection closed");
    };
    webSocket.onerror = function wserror(message) {
        console.log("error: " + message);
    };

   document.getElementById("messageField")
        .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        sendMsg();
    }
});
</script>
</body>
</html>

Java config

Along with @EnableWebMvc, we are going to use @EnableWebSocket to enable Spring WebSocket support:

@Configuration
@EnableWebSocket
@EnableWebMvc
public class MyWebConfig implements WebSocketConfigurer {

  @Override
  public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
      registry.addHandler(new MyHandler(), "/myHandler")
              .setAllowedOrigins("*");
  }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Open the ws-client.html outside of the Servlet container:

Example Project

Dependencies and Technologies Used:

  • spring-websocket 5.0.2.RELEASE: Spring WebSocket.
  • spring-webmvc 5.0.2.RELEASE: Spring Web MVC.
  • spring-messaging 5.0.2.RELEASE: Spring Messaging.
  • javax.servlet-api 3.1.0 Java Servlet API
  • JDK 1.8
  • Maven 3.3.9

Spring WebSocket in MVC Application Example Select All Download
  • spring-websocket-example
    • src
      • main
        • java
          • com
            • logicbig
              • example
                • MyHandler.java

    See Also