Spring websocket upgraderequest

问题描述 投票:0回答:1

我有一个弹簧应用程序。

我需要为初始握手设置一个值。

网址看起来像:ws://localhost:8080/chat?key=value

我需要在我的Websocket Handler中使用这个key=value

我该如何访问它?

Websocket配置:

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        // alle origins erlauben
        registry.addHandler(chatWebSocketController(), "/chat").addInterceptors(new HttpSessionHandshakeInterceptor())
            .setAllowedOrigins("*");
    }

    @Bean
    public ChatWebSocketController chatWebSocketController() {
        return new ChatWebSocketController();
    }
}

Websocket Handler方法:

@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {

    if (session.getAttributes().containsKey("key")) {
        List<String> userMap = session.getHandshakeHeaders().get("key");
        JwtTokenUtil jwtTokenUtil = new JwtTokenUtil();
        String token = userMap.get(0);
        if (jwtTokenUtil.validateToken(token)) {
            User userToStore = new User(jwtTokenUtil.getUsernameFromToken(token));
            userUsernameMap.put(session, userToStore);
            LOGGER.info("User with name " + jwtTokenUtil.getUsernameFromToken(token) + "and IP "
                    + session.getRemoteAddress() + " successfully connected");
            sendConnectMessage(session, userToStore);

        }
    } else {
        session.close(CloseStatus.POLICY_VIOLATION);
    }
}
java spring spring-mvc websocket stomp
1个回答
0
投票

我自己找到了解决方案。你必须编写自己的HandshakeInterceptor,你可以访问http参数。所以你可以把它放到你的attribbutes地图上。

public class HttpHandshakeInterceptor implements HandshakeInterceptor {

@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
        Map<String, Object> attributes) throws Exception {
    if (request instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
        HttpSession session = servletRequest.getServletRequest().getSession();
        attributes.put("sessionId", session.getId());
        attributes.put("key", servletRequest.getServletRequest().getParameterMap().get("key"));
    }
    return true;
}

@Override
public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler,
        Exception exception) {
    //nothing to do
}

}
© www.soinside.com 2019 - 2024. All rights reserved.