gpt4 book ai didi

java - 在 WebSocketServlet (Jetty WebSockets) 中访问在 HttpServlet 中设置的 session 属性

转载 作者:行者123 更新时间:2023-12-02 13:31:51 27 4
gpt4 key购买 nike

我正在尝试访问 HttpServlet 中设置的 session 属性来自 WebSocketServlet
我有两个 ServletContextHandler对象,都带有 SESSIONS启用:

val httpHandler = object : ServletContextHandler(nullParent, contextPath, SESSIONS).apply {
addServlet(ServletHolder(httpServlet), "/*")
}

val webSocketHandler = ServletContextHandler(nullParent, contextPath, SESSIONS).apply {
addServlet(ServletHolder(wsServlet), "/*")
}

这些以 HandlerList(httpHandler, webSocketHandler) 的形式附加。到我的 jetty Server . doHandle 的第一行的 ServletContextHandler对于 HttpHandler检查请求是否为 WebSocket 升级请求,如果是则立即返回(在这种情况下,它被移交给 ServletContextHandlerWebSocketServlet )。

我有一个简单的 POST设置 session 属性的端点,但我无法在 WebSocketServlet 中检索此 session 属性:

class MyWsServlet : WebSocketServlet() {

override fun configure(factory: WebSocketServletFactory) {
factory.creator = WebSocketCreator { req, res ->
// session exists here, but req.session.getAttribute("any-attr") is always null
}
}

override fun service(req: HttpServletRequest, res: HttpServletResponse) {
// session also exists here, but req.session.getAttribute("any-attr") is always null
}

}

欢迎任何意见或建议。

编辑:我在 req.session.setAttribute("test", "tast") 之后包含了一些来自 GET 请求和 WebSocket 请求的调试信息。被称为:
Path: /
Cookies:{JSESSIONID=node01cxyhb0addjwikyb2lgtnlxlw0.node0}
Session: Session@24b04e4{id=node01cxyhb0addjwikyb2lgtnlxlw0,x=node01cxyhb0addjwikyb2lgtnlxlw0.node0,req=1,res=true}
Session id: node01cxyhb0addjwikyb2lgtnlxlw0
Session isNew: false
Session attributes: {test=tast}
---------------------------
Path: /websocket
Cookies:{JSESSIONID=node01cxyhb0addjwikyb2lgtnlxlw0.node0}
Session: Session@5989f3d1{id=node01cxyhb0addjwikyb2lgtnlxlw0,x=node01cxyhb0addjwikyb2lgtnlxlw0.node0,req=1,res=true}
Session id: node01cxyhb0addjwikyb2lgtnlxlw0
Session isNew: false
Session attributes: {}

最佳答案

首先,摆脱你的 2 ServletContextHandler ,使用一个。无论如何,您不能在同一个 contextPath 上有两个处理程序。

此外,您有 2 种主要方式可以实现 Jetty Server WebSockets,使用 WebSocketServlet ,或使用 WebSocketUpgradeFilter .最大的区别是使用 WebSocketUpgradeFilter你可以有多个映射指向任意数量的 WebSocket 端点,使用 Servlet url-pattern notation,或 URI-template notation,甚至 regex notation。

如果您这样做后问题仍然存在,那么听起来您的客户要么没有发送Cookie。 Jetty 需要的 header ,或发送错误的 header (例如:Cookie header 指向不同的/新的 HttpSession 引用)。

捕获你的客户端和服务器之间的流量,注意客户端Cookie值,以及任何 Set-Cookie在来自服务器的响应中看到的值。

您也可以有一个过滤器,只转储 Activity 的 HttpSession每个请求的详细信息。确保它显示 HttpSession.getId() , HttpSession.isNew()并转储所有属性(通过 .getAttributeNames()getAttribute(String name) 调用的组合)。

关于java - 在 WebSocketServlet (Jetty WebSockets) 中访问在 HttpServlet 中设置的 session 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60753624/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com