[英]Redirect ModelAndView with message
我的应用程序有一个更新会议的方法。 这样做之后,我有一个带有重定向到主会议列表的模型和视图。 这一切都很好,尽管我作为 object 添加到模型视图的消息没有显示。
我在 controller 中的方法:
@PostMapping("/updateConference")
public ModelAndView updateConference(
@ModelAttribute("conference") @Valid ConferenceDto conferenceDto, BindingResult result) {
if(result.hasErrors()){
return new ModelAndView("updateConference","conferenceDto", conferenceDto);
}
try {
conferenceService.updateConference(conferenceDto);
} catch (ConferenceAlreadyExistException uaeEx) {
ModelAndView mav = new ModelAndView("updateConference","conferenceDto", conferenceDto);
mav.addObject("message", uaeEx.getMessage());
return mav;
}
ModelAndView mav = new ModelAndView("redirect:/teacher/configure"); // Problem is here
mav.addObject("message", "Successfully modified conference.");
return mav;
}
在我的 html 我有这行:
<div th:if="${message != null}" th:align="center" class="alert alert-info" th:utext="${message}">message</div>
更新会议后,它会返回到 configure.html 尽管消息没有显示。 在 url 我可以看到http://localhost:8080/teacher/configure?message=Successfully+modified+conference
我看过这个线程,虽然它没有帮助。
我尝试通过设置ModelAndView mav = new ModelAndView("configure")进行实验,消息显示,但我的会议列表为空,url 为 http://localhost:8080/teacher/updateconference
任何提示都非常感谢!
编辑
我已经尝试使用 RedirectAttributes 作为crizzis指出的 & 这个页面,现在有了这个:
@PostMapping("/updateConference")
public String updateConference(
@ModelAttribute("conference") @Valid ConferenceDto conferenceDto, BindingResult result, RedirectAttributes attributes) {
if(result.hasErrors()){
attributes.addFlashAttribute("org.springframework.validation.BindingResult.conferenceDto", result);
attributes.addFlashAttribute("conferenceDto", conferenceDto);
return "redirect:/teacher/updateConference";
}
try {
conferenceService.updateConference(conferenceDto);
} catch (ConferenceAlreadyExistException uaeEx) {
attributes.addFlashAttribute("conferenceDto", conferenceDto);
attributes.addFlashAttribute("message", uaeEx.getMessage());
return "redirect:/teacher/updateConference";
}
attributes.addFlashAttribute("message", "Successfully modified conference.");
return "redirect:/teacher/configure";
}
我的获取方法:
@GetMapping(path = "/updateConference/{id}")
public String showUpdateConferenceForm(@PathVariable(name = "id") Long id, Model model){
Optional<Conference> conference = conferenceService.findById(id);
if (!model.containsAttribute("ConferenceDto")) {
model.addAttribute("conference", new ConferenceDto());
}
return "updateConference";
}
这按预期工作,我的消息显示在我的 configure.html 上。 但是,当我在 BindingResults 中出现错误时,应用程序会转到错误页面,并且我在控制台中得到了这个:
Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported]
使用具有addFlashAttribute
方法的RedirectAttributes
。 您可以像以前一样设置success
或failure
消息,并根据需要通过重定向页面中的密钥访问该消息。
当错误发生时,您将重定向到相同的方法而不是这个,您可以只呈现模板以防出现错误。 我这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.