由于WebSocket使用的协议有别于单纯的http,所以如果想要在WebSocket中直接获取HttpSession是无法获取的。需要想办法将HttpSession传入websocket中。

     首先新建一个类继承Configurator

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
import javax.websocket.server.ServerEndpointConfig.Configurator;


/**
 * 该类的作用是将HttpSession注入websocket
 */
public class GetHttpSessionConfigurator extends Configurator {
    @Override
    public void modifyHandshake(ServerEndpointConfig sec,
                                HandshakeRequest request, HandshakeResponse response) {
        // TODO Auto-generated method stub
        HttpSession httpSession=(HttpSession) request.getHttpSession();
        sec.getUserProperties().put(HttpSession.class.getName(),httpSession);
    }

}

然后在websocket的@ServerEndpoint注解里面添加configurator属性

@ServerEndpoint(value =\"/websocket\",configurator=GetHttpSessionConfigurator.class)

最后在onOpen方法里加入参数EndpointConfig config就可以获取到HttpSession

    private  HttpSession httpSession;
    @OnOpen
    public void onOpen( Session session,EndpointConfig config)
    {
      httpSession= (HttpSession) config.getUserProperties().get(HttpSession.class.getName());
 
    }

 

 

 

 

 

 

 

 

收藏 打印