最近在做瑞吉外卖的时候就遇到了这个问题,写过滤器处理请求的时候判断是否登录时

request.getSession().getAttribute("employee")

获得了空值

 //4 判断是否登录 已登录则放行
        if(request.getSession().getAttribute("employee")!=null){
            log.info("用户已登录,id为{}",request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }

employee是登录时set进去的

代码如下:

@PostMapping("/login")
    public R<Employee> login(HttpServletRequest request , @RequestBody Employee employee){

        //1、将页面提交的密码password进行md5加密处理
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());//等值查询
        Employee emp = employeeService.getOne(queryWrapper);

        //3、如果没有查询到则返回登录失败结果
        if(emp==null){
            return R.error("账号不存在,录失败");
        }

        //4、密码比对,如果不一致则返回登录失败结果
        if(!emp.getPassword().equals(password)){
            return R.error("密码错误,登录失败");
        }
        //5、查看员工状态,如果为已禁用状态,则返回员工已禁用结果
        if(emp.getStatus() == 0){
            return R.error("账号已禁用");
        }
        //6、登录成功,将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee",employee.getId());
        System.out.println("登录成功");
        //System.out.println((String) request.getSession().getAttribute("employee"));
        return R.success(emp);
    }

判断是否登录时request.getSession().getAttribute("employee")得到了null,百度有说是因为

HttpServletRequest导的包不同导致的,我仔细对比了两个类的包是一样的,还有说是因为Ajax跨域的。

一番百度无果,于是乎我在login这个方法里set完就get一下看看,发现这得到的也是空值,至此我陷入了沉思。一番测试后我set的时候把employee改成emp

//6、登录成功,将员工id存入Session并返回登录成功结果
        request.getSession().setAttribute("employee",emp.getId());

然后就可以了,过滤器里判断是否登录也能get到值了,虽然问题解决了,为什么employee不可以,我还是没想明白。有知道的大佬可以评论告知一下,非常感谢。

 

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐