request.getSession().setAttribute与request.setAttribute的区别

equest.setattrbute()顾名思义只能在一个request内有效,如果重定向回客户端,将取不到值。
request.getsession.setattribute()则可以通过jsessionid得到自己的session,进而取回其中的值,即使重定向回客户端也无所谓.
第一个是保存在session里
第二个是保存在request里
遇到实际问题代码

@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Cookie[] cookies = request.getCookies();
        boolean boo = false;
        if (cookies==null){
            return boo;
        }
        for (Cookie cookie : cookies) {
            String name = cookie.getName();
            //判断当前cookie是否为登录信息的cookie
            if (wisdomPipelineParameterMenu.COOKIE_KEY.equals(name)){
                //获取cookie存入redis的key值
                String value = cookie.getValue();
                String s = stringRedisTemplate.opsForValue().get(value);
                if (!StringUtils.isEmpty(s)){
                    //判读当前用户账号密码是否有过变动
                    UserEntity userEntity = JSON.parseObject(s, UserEntity.class);
                    UserEntity user = userService.getById(userEntity.getUserId());
                    if (user!=null&&user.getAccount().equals(userEntity.getAccount())  && user.getPassword().equals(userEntity.getPassword())){
                        userThreadLocal.set(userEntity);
                        
                        request.getSession().setAttribute("user",userEntity);
                        //获取页面session是否过期如果过期就重新赋值
                        Object homePageDataVo = request.getSession().getAttribute("homePageDataVo");
                        if (homePageDataVo==null){
                            HomePageDataVo loginHomePageData = userService.getHomePageData(userThreadLocal.get());
                            request.getSession().setAttribute("homePageDataVo",loginHomePageData);
                        }
                        boo=true;
                    }
                }
            }
        }
        if (!boo){
            response.sendRedirect("/login");
        }
        return boo;
    }

这两个位置 如果使用 request.setattrbute() 那么每次查询都要去查询数据库
 request.getSession().setAttribute("user",userEntity);
 request.getSession().setAttribute("homePageDataVo",loginHomePageData);
 
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值