【问题标题】:How can I get a cookie value inside websocket end-point如何在 websocket 端点中获取 cookie 值
【发布时间】:2013-08-08 11:20:11
【问题描述】:

我在我的应用程序中使用基于 JavaEE 7 的 Websocket-API。

我需要访问我的 websocket 端点 [Annotated one : @ServerEndpoint ("/websocket") ] 内的 cookie 中设置的值。我该怎么做?

@onOpen() 方法在那里,当建立到这个 websocket 端点的连接时会自动调用。我想在此方法中访问其中的 cookie 值。

我知道如何在 servlet 或 JSP 中做到这一点,但我是 Websockets 的新手。

请帮我做这件事。提前致谢。

【问题讨论】:

    标签: cookies websocket java-ee-7


    【解决方案1】:

    虽然 Joakim 的回答确实提供了正确方向的提示,但我相信它并没有完全回答这个问题,或者至少可以补充。

    为了检索 cookie 的值,您必须获取 HandshakeRequest 对象的标头,并查找名为“cookie”的标头。您的 modifyHandshake 实现将如下所示:

    public class MyEndpointConfigurator extends ServerEndpointConfig.Configurator {
        @Override
        public void modifyHandshake(ServerEndpointConfig config, 
                                    HandshakeRequest request, 
                                    HandshakeResponse response)
        {
            Map<String,List<String>> headers = request.getHeaders();
            config.getUserProperties().put("cookie",headers.get("cookie"));
        }
    }
    

    【讨论】:

      【解决方案2】:

      通过@ServerEndpoint(configurator=MyConfigurator.class) 技术访问请求参数。

      请参阅other answer on how to access the HttpSession,因为它的技术非常相似。

      【讨论】:

      • 这真是太棒了。我可以使用您说明的方式成功获取 HttpSession 。但我的目的是获取 cookie,而不是 HttpSession;我尝试了相同的场景,但未能得到它。 'this.httpCookie = (HttpSession) config.getUserProperties() .get(HttpCookie.class.getName());'我不知道如何通过配置器的 modifyHandshake() 方法将此 HttpCookie 放入 EndPointConfig。帮我做这件事。
      • 这实际上并没有回答原始问题
      • @gshauger 这确实是一个重复的问题,因此引用了访问 HttpSession 的其他答案(传统上在 JEE 应用程序中访问 Cookie)
      • @JoakimErdfelt 感谢您提供指向其他答案的链接。那里有丰富的信息。
      猜你喜欢
      • 1970-01-01
      • 2017-12-02
      • 1970-01-01
      • 2015-08-14
      • 2019-09-26
      • 2015-02-23
      • 2017-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多