以前看到空指针问题总感觉束手无策,不知道怎么定位和解决,然而通过一直以来的的努力,终于知道了该怎么处理。
先贴代码:
@PostMapping("/publish")
public String doPublish(
@RequestParam("title") String title,
@RequestParam("description") String description,
@RequestParam("tag") String tag,
HttpServletRequest request,
Model model
) {
GithubUser user = null;
Cookie[] cookies = request.getCookies();
for (Cookie cookie : cookies) {
if (cookie.getName().equals("token")) {
String token = cookie.getValue();
user = userMapper.findByToken(token);
if (user != null) {
request.getSession().setAttribute("user", user);
}
break;
}
}
if (user == null) {
model.addAttribute("error", "用户未登录");
return "publish";
}
Question question = new Question();
question.setTitle(title);
question.setDescription(description);
question.setTag(tag);
question.setCreator(user.getId());
question.setGmtCreate(System.currentTimeMillis());
question.setGmtModified(question.getGmtCreate());
questionMapper.create(question);
return "redirect:/";
}
如果cookie为空,就会抛出空指针异常,解决方法是判断cookie是否为空,如果为空的话就跳转回当前页面,
其它的对象也是一样,有可能出现空指针的类进行异常处理之后,把错误信息进行文字处理返回给用户并跳转回页面。
具体情况还要根据业务来定。