I have simple code for 2 controllers
@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";
}
When I launch it in browser (localhost:8080/people/0/createPost), the first controller works well. When I submit empty Form and bindingResult.hasErrors()==true (in second Controller), it forwards in the Browser to localhost:8080/people/0 instead of to the same page and gets 500 error. If I fill out the Form, it is also redirected to localhost:8080/people/0 and also gives an error 500.
Controller, where it redirects
@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");
}
works well If I update browser by hands on the link localhost:8080/people/0 or go to it from the HTML link. But fails, when redirected to it from PostMapping controller. What's wrong with it?
Project pushed on github: over here is controller, and the form
Upd: IDEA says the wrong return template. What will be correct one?
CodePudding user response:
You can try using a different way for the redirect. Maybe something like this where you use HttpServletResponse#sendRedirect:
@GetMapping("/foo")
public void handleFoo(HttpServletResponse response) throws IOException {
response.sendRedirect("/foobar");
}
@GetMapping("/foobar")
public String handleFooBar() {
return "FooBar!";
}