Spring Boot系列20 Spring Websocket实现向指定的用户发送消息

本文详细介绍了如何在Spring Boot应用中利用WebSocket实现向特定用户发送消息,包括实现登录功能、重写Principal、配置WebSocket及测试过程。通过登录验证、自定义Principal和消息发送,确保消息仅发送给指定用户。
摘要由CSDN通过智能技术生成

概述

不同上文Spring Boot系列十七 Spring Boot 集成 websocket,使用RabbitMQ做为消息代理,本文我们介绍通过Spring websocket实现向特定的用户发送消息。
本文的内容如下:
1. 首先实现简单的登录功能,这里向特定用户发送消息的必要条件
2. 用户登录系统后,才可以登录websocket,并重写MyPrincipal
3. 实现向特定用户发送消息的功能
4. 测试

首先实现简单的登录功能,这是向特定用户发送消息的必要条件

TestMQCtl:控制类
提供模拟登录,登录成功后转到websocket页面

   /**
     * 模拟登录     */
    @RequestMapping(value = "loginIn", method = RequestMethod.POST)
    public String login(HttpServletRequest request, @RequestParam(required=true) String name, String pwd){
        HttpSession httpSession = request.getSession();
        // 如果登录成功,则保存到会话中
        httpSession.setAttribute("loginName", name);
        return "websocket/sendtouser/ws-sendtouser-rabbitmq";
    }

    /**
     * 转到登录页面
     */
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String loginPage(){
        // 转到登录页面
        return "websocket/sendtouser/login";
    }

    /**
     * websocket页面
     * @return
     */
    @RequestMapping(value="/broadcast-rabbitmq/index")
    public String broadcastIndex(){
        return "websocket/sendtouser/ws-sendtouser-rabbitmq";
    }

login.jsp
简单的form表单,将请求提到loginIn,并转到ws-sendtouser-rabbitmq.jsp页面

<form action="loginIn" method="post">
    用户名:<input type="text" name="name" />
    <p>
        密码:<input type="password" name="password" />
    <p>
        <input type="submit" value="submit" />
</form>

ws-sendtouser-rabbitmq.jsp
连接websocket并订阅消息,这个jsp之前的文章已经介绍过了这里不详细描述。页面通过向/ws/icc/websocket启动websocket,然后订阅/user/topic/demo消息

<script type="text/javascript">
    var stompClient = null;

    function setConnected(connected) {
    
        document.getElementById('
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值