WebSockets enable two-way communication over a single, persistent connection, allowing for real-time, bidirectional data exchange between the client and server. Unlike traditional HTTP, which is request-response based, WebSocket communication allows for real-time, bi-directional communication between the client and the server. This makes WebSockets ideal for applications requiring immediate data updates, such as chat applications, gaming, collaborative editing, and real-time notifications. In this article, we'll explore how to use WebSocket with Spring Boot to build an interactive web application.
WebSocket in Spring Boot
WebSocket communication in Spring Boot involves using @Controller annotated classes to handle WebSocket connections. The communication protocol is defined using mappings that match client-side connections to server-side message-handling methods. A message broker is often utilized to manage message routing between clients.
The WebSocket workflow typically looks like this:
- Client Connection: The client sends a connection request to the server using the WebSocket protocol.
- Server Handshake: The server responds with the WebSocket handshake response and establishes the connection.
- Message Exchange: Once connected, the client and server can send messages to each other in real-time.
- Connection Termination: Either party can terminate the connection.
Implementation of Using WebSocket to Build an Interactive Web Application in Spring Boot
We'll build a simple chat application using WebSocket in a Spring Boot project.
Step 1: Set Up the Spring Boot Project
- Create a new Spring Boot project using IntelliJ IDEA with the following options:
- Name:
websocket-chat-app - Language: Java
- Type: Maven
- Packaging: Jar
- Name:
Click on the Next button.

Step 2: Add Dependencies
Add the following dependencies into the Spring Boot project.
- WebSocket
- Spring Web
- Spring Boot DevTools
- Thymeleaf
- Lombok
Click on the Create button.

Project Structure
Once created the project, the file structure will look like the below image.

Step 3: Configure Application Properties
Add the following property to src/main/resources/application.properties:
spring.application.name=websocket-chat-appStep 4: Configure WebSocket
Create the WebSocketConfig configuration class to register WebSocket endpoints:
WebSocketConfig.java
package com.gfg.websocketchatapp;
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 registerStompEndpoints(StompEndpointRegistry registry) {
// Define the WebSocket endpoint that the client will use to connect to the server
registry.addEndpoint("/chat").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
// Enable a simple in-memory message broker and set the destination prefixes
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
}
Explanation:
@EnableWebSocketMessageBroker: Enables WebSocket message handling with a message broker.registerStompEndpoints(): Registers the/chatendpoint for WebSocket connections and supports SockJS as a fallback option.configureMessageBroker(): Configures the message broker to route messages based on the destination prefixes/topicand/app."
Step 5: Create the Message Model
Create the Message class to define the structure of the messages:
Message.java
package com.gfg.websocketchatapp;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Message {
private String from;
private String text;
}
Step 6: Create the ChatController to Handle Messages
Create the ChatController class to handle incoming messages and broadcast them to connected clients:
ChatController.java
package com.gfg.websocketchatapp;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Controller;
@Controller
public class ChatController {
@MessageMapping("/chat.sendMessage")
@SendTo("/topic/public")
public Message sendMessage(Message message) {
return message;
}
}
Explanation:
@MessageMapping("/chat.sendMessage"): Maps incoming messages to the/chat.sendMessagedestination.@SendTo("/topic/public"): Sends the returned message to all subscribers of/topic/public.
Step 7: Main class
No changes are required in the main class.
package com.gfg.websocketchatapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WebsocketChatAppApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketChatAppApplication.class, args);
}
}
Step 8: Create the Web Page for Chat
Create the chat.html page to provide a simple chat interface:
src/main/resources/templates/chat.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebSocket Chat</title>
<link rel="stylesheet" href="/css/chat.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.5.0/sockjs.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
<script src="/js/chat.js"></script>
</head>
<body>
<div class="chat-container">
<h2>WebSocket Chat Application</h2>
<div id="chat-box" class="chat-box"></div>
<div class="input-container">
<input type="text" id="message" class="message-input" placeholder="Enter your message here..." />
<button id="send-button" class="send-button" onclick="sendMessage()">Send</button>
</div>
</div>
</body>
</html>
Step 9: Create the Stylesheet
Create chat.css to style the chat application:
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
color: #333;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
}
.chat-container {
background-color: #ffffff;
padding: 20px;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
width: 400px;
max-width: 100%;
}
h2 {
color: #4CAF50; /* Light green primary color */
text-align: center;
margin-bottom: 20px;
}
.chat-box {
background-color: #f9f9f9;
border: 1px solid #e0e0e0;
padding: 10px;
border-radius: 5px;
height: 300px;
overflow-y: auto;
margin-bottom: 10px;
}
.input-container {
display: flex;
align-items: center;
}
.message-input {
flex: 1;
padding: 10px;
border: 1px solid #e0e0e0;
border-radius: 5px;
margin-right: 10px;
font-size: 16px;
}
.send-button {
background-color: #4CAF50; /* Light green primary color */
color: #fff; /* White text */
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 16px;
transition: background-color 0.3s ease;
}
.send-button:hover {
background-color: #45a049; /* Slightly darker green on hover */
}
.message {
margin-bottom: 10px;
padding: 5px 10px;
border-radius: 5px;
width: fit-content;
max-width: 80%;
word-wrap: break-word;
}
.message.sent {
background-color: #dfffd6; /* Light green for sent messages */
align-self: flex-end;
}
.message.received {
background-color: #e0e0e0; /* Light gray for received messages */
align-self: flex-start;
}
Step 10: Create the Chat JavaScript file
Create the chat JavaScript file and this script will manage the WebSocket connections and handling the sending/receiving messages.
src/main/resources/static/js/chat.js
var stompClient = null;
function connect() {
var socket = new SockJS('/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}, function (frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/public', function (message) {
showMessage(JSON.parse(message.body));
});
});
}
function sendMessage() {
var messageContent = document.getElementById("message").value;
if (messageContent) {
var message = {
from: "User",
text: messageContent
};
stompClient.send("/app/chat.sendMessage", {}, JSON.stringify(message));
document.getElementById("message").value = '';
}
}
function showMessage(message) {
var chatBox = document.getElementById("chat-box");
var messageElement = document.createElement("p");
messageElement.textContent = message.from + ": " + message.text;
chatBox.appendChild(messageElement);
}
connect();
Explanation:
- SockJS: The JavaScript library that provides the WebSocket-like object functionality.
- STOMP: The simple text-oriented messaging protocol and it often used with the WebSocket.
- connect(): It establishes the WebSocket connection to the /chat endpoint.
- sendMessage(): It sends the message to the server via the /app/chat.sendMessae endpoint.
- showMessage(): It display the received message in the chat box.
pom.xml file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.gfg</groupId>
<artifactId>websocket-chat-app</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>websocket-chat-app</name>
<description>websocket-chat-app</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 10: Run the Application
Once completed the project, it will start and run at port 8080. We can run the spring boot application using the IntelliJ IDEA or with the following Maven command.
mvn spring-boot:runOutput:

Step 11: Accessing the Chat Page
Open the web browser and navigate to the below URL.
http://localhost:8080/chat.htmlVideo Output:
Enter the message in the input box and click the send button. We should see the message appear in the chat box and it will also broadcast to the any other open connections of the chat application.