在spring boot中使用webSocket组件(二)
该篇演示如何使用websocket创建一对一的聊天室,废话不多说,我们马上开始!
一.首先先创建前端页面,代码如下图所示:
1.login.html
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<meta charset="UTF-8" />
<head>
<title>登陆页面</title>
</head>
<body>
<div th:if="${param.error}">
无效的账号和密码
</div>
<div th:if="${param.logout}">
你已注销
</div>
<form th:action="@{/login}" method="post">
<div><label> 账号 : <input type="text" name="username"/> </label></div>
<div><label> 密码: <input type="password" name="password"/> </label></div>
<div><input type="submit" value="登陆"/></div>
</form>
</body>
</html>
2.chat.html
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org">
<meta charset="UTF-8" />
<head>
<title>Home</title>
<script th:src="@{sockjs.min.js}"></script>
<script th:src="@{stomp.min.js}"></script>
<script th:src="@{jquery.js}"></script>
</head>
<body>
<p>
聊天室
</p> <form id="wiselyForm">
<textarea rows="4" cols="60" name="text"></textarea>
<input type="submit"/>
</form> <script th:inline="javascript">
$('#wiselyForm').submit(function(e){
e.preventDefault();
var text = $('#wiselyForm').find('textarea[name="text"]').val();
sendSpittle(text);
}); var sock = new SockJS("/endpointChat"); //1
var stomp = Stomp.over(sock);
stomp.connect('guest', 'guest', function(frame) {
stomp.subscribe("/user/queue/notifications", handleNotification);//2
}); function handleNotification(message) {
$('#output').append("<b>Received: " + message.body + "</b><br/>")
} function sendSpittle(text) {
stomp.send("/chat", {}, text);//3
}
$('#stop').click(function() {sock.close()});
</script> <div id="output"></div>
</body>
</html>
二.在spring boot中创建spring Security,代码如下图所示:
(spring Security是一个能够为基于Spring的企业应用系统提供声明式的安全访问控制解决方案的安全框架。通俗地讲就是为你的系统提供安全权限,不是什么人都能访问你的系统,只有有权限的人才行!)
1.先在pom.xml中引入spring Security的依赖,代码如下图所示:
<!--spring-boot-security安全框架-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
2.WebSecurityConfig类
package com.wisely.ch7_6; import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; @Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/","/login").permitAll()//1根路径和/login路径不拦截
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login") //2登陆页面
.defaultSuccessUrl("/chat") //3登陆成功转向该页面
.permitAll()
.and()
.logout()
.permitAll();
}
//
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("dzz").password("dzz").roles("USER")//这里两个是分别账号和密码(账号:dzz密码:dzz)
.and()
.withUser("zbb").password("zbb").roles("USER");//这里两个是分别账号和密码(账号:zbb密码:zbb)
}
//5忽略静态资源的拦截
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/static/**");
}
}
3.在原来的WsController类中增加聊天的方法handleChat(),代码如下图所示:
@Autowired
private SimpMessagingTemplate messagingTemplate;// @MessageMapping("/chat")
public void handleChat(Principal principal, String msg) { //
if (principal.getName().equals("dzz")) {//
messagingTemplate.convertAndSendToUser("zbb",
"/queue/notifications", principal.getName() + "-send:"
+ msg);
} else {
messagingTemplate.convertAndSendToUser(dzz",
"/queue/notifications", principal.getName() + "-send:"
+ msg);
}
}
}
(1)SimpMessagingTemplate用于向浏览器发送信息。
(2)在spring mvc中,principal包含了登录用户的信息,在这里我们直接用。
(3)这里是一段写死的代码,如果登录的用户是dzz,那就将消息发送给zbb,大家根据自己的需求进行修改。通过convertAndSendToUser()方法进行发送,第一个参数是信息接收的目标,第二个参数是要发送的地址,第三个参数是要发送的信息。
4.在原来的WebSocketConfig类中再创建一个节点(endpoint)和代理(MessageBroker),代码如下图所示:
package com.wisely.ch7_6; import org.springframework.context.annotation.Configuration;
import org.springframework.messaging.simp.config.MessageBrokerRegistry;
import org.springframework.web.socket.config.annotation.AbstractWebSocketMessageBrokerConfigurer;
import org.springframework.web.socket.config.annotation.EnableWebSocketMessageBroker;
import org.springframework.web.socket.config.annotation.StompEndpointRegistry; @Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{ @Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/endpointWisely").withSockJS();
registry.addEndpoint("/endpointChat").withSockJS();//
} @Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
registry.enableSimpleBroker("/queue","/topic"); //
} }
5.在原来的WebMvcConfig类中加入/login和/chat的映射,如下图:
registry.addViewController("/login").setViewName("/login");
registry.addViewController("/chat").setViewName("/chat");
三.效果演示
用两个账号登录后,如图所示:
dzz发送消息后zbb就能收到消息了,如图所示:
websocket的一对一聊天演示到此就结束了,如有错误,欢迎指正。
在spring boot中使用webSocket组件(二)的更多相关文章
- 在spring boot中使用webSocket组件(一)
最近在项目中使用到了spring的webSocket组件,在这里和大家分享下,如有错误,欢迎大家指正. 在这里我使用的IDE工具是Intellij idea,框架是spring boot.spring ...
- 禁用 Spring Boot 中引入安全组件 spring-boot-starter-security 的方法
1.当我们通过 maven 或 gradle 引入了 Spring boot 的安全组件 spring-boot-starter-security,Spring boot 默认开启安全组件,这样我们就 ...
- Spring Boot中使用Websocket搭建即时聊天系统
1.首先在pom文件中引入Webscoekt的依赖 <!-- websocket依赖 --> <dependency> <groupId>org.springfra ...
- Spring Boot 中使用 WebSocket 实现一对多聊天及一对一聊天
为什么需要WebSocket? 我们已经有了http协议,为什么还需要另外一个协议?有什么好处? 比如我想得到价格变化,只能是客户端想服务端发起请求,服务器返回结果,HTTP协议做不到服务器主动向客户 ...
- 学习Spring Boot:(二十三)Spring Boot 中使用 Docker
前言 简单的学习下怎么在 Spring Boot 中使用 Docker 进行构建,发布一个镜像,现在我们通过远程的 docker api 构建镜像,运行容器,发布镜像等操作. 这里只介绍两种方式: 远 ...
- (转)Spring Boot 2 (十):Spring Boot 中的响应式编程和 WebFlux 入门
http://www.ityouknow.com/springboot/2019/02/12/spring-boot-webflux.html Spring 5.0 中发布了重量级组件 Webflux ...
- Spring Boot 2 (十):Spring Boot 中的响应式编程和 WebFlux 入门
Spring 5.0 中发布了重量级组件 Webflux,拉起了响应式编程的规模使用序幕. WebFlux 使用的场景是异步非阻塞的,使用 Webflux 作为系统解决方案,在大多数场景下可以提高系统 ...
- Spring Boot开发之流水无情(二)
http://my.oschina.net/u/1027043/blog/406558 上篇散仙写了一个很简单的入门级的Spring Boot的例子,没啥技术含量,不过,其实学任何东西只要找到第一个突 ...
- 【定时任务】Spring Boot 中如何使用 Quartz
这篇文章将介绍如何在Spring Boot 中使用Quartz. 一.首先在 pom.xml 中添加 Quartz 依赖. <!-- quartz依赖 --> <dependency ...
随机推荐
- Java 8特性尝鲜:新新IO
Java 8特性尝鲜:新新IO 在这个专题前面的文章中,我们已经看到,使用Java8的lambda表达式对现有的JDK1.2 I/O库的提升,主要是可以使用lambda表达式来构造java.io.Fi ...
- WPF 动态加载主题由zip
经典主题的方式 主题战略 加载速度 本机支持 (不需要额外的代码) 支持代码为主题 (捆绑代码 & 资源成单独的文件) 支持资源层次结构中导航 动态加载 动态卸载 轻松地编辑和编译 (不需要安 ...
- js中Object.defineProperty()和defineProperties()
在介绍js中Object.defineProperty()和defineProperties()之前,我们了解下js中对象两种属性的类型:数据属性和访问器属性. 数据属性 数据属性包含一个数据的位置, ...
- JAVA基础之基本类型包装类、System类、Math类、Arrays类及大数据运算
个人理解: 为了方便运算及调用一些方法,我们需要将基本类型的数值转换为对象:不过转换的时候需要特别注意好它们的类型到底是什么,需要调用方法的类名是哪个!特别注意是Byte常量池的相关问题(==):gc ...
- 1008 选数 2002年NOIP全国联赛普及组
1008 选数 2002年NOIP全国联赛普及组 时间限制: 1 s 空间限制: 128000 KB 题目等级 : 黄金 Gold 题解 查看运行结果 题目描述 Description ...
- Beta_版本发布
学号 姓名 201731041215 王阳 201731062302 鲜雨珂 201731062128 邓捷 201731062305 周蓉 201731062131 龙继平 201731062304 ...
- Yii2.0数据库缓存依赖发布的使用理解
对于产品中经常需要生成一些缓存类的东西,比如系统基础配置,商品分类等,每次修改调整后都要手动进行缓存发布,是不是非常麻烦!这时候Yii2.0的缓存依赖发布就起到至关重要的作用了!现将主要的使用流程介绍 ...
- Android商城开发系列(五)—— 商城首页回到顶部和搜索框布局实现
今天我们来开发商城的首页[输入搜索框]布局和点击右下角图片回到顶部的效果 搜索功能在App中很常见,尤其是在商城类的项目当中,一般都会提供很强大的搜索功能,App的搜索布局一般都是在App的顶部,如下 ...
- 如何从桌面程序向浏览器传递cookie或自定义header
类似问题 从c#程序启动ie并传递cookie 打开默认浏览器并传递cookie 打开一个web浏览器使用c#应用程序并添加请求头 猜想 从wpf程序打开默认浏览器并定位到一个url ,并且向这个ur ...
- Html.Action Html.RenderAction Html.Partial Html.RenderPartial Url.Action Html.ActionLink 大括号和小括号区别
在查阅了一些资料后,结论如下: Action 是以mvchtmlstring的方式返回一个结果,RenderAction 无返回值,速度上action慢于RenderAction partial和Re ...