在websocket中获取httpsession

1.新建

public class HttpSessionConfigurator extends Configurator {

    @Override
    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        HttpSession httpSession = (HttpSession) request.getHttpSession();
        sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
    }

}

2.新建

@Component
public class RequestListener implements ServletRequestListener {

    public void requestInitialized(ServletRequestEvent sre)  {
        //将所有request请求都携带上httpSession
        ((HttpServletRequest) sre.getServletRequest()).getSession();

    }
    public RequestListener() {
    }

    public void requestDestroyed(ServletRequestEvent arg0)  {
    }
}

3.在配置类中添加

@Autowired
private RequestListener requestListener;

@Bean
public ServletListenerRegistrationBean<RequestListener> servletListenerRegistrationBean() {
    ServletListenerRegistrationBean<RequestListener> servletListenerRegistrationBean = new ServletListenerRegistrationBean<>();
    servletListenerRegistrationBean.setListener(requestListener);
    return servletListenerRegistrationBean;
}

4.在@ServerEndpoint后面添加配置类

@ServerEndpoint(value="/ws",configurator = HttpSessionConfigurator.class)

并修改onOpen方法

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

注意:我自己写的时候发现httpsession总是没有值,后来发现原因在于自己浏览器访问的ip用的127.0.0.1而websocket连接用的ip为电脑实际ip,改成一样的就好了。感谢网友分享让我找到原因https://blog.csdn.net/qq_35101027/article/details/80745664。另外,其他部分代码是根据https://www.cnblogs.com/zhuxiaojie/p/6238826.html学着写的,原文更加详细,大家可以看看,同样表示感谢。


版权声明:本文为littleDingDang原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。