看了好多网上能搜到的spring mvc实现websocket的教程,总算淌出了坑,搞出来一个比较纯粹的实现websocket的Demo。
项目运行后,可以启动一个页面进行登录,然后在另一个页面中向服务器发送请求,服务器再向登录的页面推送消息。
启动页面登录:http://127.0.0.1:8080/jyl/login/jyl
login后是用户名,登录后页面效果如图
再使用另一页面向服务器发送请求,请求中包含数据,服务器将消息推送到已登录的页面中,已登录页面将刷新出内容
请求为:127.0.0.1:8080/jyl/msg/jyl/我要发消息了
msg后为:/用户名/消息内容
需要源码的请这里下载:https://download.csdn.net/download/jiyanglin/10972609
废话不多说,直接上代码。。。
maven依赖
下面这些就够了
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.1.9.RELEASE</version>
</dependency>
jsp页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncod