Дорогие, Я пытаюсь получить HTTPSession в своем WebSocketHandler. Я мог сделать это успешно, когда использовал javax.websocket-api, но теперь я использую Spring-Websocket.
Конфигурация:
@ConditionalOnWebApplication
@Configuration
@EnableWebSocket
public class WebSocketConfigurator implements WebSocketConfigurer {
@Autowired
private ApplicationContext context;
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
MyEndpoint endpoint = context.getBean(MyEndpoint.class);
registry.addHandler(endpoint, "/signaling");
}
}
Когда соединение установлено:
@Component
public class MyEndpoint implements WebSocketHandler {
private WebSocketSession wsSession;
@Override
public void afterConnectionEstablished(WebSocketSession webSocketSession) throws Exception {
this.wsSession = webSocketSession;
// need to get the HTTP SESSION HERE
log.info("Opening: " + webSocketSession.getId());
}
}
А теперь это пример того, как я могу это сделать с помощью javax.websocket-api:
Конфигурация:
@ServerEndpoint(value = "/signaling", //
decoders = MessageDecoder.class, //
encoders = MessageEncoder.class,
configurator = MyEndpointConfigurator.class)
/***
* define signaling endpoint
*/
public class MyEndpoint extends NextRTCEndpoint {
}
Затем я вводил HTTPSession, изменяя рукопожатие:
public class MyEndpointConfigurator extends ServerEndpointConfig.Configurator {
@Override
public void modifyHandshake(ServerEndpointConfig config,
HandshakeRequest request,
HandshakeResponse response) {
HttpSession httpSession = (HttpSession) request.getHttpSession();
config.getUserProperties().put(HttpSession.class.getName(), httpSession);
}
}
И, наконец, он был доступен при установлении WS-соединения:
@OnOpen
public void onOpen(Session session, EndpointConfig config) {
this.wsSession = session;
this.httpSession = (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
log.info("Opening: " + session.getId());
server.register(session, httpSession);
}
Мне не удалось сделать что-то подобное с «Spring Websocket». Любое решение? Пожалуйста, не предлагайте классы из StompJS, поскольку я его не использую.




Вот этот, который можно использовать:
**
* An interceptor to copy information from the HTTP session to the "handshake
* attributes" map to made available via{@link WebSocketSession#getAttributes()}.
*
* <p>Copies a subset or all HTTP session attributes and/or the HTTP session id
* under the key {@link #HTTP_SESSION_ID_ATTR_NAME}.
*
* @author Rossen Stoyanchev
* @since 4.0
*/
public class HttpSessionHandshakeInterceptor implements HandshakeInterceptor {
И в Справочное руководство есть пример того, как его настроить:
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(new MyHandler(), "/myHandler")
.addInterceptors(new HttpSessionHandshakeInterceptor());
}
Итак, все, что вам нужно от сеанса HTTP, будет доступно в WebSocketSession.getAttributes().
Большой! Пора принять ответ: stackoverflow.com/help/someone-answers!
отлично, сегодня попробую, спасибо за ответ!