codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🍃

Spring Boot

32 / 62 topics
31Introduction to WebSockets in Spring Boot32Using STOMP over WebSockets
Tutorials/Spring Boot/Using STOMP over WebSockets
🍃Spring Boot

Using STOMP over WebSockets

Updated 2026-04-20
3 min read

Introduction

In this tutorial, we will explore how to use Simple (STOMP) over WebSocket for real-time communication in a Spring Boot application. STOMP is a simple text-based protocol that provides message headers and allows you to send messages to specific destinations. It is commonly used with WebSockets to enable real-time messaging between clients and servers.

Prerequisites

Before we begin, ensure you have the following:

  • Basic knowledge of Spring Boot.
  • Java Development Kit (JDK) 8 or higher installed.
  • An Integrated Development Environment (IDE) like IntelliJ IDEA or Eclipse.
  • Node.js and npm for running frontend applications.

Setting Up a Spring Boot Project

First, create a new Spring Boot project using Spring Initializr. Choose the following options:

  • Project: Maven Project
  • Language: Java
  • Spring Boot: Latest stable version
  • Project Metadata:
    • Group: com.example
    • Artifact: stomp-websocket-demo
    • Name: stomp-websocket-demo
    • Description: Demo project for using STOMP over WebSockets in Spring Boot
    • Package name: com.example.stompwebsocketdemo
  • Packaging: Jar
  • Java: 8 or higher

Add the following dependencies:

  • Spring Web
  • Thymeleaf (for frontend)
  • Spring WebSocket
  • Spring Messaging

Click "Generate" to download the project files, then import them into your IDE.

Configuring STOMP and WebSocket in Spring Boot

1. Configure WebSocket Message Broker

Create a configuration class to set up the WebSocket message broker:

package com.example.stompwebsocketdemo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry;
import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer;

@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {

    @Override
    public void configureMessageBroker(MessageBrokerRegistry config) {
        // Enable a simple memory-based message broker to relay messages between connected clients
        config.enableSimpleBroker("/topic");
        // Define the prefix for application destinations
        config.setApplicationDestinationPrefixes("/app");
    }

    @Override
    public void registerStompEndpoints(StompEndpointRegistry registry) {
        // Register STOMP endpoint "/ws" and enable SockJS fallback options
        registry.addEndpoint("/ws").withSockJS();
    }
}

2. Create a Message Controller

Create a controller to handle messages sent from clients:

package com.example.stompwebsocketdemo.controller;

import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;

@Controller
public class MessageController {

    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    public String greeting(String message) throws Exception {
        Thread.sleep(1000); // Simulate delay
        return "Hello, " + message + "!";
    }
}

Frontend Setup

1. Create a Simple HTML Page

Create a new directory src/main/resources/templates and add an HTML file index.html:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>STOMP over WebSocket Demo</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
    <script type="text/javascript">
        var stompClient = null;

        function connect() {
            var socket = new SockJS('/ws');
            stompClient = Stomp.over(socket);
            stompClient.connect({}, function (frame) {
                console.log('Connected: ' + frame);
                stompClient.subscribe('/topic/greetings', function (greeting) {
                    showGreeting(JSON.parse(greeting.body).content);
                });
            });
        }

        function disconnect() {
            if (stompClient !== null) {
                stompClient.disconnect();
            }
            console.log("Disconnected");
        }

        function sendName() {
            var name = document.getElementById('name').value;
            stompClient.send("/app/hello", {}, JSON.stringify({'name': name}));
        }

        function showGreeting(message) {
            var response = document.getElementById('response');
            var p = document.createElement('p');
            p.style.wordWrap = 'break-word';
            p.appendChild(document.createTextNode(message));
            response.appendChild(p);
        }
    </script>
</head>
<body onload="connect();">
<noscript><h2 style="color: #ff0000">Seems your browser doesn't support Javascript! WebSocket relies on Javascript being enabled.</h2></noscript>

<div>
    <div>
        <label for="name">What is your name?</label><br/>
        <input type="text" id="name"/>
        <button onclick="sendName();">Send</button>
        <p id="response"></p>
    </div>
</div>
</body>
</html>

2. Run the Application

Run your Spring Boot application using your IDE or by executing:

mvn spring-boot:run

Navigate to http://localhost:8080 in your browser. You should see a simple form where you can enter your name and send it to the server. The server will respond with a greeting message, which will be displayed on the page.

Best Practices

  1. Security: Always secure WebSocket endpoints using Spring Security to prevent unauthorized access.
  2. Error Handling: Implement proper error handling for WebSocket connections and messages.
  3. Scalability: For production applications, consider using a message broker like RabbitMQ or ActiveMQ instead of the simple in-memory broker.
  4. Performance: Optimize your message payloads and ensure efficient use of resources to handle high volumes of real-time data.

Conclusion

In this tutorial, we have learned how to set up STOMP over WebSockets in a Spring Boot application for real-time communication. This setup allows you to build interactive applications with features like live updates and instant messaging. By following the best practices outlined above, you can ensure your application is secure, scalable, and performant.

Feel free to explore more advanced topics such as integrating with message brokers, handling complex message structures, and implementing robust error handling mechanisms to enhance your real-time communication capabilities in Spring Boot applications.


PreviousIntroduction to WebSockets in Spring BootNext OAuth2 Basics in Spring Boot

Recommended Gear

Introduction to WebSockets in Spring BootOAuth2 Basics in Spring Boot