空指针:HttpSession异常,SpringBoot集成WebSocket

异常可能性:

  • 404 : 请检查拦截器是否将请求拦截
  • WebSocket握手期间HttpSession为空

HttpSession为空

方法一 :

网上参考大量的文档,有说跟前端请求域名有关系的。 反正对我来说,没啥用无法连接。

需使用 localhost,不能使用127.0.01

复制代码
    var host = window.location.host;
    var url = "ws://"+host+"/chatRoom/null";

方法二 :可以解决

添加监听配置 ,采用spring boot自动装配的方式,创建一个Session。

因为我需要存入数据,所以对我而言,不太ok。

其他原因看:WebSocket获取httpSession空指针异常的解决办法https://blog.csdn.net/csu_passer/article/details/78536060

java 复制代码
@WebListener
public class RequestListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent servletRequestEvent) {
    }

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

虽然有Session了,还是连接不上!

方法三 :成功解决

灵感 : 方法2通过监听创建Session。监听最牛逼的不应该是拦截器或者过滤器。

可以从拦截器中获取到我需要的数据,在request里面配置,应该更好。从request中getSession,存点东西进去试试。

java 复制代码
@WebFilter(urlPatterns = "/*")
public class ArticleFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException{
        long start = System.currentTimeMillis();

        // 存入session
        System.out.println("存入session");
        ((HttpServletRequest) request).getSession().setAttribute("name", 123);

        // 封装请求信息存储到请求上下文
        chain.doFilter(request, response);
        long end = System.currentTimeMillis();
        System.out.println("请求耗时:" + (end - start) + "ms");
    }
}
相关推荐
Lovely_Ruby17 分钟前
前端er Go-Frame 的学习笔记:实现 to-do 功能(三),用 docker 封装成镜像,并且同时启动前后端数据库服务
前端·后端
Lear20 分钟前
MySQL配置文件优化详解:提升数据库性能的关键参数配置
后端
光影少年28 分钟前
node中的peerDependencie含义
后端·node.js·掘金·金石计划
7哥♡ۣۖᝰꫛꫀꪝۣℋ1 小时前
Spring Boot ⽇志
java·spring boot·后端
新手程序员大大1 小时前
springCloudGateway+Nacos注册与转发Netty+WebSocket
spring boot
橙序员小站1 小时前
Java 接入 Pinecone 搭建知识库踩坑实记
java·后端
wadesir2 小时前
Go语言反射之结构体的深比较(详解reflect.DeepEqual在结构体比较中的应用)
开发语言·后端·golang
即将进化成人机2 小时前
springboot项目创建方式
java·spring boot·后端
vx_bisheyuange2 小时前
基于SpringBoot的游戏交易系统
spring boot·后端·游戏·毕业设计
curd_boy2 小时前
IM 顶层设计
websocket·架构·信息与通信