前端通过STOMP over websocket与spring后端通信,需引入sockjs-client和stompjs库;首先配置Spring WebSocket支持STOMP,定义端点如/ws、消息代理前缀/topic及应用前缀/app;前端使用SockJS连接/ws,通过Stomp.over建立STOMP客户端,连接成功后订阅/topic/greetings主题;调用stompClient.send(“/app/hello”, {}, json.stringify(data))发送消息至后端@Controller类的@MessageMapping方法;后端处理后通过@SendTo广播到/topic/greetings,所有订阅者接收并更新页面;页面卸载时应调用disconnect避免资源泄漏。关键点包括跨域配置、路径一致性、消息格式匹配。

前端通过javaScript调用Spring WebSocket服务,主要依赖浏览器原生的 WebSocket API 与后端建立双向通信。Spring 提供了基于 STOMP(Simple Text Oriented Messaging Protocol)的 WebSocket 支持,因此前端通常使用 STOMP over WebSocket 的方式来连接和交互。
1. 确保后端已配置 Spring WebSocket + STOMP
在开始 JS 调用前,确认你的 spring boot 项目已正确配置 WebSocket 服务。以下是最基本的配置示例:
添加依赖(maven):
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
启用 WebSocket 配置类:
@Configuration @EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint("/ws").setAllowedOriginPatterns("*").withSockJS(); } @Override public void configureMessageBroker(MessageBrokerRegistry registry) { registry.setApplicationDestinationPrefixes("/app"); registry.enableSimpleBroker("/topic", "/queue"); } }
创建消息处理 Controller:
@Controller public class WsController { @MessageMapping("/hello") @SendTo("/topic/greetings") public GreetingMessage greeting(HelloMessage message) throws Exception { Thread.sleep(1000); return new GreetingMessage("Hello, " + message.getName() + "!"); } }
上面配置说明:
- /ws 是 WebSocket 连接端点
- /app/hello 是客户端发送消息的目标路径
- /topic/greetings 是广播消息的订阅主题
2. 前端引入 STOMP.js 并连接 WebSocket
由于原生 WebSocket 不支持 STOMP 协议,需引入 stomp.js 或 @stomp/stompjs 库。
安装 stompjs(推荐使用 npm):
npm install @stomp/stompjs sockjs-client
或直接使用 CDN 引入:
<script src=”https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js”></script>
<script src=”https://cdn.jsdelivr.net/npm/@stomp/stompjs@7.0.0/bundles/stomp.umd.min.js”></script>
javascript 连接并使用 STOMP:
const socket = new SockJS('/ws'); const stompClient = Stomp.over(socket); stompClient.connect({}, function(frame) { console.log('Connected: ' + frame); // 订阅 /topic/greetings 主题 stompClient.subscribe('/topic/greetings', function(greeting) { const message = JSON.parse(greeting.body); console.log('Received: ' + message.content); // 更新页面 DOM document.getElementById("output").innerhtml += "<br>" + message.content; }); }, function(error) { console.error('STOMP connection error:', error); });
3. 发送消息到 Spring 后端
连接成功后,可通过 stompClient.send() 向后端发送消息。
示例:发送消息触发 /app/hello
function sendMessage() { const msg = { name: "张三" }; stompClient.send("/app/hello", {}, JSON.stringify(msg)); }
HTML 示例按钮:
<button onclick=”sendMessage()”>发送消息</button>
<div id=”output”></div>
点击按钮后,前端发送消息 → Spring 处理 → 广播到 /topic/greetings → 所有订阅者收到响应。
4. 处理断开连接与错误
建议在页面卸载时关闭连接,避免资源浪费。
window.onbeforeunload = function() { if (stompClient && stompClient.connected) { stompClient.disconnect(); } };
也可以监听网络中断、重连等状态,增强健壮性。
基本上就这些。只要后端配置好 STOMP 端点,前端用 stomp.js 连接、订阅、发消息,就能实现实时双向通信。不复杂但容易忽略细节,比如跨域、路径前缀、消息格式等,务必核对一致。