我是靠谱客的博主 沉默豆芽,这篇文章主要介绍记录两次空指针问题的解决方案,现在分享给大家,希望可以做个参考。

以前看到空指针问题总感觉束手无策,不知道怎么定位和解决,然而通过一直以来的的努力,终于知道了该怎么处理。

先贴代码:

@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是否为空,如果为空的话就跳转回当前页面,

其它的对象也是一样,有可能出现空指针的类进行异常处理之后,把错误信息进行文字处理返回给用户并跳转回页面。

具体情况还要根据业务来定。

最后

以上就是沉默豆芽最近收集整理的关于记录两次空指针问题的解决方案的全部内容,更多相关记录两次空指针问题内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(125)

评论列表共有 0 条评论

立即
投稿
返回
顶部