【发布时间】:2021-05-06 00:22:37
【问题描述】:
我的应用程序有一个更新会议的方法。这样做之后,我有一个带有重定向到主会议列表的模型和视图。这一切都很好,尽管我作为对象添加到模型视图的消息没有显示。
我的控制器中的方法:
@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,尽管消息没有显示。在网址中我可以看到 http://localhost:8080/teacher/configure?message=Successfully+modified+conference
我查看了this thread,尽管它没有帮助。
我尝试通过设置 ModelAndView mav = new ModelAndView("configure") 进行实验,消息显示,但我的会议列表为空且 url 为 http://localhost:8080/teacher/更新会议
非常感谢任何提示!
编辑
我已经尝试使用 RedirectAttributes,正如 crizzis 指出的那样 & this page 并且现在有了这个:
@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";
}
我的get方法:
@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]
【问题讨论】:
-
也许可以试试
${#request.getParameter('message') -
感谢您的回复!我正在尝试使用 RedirectAttributes 方式,它按预期工作。消息传递并显示。虽然我的 GET 方法有问题,因为它没有显示绑定结果并进入错误页面。我将使用我尝试使用的已实施方法来更新我的问题