定向发送消息涉及到用户,需要引入Spring Security相关内容。
1.添加Spring Security,websocket和thymeleaf等依赖
<dependency>
<groupId>org
.springframework
.boot
</groupId
>
<artifactId>spring
-boot
-starter
-web
</artifactId
>
</dependency
>
<dependency>
<groupId>org
.springframework
.boot
</groupId
>
<artifactId>spring
-boot
-starter
-web
</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
-websocket
</artifactId
>
</dependency
>
<dependency>
<groupId>org
.springframework
.boot
</groupId
>
<artifactId>spring
-boot
-starter
-security
</artifactId
>
</dependency
>
2.配置Spring Security
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http
) throws Exception
{
http
.authorizeRequests()
.antMatchers("/","/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/chat")
.permitAll()
.and()
.logout()
.permitAll();
}
@Override
protected void configure(AuthenticationManagerBuilder auth
) throws Exception
{
auth
.inMemoryAuthentication()
.passwordEncoder(new BCryptPasswordEncoder()).withUser("user1").password(new BCryptPasswordEncoder().encode("123")).roles("USER")
.and()
.passwordEncoder(new BCryptPasswordEncoder()).withUser("user2").password(new BCryptPasswordEncoder().encode("123")).roles("USER");
}
@Override
public void configure(WebSecurity web
) throws Exception
{
web
.ignoring().antMatchers("/resources/static/**");
}
}
3.配置WebSocket
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void registerStompEndpoints(StompEndpointRegistry registry
){
registry
.addEndpoint("/endpointChat").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry
){
registry
.enableSimpleBroker("queue", "/topic");
}
}
4.控制器
@Controller
public class WsController {
@Autowired
private SimpMessagingTemplate messagingTemplate
;
@MessageMapping("/chat")
public void handleChat(Principal principal
, String msg
){
if(principal
.getName().equals("user1")){
messagingTemplate
.convertAndSendToUser("user2", "/queue/notifications", principal
.getName() + "-send:" + msg
);
}else {
messagingTemplate
.convertAndSendToUser("user1", "/queue/notifications", principal
.getName() + "-send:" + msg
);
}
}
}
5.登录页面和聊天页面
登录页面
<!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>
聊天页面
<!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="messageForm">
<textarea rows="4" cols="60" name="text"></textarea>
<input type="submit"/>
</form>
<script th:inline="javascript">
$('#messageForm').submit(function(e){
e.preventDefault();
var text = $('#messageForm').find('textarea[name="text"]').val();
sendSpittle(text);
});
var sock = new SockJS("/endpointChat");
var stomp = Stomp.over(sock);
stomp.connect('guest', 'guest', function(frame) {
stomp.subscribe("/user/queue/notifications", handleNotification);
});
function handleNotification(message) {
$('#output').append("<b>Received: " + message.body + "</b><br/>")
}
function sendSpittle(text) {
stomp.send("/chat", {}, text);
}
$('#stop').click(function() {sock.close()});
</script>
<div id="output"></div>
</body>
</html>
6.配置WebMvcConfig
@Configuration
public class WebMvcConfigMy implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry
) {
registry
.addViewController("/login").setViewName("/login");
registry
.addViewController("/chat").setViewName("/chat");
}
}
7.该页面需要的js
链接: https://pan.baidu.com/s/1LC1JNdm-R9yU49GIGm4M1w 密码: l808