我有 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");
}
如果我在鏈接 localhost:8080/people/0 上手動更新瀏覽器或從 HTML 鏈接轉到它,效果很好。但是當從 PostMapping 控制器重定向到它時失敗。它出什么問題了?
github上推送的專案:這里是控制器,表單
更新:IDEA 說回傳模板錯誤。什么是正確的?
uj5u.com熱心網友回復:
您可以嘗試使用不同的方式進行重定向。在你使用 HttpServletResponse#sendRedirect 的地方可能是這樣的:
@GetMapping("/foo")
public void handleFoo(HttpServletResponse response) throws IOException {
response.sendRedirect("/foobar");
}
@GetMapping("/foobar")
public String handleFooBar() {
return "FooBar!";
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/465602.html
