WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Spring Boot & Hibernate · Expert · question 77 of 100

How can you use WebSockets with Spring Boot to enable real-time communication between clients and servers?

📕 Buy this interview preparation book: 100 Spring Boot & Hibernate questions & answers — PDF + EPUB for $5

WebSockets is a protocol that allows bidirectional communication between clients and servers over a single, long-lived connection. In a Spring Boot application, we can use the Spring WebSocket module to implement WebSockets functionality.

Here are the steps to use WebSockets with Spring Boot:

Add the necessary dependencies to the pom.xml file:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-websocket</artifactId>
    </dependency>

Create a WebSocket configuration class that extends AbstractWebSocketMessageBrokerConfigurer:

    @Configuration
    @EnableWebSocketMessageBroker
    public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
        
        @Override
        public void configureMessageBroker(MessageBrokerRegistry registry) {
            registry.enableSimpleBroker("/topic");
            registry.setApplicationDestinationPrefixes("/app");
        }
        
        @Override
        public void registerStompEndpoints(StompEndpointRegistry registry) {
            registry.addEndpoint("/ws").withSockJS();
        }
    }

This class enables WebSocket message handling, configures message broker to relay messages to subscribed clients and sets up an endpoint that clients can use to establish a WebSocket connection.

Create a WebSocket controller class that handles WebSocket messages:

    @Controller
    public class WebSocketController {
        
        @MessageMapping("/hello")
        @SendTo("/topic/greetings")
        public Greeting greeting(HelloMessage message) {
            return new Greeting("Hello, " + message.getName() + "!");
        }
        
        @MessageExceptionHandler
        @SendToUser("/queue/errors")
        public String handleException(Throwable exception) {
            return exception.getMessage();
        }
    }

This class uses the @MessageMapping annotation to map incoming WebSocket messages to handler methods. The @SendTo annotation is used to specify the destination to which the response message will be sent.

Create a simple HTML page with JavaScript to establish a WebSocket connection and send/receive messages:

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket Example</title>
    <script src="/webjars/jquery/jquery.min.js"></script>
    <script src="/webjars/sockjs-client/sockjs.min.js"></script>
    <script src="/webjars/stomp-websocket/stomp.min.js"></script>
    <script>
        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 = \$("\#name").val();
            stompClient.send("/app/hello", {}, JSON.stringify({ 'name': name }));
        }

        function showGreeting(message) {
            \$("\#greetings").append("<tr><td>" + message + "</td></tr>");
        }
    </script>
</head>
<body>
    <div>
        <label for="name">Name:</label>
        <input type="text" id="name">
        <button onclick="sendName()">Send</button>
    </div>
    <table id="greetings">
    </table>
    <button onclick="connect()">Connect</button>
    <button onclick="disconnect()">Disconnect</button>
</body>
...
Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Spring Boot & Hibernate interview — then scores it.
📞 Practice Spring Boot & Hibernate — free 15 min
📕 Buy this interview preparation book: 100 Spring Boot & Hibernate questions & answers — PDF + EPUB for $5

All 100 Spring Boot & Hibernate questions · All topics