在 WebSocketHandler 中访问 HTTP Session

亲爱的,我试图在我的 WebSocketHandler 中获得一个 HTTPSession。当我使用“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);

    }

}

我无法成功地用“Spring Websocket”做类似的事情。任何解决方案?请不要从 StompJS 中推荐类,因为我没有使用它。


慕侠2389804
浏览 250回答 1
1回答

达令说

有一个可以使用:**&nbsp;* An interceptor to copy information from the HTTP session to the "handshake&nbsp;* attributes" map to made available via{@link WebSocketSession#getAttributes()}.&nbsp;*&nbsp;* <p>Copies a subset or all HTTP session attributes and/or the HTTP session id&nbsp;* under the key {@link #HTTP_SESSION_ID_ATTR_NAME}.&nbsp;*&nbsp;* @author Rossen Stoyanchev&nbsp;* @since 4.0&nbsp;*/public class HttpSessionHandshakeInterceptor implements HandshakeInterceptor {参考手册中有一个示例如何配置它:@Overridepublic void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {&nbsp; &nbsp; registry.addHandler(new MyHandler(), "/myHandler")&nbsp; &nbsp; &nbsp; &nbsp; .addInterceptors(new HttpSessionHandshakeInterceptor());}因此,您从 HTTP 会话中需要的任何内容都将在WebSocketSession.getAttributes().
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java