Commit b9e802e4 authored by 杨伊博's avatar 杨伊博

point to point is work

parent 37faeaa7
......@@ -15,7 +15,7 @@
</parent>
<properties>
<start-class>com.us.WebApplication</start-class>
<start-class>com.us.Application</start-class>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
</properties>
......@@ -39,6 +39,7 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<!-- 引入Web模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
......@@ -51,11 +52,12 @@
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
<!-- 引入security模块 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>4.2.3.RELEASE</version>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
......
//package com.us.example.config;
//
//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();
// }
//
// //4
// @Override
// protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// auth
// .inMemoryAuthentication()
// .withUser("wyf").password("wyf").roles("USER")
// .and()
// .withUser("wisely").password("wisely").roles("USER");
// }
// //5忽略静态资源的拦截
// @Override
// public void configure(WebSecurity web) throws Exception {
// web.ignoring().antMatchers("/resources/static/**");
// }
//
//}
\ No newline at end of file
package com.us.example.config;
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()//根路径和/login路径不拦截
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login") //2登陆页面路径为/login
.defaultSuccessUrl("/chat") //3登陆成功转向chat页面
.permitAll()
.and()
.logout()
.permitAll();
}
//4在内存中配置两个用户 wyf 和 wisely ,密码和用户名一致,角色是 USER
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("wyf").password("wyf").roles("USER")
.and()
.withUser("wisely").password("wisely").roles("USER");
}
//5忽略静态资源的拦截
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/resources/static/**");
}
}
\ No newline at end of file
......@@ -18,15 +18,21 @@ public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer{
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) { //endPoint 注册协议节点,并映射指定的URl
registry.addEndpoint("/endpointWisely").withSockJS();//注册一个Stomp 协议的endpoint,并指定 SockJS协议。
// registry.addEndpoint("/endpointChat").withSockJS();
//注册一个Stomp 协议的endpoint,并指定 SockJS协议
registry.addEndpoint("/endpointWisely").withSockJS();
//注册一个名字为"endpointChat" 的endpoint,并指定 SockJS协议。 点对点-用
registry.addEndpoint("/endpointChat").withSockJS();
}
@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {//配置消息代理(message broker)
registry.enableSimpleBroker("/topic"); //广播式应配置一个/topic 消息代理
// registry.enableSimpleBroker("/queue","/topic"); //2
//广播式应配置一个/topic 消息代理
registry.enableSimpleBroker("/topic");
//点对点式增加一个/queue 消息代理
registry.enableSimpleBroker("/queue","/topic");
}
}
......@@ -23,6 +23,9 @@ import java.security.Principal;
public class WebSocketController {
@Autowired
private WebSocketService ws;
@Autowired
private SimpMessagingTemplate messagingTemplate;
//http://localhost:8080/ws
@MessageMapping("/welcome")//浏览器发送请求通过@messageMapping 映射/welcome 这个地址。
......@@ -41,19 +44,24 @@ public class WebSocketController {
return "is ok";
}
// @Autowired
// private SimpMessagingTemplate messagingTemplate;//1
//
// @MessageMapping("/chat")
// public void handleChat(Principal principal, String msg) { //2
// if (principal.getName().equals("wyf")) {//3
// messagingTemplate.convertAndSendToUser("wisely",
// "/queue/notifications", principal.getName() + "-send:"
// + msg);
// } else {
// messagingTemplate.convertAndSendToUser("wyf",
// "/queue/notifications", principal.getName() + "-send:"
// + msg);
// }
// }
@MessageMapping("/chat")
//在springmvc 中可以直接获得principal,principal 中包含当前用户的信息
public void handleChat(Principal principal, Message message) {
/**
* 此处是一段硬编码。如果发送人是wyf 则发送给 wisely 如果发送人是wisely 就发送给 wyf。
*/
if (principal.getName().equals("wyf")) {
//通过convertAndSendToUser 向用户发送信息,
// 第一个参数是接收消息的用户,第二个参数是浏览器订阅的地址,第三个参数是消息本身
messagingTemplate.convertAndSendToUser("wisely",
"/queue/notifications", principal.getName() + "-send:"
+ message.getName());
} else {
messagingTemplate.convertAndSendToUser("wyf",
"/queue/notifications", principal.getName() + "-send:"
+ message.getName());
}
}
}
......@@ -11,7 +11,9 @@ import org.springframework.stereotype.Service;
@Service
public class WebSocketService {
@Autowired
//使用SimpMessagingTemplate 向浏览器发送消息
private SimpMessagingTemplate template;
public void sendMessage() throws Exception{
......
<!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);
});
//链接endpoint名称为 "/endpointChat" 的endpoint。
var sock = new SockJS("/endpointChat");
var stomp = Stomp.over(sock);
stomp.connect('guest', 'guest', function(frame) {
/**
 订阅了/user/queue/notifications 发送的消息,这里雨在控制器的 convertAndSendToUser 定义的地址保持一致,

* 这里多用了一个/user,并且这个user 是必须的,使用user 才会发送消息到指定的用户。

* */
stomp.subscribe("/user/queue/notifications", handleNotification);
});
function handleNotification(message) {
$('#output').append("<b>Received: " + message.body + "</b><br/>")
}
function sendSpittle(text) {
stomp.send("/chat", {}, JSON.stringify({ 'name': text }));//3
}
$('#stop').click(function() {sock.close()});
</script>
<div id="output"></div>
</body>
</html>
\ No newline at end of file
<!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>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment