您可以使用 Flash 重定向属性。
@RequestMapping(value = "/administrator/users", method = RequestMethod.POST)
public String adminAddUser(@ModelAttribute("user") @Valid User user, BindingResult bindingResult, Model model, RedirectAttributes redirectAttrs) {
String redirectUrl = "/administrator/users";
try {
userService.save(user);
} catch (YourServiceException e) {
redirectAttrs.addFlashAttribute("errorMessage", "error occured: " + e.getMessage());
redirectAttrs.addFlashAttribute("userObject", user);
redirectUrl = "/administrator/users?form"; // If error - return to same view
}
return "redirect:" + redirectUrl;
}
@RequestMapping(value = "/administrator/users", params = "form", method = RequestMethod.GET, produces = "text/html")
public String adminUsersList(@ModelAttribute("errorMessage") final String errorMessage, @ModelAttribute("userObject") final User user Model model) {
if(user == null) {
user = new User();
}
model.addAttribute("user", user);
if(errorMessage != null) {
model.addAttribure("errorMessage", errorMessage);
}
return "administrator/users/create";
}
在这种情况下,您必须在 users.jsp 页面上设置部分以显示错误消息。像这样的东西:
<c:if test="${not empty errorMessage}">${errorMessage}</c:if>
如果您可以从控制器方法中获取 url 路径和 redirectAttributes - 您可以通过 @ControllerAdvice 执行此操作