使用WebApplicationContextUtils.getWebApplicationContext(ServletContext cn)获取WebApplicationContext为null

                在使用SpringMVC搭建demo时再使用WebApplicationContextUtils.getWebApplicationContext(ServletContext cn )方法获取WebApplicationContext对象时获取到的是空,可能的原因是因为在Web.xml中没有配置ContextLoaderListener监听或者没有配置ContextLoaderServlet的Servlet的类。

             原理:服务器在启动时会读取Web.xml中的配置的监听,而ContextLoaderListener这个监听类的职责就是自动封装WebApplicationContext对象,由于没有配置该监听所有获取到对象是null。

            解决方案:

          在Web.xml中配置以下监听:

               <listener>
                   <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
               </listener>

           

               

@Override protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) { System.out.println("isAccessAllowed 方法被调用"); //这里先全部拒绝 return false; } /** * 返回结果为true表明登录通过 */ @Override protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception { System.out.println("onAccessDenied 方法被调用"); // 所以以后发起请求的时候就需要在Header中放一个Authorization,值就是对应的Token String token = ((HttpServletRequest) servletRequest).getHeader("Authorization"); System.out.println(token); if (StringUtils.isEmpty(token)) { System.out.println("没有携带token;非法访问"); //onLoginFail(servletResponse, "非法访问"); return true; } if (JwtUtils.verify(token)) { // 这里是token验证通过 // 获取tokenid String tokenId = JwtUtils.getTokenId(token); // 通过ApplicationContext来获取 ServletContext context = servletRequest.getServletContext(); ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context); RedisUtil redisUtil = ctx.getBean(RedisUtil.class); // 这里在redis判断token是否过期 if (redisUtil.hasKey(tokenId)) { System.out.println("请求成功,通过"); return true; } else { // 过期重新登录 System.out.println("过期重新登录"); onLoginFail(servletResponse, "过期重新登录"); return false; } } else { // 非法token System.out.println("非法token"); onLoginFail(servletResponse, "非法token"); return true; } // 执行方法中没有抛出异常就表示登录成功 }
06-01
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值