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);