WebSocket中获取HttpSession

    由于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());
 
    }

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值