【问题标题】:How to use Spring Websocket with the Spring Session custom HttpSession and without Stomp/SockJS?如何在没有 Stomp/SockJS 的情况下将 Spring Websocket 与 Spring Session 自定义 HttpSession 一起使用?
【发布时间】:2016-06-08 01:36:11
【问题描述】:

在服务器应用程序中,我使用 裸 websockets,而没有 spring消息传递层和 sockjs/stomp。我需要我自己的消息层在上面,但我想使用例如 spring 会话来利用 servlet HttpSession 替换来保持 websocket 会话下方的 http 会话处于活动状态,以防止超时。 websocket 是使用 JavaScript 从静态 HTML 页面打开的

spring-framework documentation 中有所有必要的信息来设置裸 websocket 支持,例如一个基本的 BinaryWebSocketHandler 或 TextWebSocketHandler 以及如何 提供您自己的 HandshakeInterceptor

我添加了带有 hazelcast 的 spring session 1.1.0.RC1,用于存储会话并用 spring 会话提供的 Session/ExpiringSession 替换 servlet 容器 HttpSession 实现。我只是按照给定的说明执行此操作。

到目前为止一切都很好,但是由于我正在提供一个静态 HTML 页面,因此我使用 JavaScript 打开 websocket 而不使用 spring security 或任何其他机制触发 servlet 容器的处理,到目前为止还没有初始化 http 会话

所以问题是:如何初始化自定义 HttpSession,然后将其存储在 Spring 会话提供的 SessionRepository 中?

注意:我会自己提供一个答案,因为我认为我解决了我的案例的问题,并且可能对面临类似问题的其他人有所帮助。

【问题讨论】:

    标签: java spring session websocket


    【解决方案1】:

    从 spring-framework 文档中可以看出,可以添加自定义 HandshakeInterceptor。春季会议提供了

    // example for reference: 
    org.springframework.session.web.socket.server.SessionRepositoryMessageInterceptor 
    

    它以spring消息层为目标。它展示了如何在 preSend(...) 方法中发送消息之前重置 HttpSession 的计时器,以及如何从中选择 HttpSession beforeHandshake(...)方法中的请求

    我在此基础上实现了我自己的自己的 HandshakeInterceptor,使用了一个几乎相同的 beforeHandshake(...) 方法,但有一个细微的差别,当然还省去了 ChannelInterceptorAdapter 的东西. HttpSession 时间的重置必须在其他地方完成,但这超出了范围。

    因为在我的例子中到目前为止还没有创建 HttpSession,所以我将从请求中获取会话的行更改为如下所示:

    HttpSession session = servletRequest.getServletRequest().getSession(true);
    

    getSession(...) 方法中将布尔参数从 false 更改为 true。现在,如果目前还没有可用的 HttpSession(由 spring session 提供),这个调用将触发创建一个新的 HttpSession。

    此解决方案似乎可以满足我的需求。如果我遗漏了什么或使用了错误的方法,请纠正我。

    【讨论】:

      猜你喜欢
      • 2015-01-25
      • 2016-07-04
      • 2017-05-29
      • 1970-01-01
      • 2017-10-04
      • 1970-01-01
      • 2017-06-05
      • 2015-03-30
      • 1970-01-01
      相关资源
      最近更新 更多