项目中报java.lang.NullPointerException异常
Cookie[] cookies = request.getCookies();
for (Cookie cookie:cookies){
if(cookie.getName().equals("token")){
String token=cookie.getValue();
User user =userMapper.findByToken(token);
if(user!=null){
request.getSession().setAttribute("user",user);
}
break;
}
}
因为取不到cookie,所以在循环中报异常,虽然一直搞不懂为何会取不到cookie,但是后来经过自己研究,其实增加一个判断条件就可以解决问题,更改后代码:
Cookie[] cookies = request.getCookies();
if(cookies!=null&&cookies.length>0){//增加判断
for (Cookie cookie:cookies){
if(cookie.getName().equals("token")){
String token=cookie.getValue();
User user =userMapper.findByToken(token);
if(user!=null){
request.getSession().setAttribute("user",user);
}
break;
}
}
}