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.


Maven Dependencies



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 {
  protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
      session.sendMessage(new TextMessage("echo: "+message.getPayload()));

A JavaScript WebSocket Client


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

    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;
        divMsg.innerHTML += "<div style='color:green'>Client> " + msgToSend +
        msgField.value = "";
    webSocket.onmessage = function(message) {
                divMsg.innerHTML += "Server> : " +;
    webSocket.onopen = function() {
        console.log("connection opened");
    webSocket.onclose = function() {
        console.log("connection closed");
    webSocket.onerror = function wserror(message) {
        console.log("error: " + message);

        .addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {

Java config

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

public class MyWebConfig implements WebSocketConfigurer {

  public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
      registry.addHandler(new MyHandler(), "/myHandler")

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

mvn tomcat7:run-war


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

    See Also