您可以使用您的第一種方法設置用戶名。首先,您需要將攔截器添加到您的StompEndpointRegistry類中,然後您可以從屬性確定用戶映射並返回本金。
下面是代碼:
HttpSessionHandshakeInterceptor是用於攔截在HTTP屬性和在DefaultHandshakeHandler類爲他們提供
@Configuration
@EnableWebSocketMessageBroker
@EnableWebMvc
@Controller
public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app","/user");
}
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat")
//Method .addInterceptors for enabling interceptor
.addInterceptors(new HttpSessionHandshakeInterceptor())
.setHandshakeHandler(new MyHandler())
.withSockJS();
}
class MyHandler extends DefaultHandshakeHandler{
@Override
protected Principal determineUser(ServerHttpRequest request, WebSocketHandler wsHandler,
Map<String, Object> attributes) {
//Get the Username object which you have saved as session objects
String name = (String)attributes.get("name");
//Return the User
return new UsernamePasswordAuthenticationToken(name, null);
}
}
}