Websocket - httpSession返回null

时间:2013-11-27 10:58:43

标签: session tomcat websocket httpsession

我想在websocket handshake \ session与HttpSession对象之间建立连接。

我使用了以下握手修改:

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);
}
}

如本文所述: Accessing HttpSession from HttpServletRequest in a Web Socket @ServerEndpoint

现在, 由于某些原因,握手时,(HttpSession)request.getHttpSession()一直返回null。

这是我的客户端代码:

<!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>

为什么没有创建会话的任何想法? 感谢

4 个答案:

答案 0 :(得分:9)

这是预期的行为,但我同意这可能令人困惑。来自HandshakeRequest.getHttpSession javadoc:

/**
 * Return a reference to the HttpSession that the web socket handshake that 
 * started this conversation was part of, if the implementation
 * is part of a Java EE web container.
 *
 * @return the http session or {@code null} if either the websocket
 * implementation is not part of a Java EE web container, or there is
 * no HttpSession associated with the opening handshake request.
 */

问题是,尚未为您的客户端连接创建HttpSession,并且WebSocket API实现只询问是否创建了某些内容,如果没有,则不创建它。您需要做的是在调用WebSocket impl过滤器之前的某个时间调用httpServletRequest.getSession()(调用doFilter(...))。

这可以通过调用ServletRequestListener#requestInitalized中提到的方法或不同的过滤器等来实现。

答案 1 :(得分:7)

这是Pavel Bucek的答案,在添加之后,我得到了我的会话

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

@WebListener
public class RequestListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        // TODO Auto-generated method stub

    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        ((HttpServletRequest) sre.getServletRequest()).getSession();
    }

}

答案 2 :(得分:0)

@pavel-bucek 's answer的基础上,我写了simple HttpSessionInitializerFilter servlet filter

只需从“版本”页面下载jar并将其保存在类路径中的任何位置,然后将以下代码段添加到web.xml描述符中(根据需要修改url-pattern):

push()

答案 3 :(得分:0)

首先:创建一个新类

import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

@WebListener

public class RequestListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
    }

    @Override
    public void requestInitialized(ServletRequestEvent servletRequestEvent) {
        ((HttpServletRequest)servletRequestEvent.getServletRequest()).getSession();
    }
}

然后在App main上添加“ServletComponentScan”注释:

@SpringBootApplication

@ServletComponentScan

public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}