Websocket - httpSession 返回 null [英] Websocket - httpSession returns null
问题描述
我想在 websocket 握手\会话和 HttpSession 对象之间建立连接.
I would like to make the connection between a websocket handshake \ session to a HttpSession object.
我使用了以下握手修改:
I've used the following handshake modification:
public class GetHttpSessionConfigurator 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);
}
}
正如这篇文章中提到的:从 Web Socket @ServerEndpoint 中的 HttpServletRequest 访问 HttpSession
As mentioned in this post: Accessing HttpSession from HttpServletRequest in a Web Socket @ServerEndpoint
现在,握手时由于某种原因,(HttpSession)request.getHttpSession() 一直返回null.
Now, For some reason on the hand shake, the (HttpSession)request.getHttpSession() returns null all the time.
这是我的客户端代码:
<!DOCTYPE html>
<html>
<head>
<title>Testing websockets</title>
</head>
<body>
<div>
<input type="submit" value="Start" onclick="start()" />
</div>
<div id="messages"></div>
<script type="text/javascript">
var webSocket =
new WebSocket('ws://localhost:8080/com-byteslounge-websockets/websocket');
webSocket.onerror = function(event) {
onError(event)
};
webSocket.onopen = function(event) {
onOpen(event)
};
webSocket.onmessage = function(event) {
onMessage(event)
};
function onMessage(event) {
document.getElementById('messages').innerHTML
+= '<br />' + event.data;
}
function onOpen(event) {
document.getElementById('messages').innerHTML
= 'Connection established';
}
function onError(event) {
alert(event.data);
}
function start() {
webSocket.send('hello');
return false;
}
</script>
</body>
</html>
<div id="消息"></div><script type="text/javascript">var webSocket =new WebSocket('ws://localhost:8080/com-byteslounge-websockets/websocket');webSocket.onerror = 函数(事件){onError(事件)};webSocket.onopen = 函数(事件){onOpen(事件)};webSocket.onmessage = 函数(事件){onMessage(事件)};函数 onMessage(事件){document.getElementById('messages').innerHTML+= '
'+ 事件数据;}函数 onOpen(事件){document.getElementById('messages').innerHTML= '连接建立';}函数 onError(event) {警报(事件.数据);}函数开始(){webSocket.send('你好');返回假;}