需求
- 实现用户登录功能
- 展示用户好友列表功能
- 实现用户历史消息展示
- 实现单聊信息和群聊信息
效果展示
- 用户登录
- 好友列表展示
- 历史消息展示
- 聊天
代码实现
说明:Springboot项目,页面是用 thymeleaf 整合的。
- maven依赖
<dependencies>
<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-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
</dependencies>
- application.yml
spring:
thymeleaf:
cache: false
suffix: .html
- resource/templates目录下,创建页面
1) login.html,点击登录调用了/user/login接口
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
</head>
<body>
<div id="login" class="form-wrapper">
<div class="header">
登录
</div>
</div>
<div>
<span style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></span>
</div>
<form action="/user/login" method="post">
<div >
<div >
<input th:type="text" th:name="username" placeholder="username">
</div>
<div >
<input th:type="password" th:name="password" placeholder="password" >
</div>
</div>
<div class="action" onclick="document.getElementById('lick1').click()">
<div class="btn">
确认
</div>
</div>
<input th:type="submit" id="lick1">
</form>
</div>
</body>
</html>
2)chat.html,聊天主页面
[1]、退出登录按钮,调用了logout接口,把session中的token值清除了
[2]、好友列表,在跳转到chat页面的时候,调用了getUserList并且把用户列表数据注入到模型中,界面展示出来
[3]、连接websocket,调用了connectWebSocket()函数,调用了后端 websocket端点的onOpen方法
[4]、断开连接,调用了后台的onClose方法
[5]、发送消息,调用了后台的onMessage方法
[6]、查看历史消息,调用了后台的/history方法
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<html>
<head>
<meta charset="UTF-8">
<title>My WebSocket</title>
<style>
#message {
margin-top: 40px;
border: 1px solid gray;
padding: 20px;
}
</style>
</head>
<body>
<div>
用户token值:<span id="token" style="color: #ff0000" th:text="${session.token}"></span> <div> <a href="/logout">退出登录</a></div>
</div>
<div>
我的好友列表:<br/>
<table border="1">
<thead>
</thead>
<tbody>
<tr th:each="user:${
users}" style="color: blue">
<a th:οnclick="aClick([[${
user}]]);" th:text="${
user}" style="color: blue"> </a><br/>
</tr>
</tbody>
</table>
</div>
昵称:<input type="text" id="nickname" th:value="${
session.token}"/>
<button οnclick="conectWebSocket()">连接WebSocket</button>
<button οnclick="closeWebSocket()">断开连接</button>
<hr/>
<br/>
消息:<input id="text" type="text"/>
发送给谁: <input id="toUser" type="text">
<button οnclick="send()">