SpringBoot搭建WebSocket初始化

这篇具有很好参考价值的文章主要介绍了SpringBoot搭建WebSocket初始化。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

1.java后端的maven添加websocket依赖

<!--        websocket依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
        <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>

2.实例化ServerEndpointExporter对象,

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

3.创建一个类,该类的功能是提供websocket服务
注意:这里填写的map的key是uuid变量,不是"uuid" websocket_map.get(uuid);

@Component
@ServerEndpoint("/ws/login/{uuid}")
public class LoginWebSocket {
    private Session session;
    private static final ConcurrentMap<String,LoginWebSocket> websocket_map = new ConcurrentHashMap<>();
    @OnOpen
    public void onOpen(@PathParam("uuid") String uuid, Session session) {
        this.session = session;
        websocket_map.put(uuid,this);
        System.out.println("有新连接加入!当前在线人数为" + websocket_map.size());
    }
    @OnClose
    public void onClose(@PathParam("uuid") String uuid,Session session) throws IOException {
        websocket_map.remove(uuid);
        session.close();
        System.out.println("有一连接关闭!当前在线人数为" + websocket_map.size());
    }

    //发送消息
    @OnMessage
    public void onMessage(Session session,String message) throws IOException {
        String uuid = generateUUID();
        session.getBasicRemote()
                .sendText(uuid);
    }
    //产生uuid
    private String generateUUID(){
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }
    private void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
    }
    public static void sendMessage(String uuid,String message) throws IOException {
        LoginWebSocket qrcodeWebsocket = websocket_map.get(uuid);
        if(qrcodeWebsocket != null){
            qrcodeWebsocket.sendMessage(message);
        }
    }

}


接下来需要控制器进行页面的跳转

@Controller
public class LoginController {
    @GetMapping("/")
    public String loginPage(){
        return "login";
    }
    @GetMapping("/generateUUID")
    @ResponseBody
    public String generateUUID(){
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }
    @GetMapping("/confirmLogin/{uuid}")
    public String confirmLoginPage(@PathVariable("uuid") String uuid, Model model){
        model.addAttribute("uuid",uuid);
        return "confirmLogin";
    }
    @GetMapping("/loginSuccess/{uuid}")
    public String loginSuccess(@PathVariable("uuid") String uuid) throws IOException {
            LoginWebSocket.sendMessage(uuid,"确认登录");
            return "loginSuccess";
    }
}

前端测试发起请求获取uuid,生成二维码,连接websocket
创建了一个登录html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录</title>
    <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
    <div class="container mt-5">
        <div class="row">
            <div class="col-md-6 offset-md-3">
                <div class="card">
                    <div class="card-body text-center" style="margin: 1px auto">
                        <div id="qrcode"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
<script src="https://cdn.jsdelivr.net/gh/davidshimjs/qrcodejs/qrcode.min.js"></script>
    <script>
        var qr = new QRCode(document.getElementById("qrcode"),{
            text:"",
            width:128,
            height:128
        })
        //页面加载时,发起请求获取uuid
        fetch("/generateUUID").then(response => response.text()).then(uuid => {
            var confirmUrl = "http://" + window.location.host + "/confirmLogin/" + uuid
            console.log("uuid",uuid);
            qr.makeCode(confirmUrl);
            //连接websocket
            var socket = new WebSocket("ws://" + window.location.host + "/ws/login/" + uuid)
            socket.onopen = function (event) {
                console.log("websocket连接已经打开");
            }
            socket.onmessage = function (event) {
                var message = event.data;
                console.log(message);
                if (message === "确认登录"){
                    window.location.href = "/loginSuccess/"+ uuid
                }
            }
            socket.onclose = function (event) {
                console.log("websocket连接已经关闭");
            }
        })
    </script>
</html>

一个确认登录页面,注意这里由于使用了thymeleaf的th元素,需要引入约束空间xmlns:th=“http://www.thymeleaf.org”

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>确认页面</title>
    <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
<div class="container mt-5">
    <div class="row">
        <div class="col-md-6 offset-md-3">
            <div class="card">
                <div class="card-body text-center">
                    <h1>请确认登录</h1>
                    <form th:action="@{'/loginSuccess/'+${uuid}}">
                        <button id="confirmButton" class="btn btn-primary mt-3">确认登录</button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
</html>

一个登录成功页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>登录成功</title>
  <link rel="stylesheet" href="bootstrap.css">
</head>
<body>
后台界面
<a href="/" class="btn btn-primary mt-3">退出</a>
</body>
</html>

将bootstrap.css放在static文件下

将下面这个路径粘贴到浏览器获得bootstrap.css源码,在static文件下新建bootstrap.css文件,粘贴进去
https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css

运行结果:
浏览器输入http://192.168.xx.xx(自己的ip):8888/
SpringBoot搭建WebSocket初始化,java,spring boot,websocket,后端

手机扫码,出现确认登录按钮,点击确认登录,跳转到登录成功页面,同时PC端也跳转到登录成功页面。文章来源地址https://www.toymoban.com/news/detail-626417.html

到了这里,关于SpringBoot搭建WebSocket初始化的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • spring事物初始化过程分析

    1.注入4个bd 2.执行 org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessBeforeInstantiation 逻辑分析:遍历所有的bd: 获取beanname-判断beanname是否有长度并且没有被处理过-是否遍历放入advisedBeans- 是否是基础类-是否该跳过  4大基础类 3.执行org.springframework.aop.framework.autoprox

    2024年02月02日
    浏览(24)
  • Spring Bean初始化方式

    对于Spring Bean 的初始化归纳了下,主要可以归纳一下三种方式 @PostConstruct 标注方法 自定义初始化方法 实现 initializingBean 接口的afterPropertiesSet()方法 执行顺序:Constructor @PostConstruct InitializingBean init-method @PostConstruct是Java自己的注解 假设类UserController有个成员变量UserService被**

    2024年02月01日
    浏览(35)
  • Spring Boot 系统初始化器详解

    Spring Boot 3.x系列文章 Spring Boot 2.7.8 中文参考指南(一) Spring Boot 2.7.8 中文参考指南(二)-Web Spring Boot 源码阅读初始化环境搭建 Spring Boot 框架整体启动流程详解 Spring Boot 系统初始化器详解 Spring Boot 有多种加载自定义初始化器的方法: 1、创建一个实现ApplicationContextInitializer接口的

    2024年02月11日
    浏览(38)
  • Spring初始化顺序- RabbitMq 无法自动创建队列

    项目中使用了RabbitMq, 并配置了自动创建topic, exchange,binding 等,但是通过测试发现,有一个队列始终无法自动创建,在对spring 源码以及rabbitmq 源码debug 后发现问题。 rabbitmq 配置了两套环境 , 以下为代码示例 Queue, Exchange, Binding 自动生成配置: 通过运行项目,发现队列,交换机

    2024年02月13日
    浏览(34)
  • 【2】Spring手写模拟-依赖注入、初始化、AOP

    首先回顾一下我们之前的流程 ApplicationContext 构造方法 获取Spring配置类 @ComponetScan 注解,扫描包,获取其路径及其对应的字节码文件 逐个扫描字节码文件 利用字节码文件获取类,查看是否包含 @Componet 注解,并获取或者生成 BeanName 获取 BeanDefinition ,包含其类和类型(单例,多

    2024年02月16日
    浏览(37)
  • 从零开始 Spring Boot 37:初始化 ApplicationContext

    图源:简书 (jianshu.com) 从前文可以知道,作为 Ioc 容器的 ApplicationContext,需要进行一系列步骤来初始化以最终就绪(对于 Web 应用来说就是可以提供Http服务)。 这些步骤大概可以分为以下内容: 准备上下文关联的 Environment 。 初始化 ApplicationContext( ApplicationContextInitializers

    2024年02月08日
    浏览(34)
  • SpringBoot启动时的几种初始化操作

    1、静态代码块 static静态代码块,在类加载的时候即自动执行。 2、构造方法 在对象初始化时执行。执行顺序在static静态代码块之后。 3、通过注解@PostConstruct实现 @PostConstruct注解使用在方法上,它可以被用来标注一个 非静态的 void 方法 ,这个方法会在该类被 Spring 容器初始化

    2024年02月09日
    浏览(36)
  • Spring 填充属性和初始化流程源码剖析及扩展实现

    在上一篇博文 讲解 Spring 实例化的不同方式及相关生命周期源码剖析 介绍了 Spring 实例化的不同方式,本文主要围绕实例化过后对象的填充属性和初始化过程进行详细流程剖析 回顾前言知识,doCreateBean-createBeanInstance,通过 Supplier 接口、FactoryMethod、构造函数反射 invoke,创建

    2024年02月06日
    浏览(33)
  • 【SpringBoot系列】初始化机制几种实现策略模式

    前言 Spring Boot是一个用于快速构建基于Spring框架的应用程序的开发框架。 它提供了许多便捷的功能和特性,使得开发者可以更加高效地开发和部署应用程序。 其中,初始化策略是Spring Boot中一个重要的概念,它决定了应用程序在启动时如何进行初始化和配置。 本文将介绍S

    2024年02月07日
    浏览(32)
  • 一文详解 springboot 项目启动时异步执行初始化逻辑

    你知道的越多,你不知道的越多 点赞再看,养成习惯 如果您有疑问或者见解,欢迎指教: 企鹅:869192208 前言 前面的工作中,为了提高地区数据的响应时间,需要加载全国区划数据到 redis 中缓存起来,这个过程希望在项目时启动。 由于初始化全国区划到 redis 中这个过程是

    2024年02月12日
    浏览(36)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包