Spring开机。 PostMapping Controller return 语句后出现 500 错误

Spring Boot. 500 error after PostMapping Controller return statement

我有 2 个控制器的简单代码

@GetMapping("/{id}/createPost") 
public String createUserPost(@PathVariable("id") int id, ModelMap modelMap) {
    modelMap.addAttribute("person", personDao.getPersonById(id));
    modelMap.addAttribute("userDB", personDao.getUsrById(id));
    modelMap.addAttribute("webPost", new WebPost());
    return "people/createPost";
}

@PostMapping("/{id}") 
public String postUserPost(@ModelAttribute("webPost") @Valid WebPost webPost, BindingResult bindingResult,
                           @PathVariable("id") int id) {
    if (bindingResult.hasErrors())
        return "people/{id}/createPost";
    webPost.setId_note(1);
    webPost.setData_pub(new Date());
    return  "redirect:/people/{id}"; //"people/test";
}

当我在浏览器中启动它时 (localhost:8080/people/0/createPost),第一个控制器运行良好。当我提交空表单和 bindingResult.hasErrors()==true (在第二个控制器中)时,它在浏览器中转发到 localhost:8080/people/0 而不是同一页面并收到 500 错误。 如果我填写表格,它也会被重定向到 localhost:8080/people/0 并且还会给出错误 500.

控制器,它重定向的地方

@GetMapping("/{id}") 
    public String showBlog (@PathVariable ("id") int id, ModelMap modelMap1){ 
        modelMap1.addAttribute("person", personDao.getPersonById(id));
        modelMap1.addAttribute("userDB", personDao.getUsrById(id));
        modelMap1.addAttribute("webPost", new WebPost());
        return ("people/blog");
    }

效果很好 如果我在 link localhost:8080/people/0 上手动更新浏览器或从 HTML link 转到它。但是,当从 PostMapping 控制器重定向到它时失败了。 怎么了?

项目推进 github:这里是 controller, and the form

更新:IDEA 说错了 return 模板。哪一个是正确的?

您可以尝试使用不同的重定向方式。 也许像这样你使用 HttpServletResponse#sendRedirect:


    @GetMapping("/foo")
    public void handleFoo(HttpServletResponse response) throws IOException {
        response.sendRedirect("/foobar");
    }

    @GetMapping("/foobar")
    public String handleFooBar() {
        return "FooBar!";
    }