我在重定向后显示错误消息时遇到了一些非常奇怪的问题。我使用 RedirectAttributes 将带有错误消息的 BindingResult 对象传递给视图,但此解决方案不起作用。
当我只返回一个没有重定向的视图名称时,一切正常。
有人可以提供建议,但没有会话使用吗?
@Controller
public class UserRegistrationController {
@Autowired
private UserService userService;
@RequestMapping(value="/registration", method=RequestMethod.GET)
public ModelAndView registrationPage() {
ModelAndView modelAndView = new ModelAndView("user-registration/registration-form");
modelAndView.addObject("user", new User());
return modelAndView;
}
@RequestMapping(value="/registration", method=RequestMethod.POST)
public ModelAndView registerUser(@ModelAttribute @Valid User user,
BindingResult result,
final RedirectAttributes redirectAttributes) {
ModelAndView modelAndView = new ModelAndView("redirect:registration.html");
User tempUser = userService.get(user.getEmail());
Map<String, String> messages = new HashMap<String, String>();
if (tempUser == null && ! result.hasErrors()) {
userService.save(user);
messages.put("success", "message.user.success.register");
} else {
messages.put("error", "message.user.invalid.register");
redirectAttributes.addFlashAttribute("user", user);
redirectAttributes.addFlashAttribute("errors", result);
}
redirectAttributes.addFlashAttribute("messages", messages);
return modelAndView;
}
}
以及查看代码:
<p>
<c:forEach var="message" items="${messages}">
<span class="${message.key}"><spring:message code="${message.value}" /></span><br />
</c:forEach>
</p>
<form:form method="POST" commandName="user" action="${pageContext.request.contextPath}/registration.html">
<table>
<tbody>
<tr>
<td><spring:message code="user.registration.email" /></td>
<td><form:input path="email" /></td>
<td><form:errors cssClass="error" path="email" /></td>
</tr>
<tr>
<td><spring:message code="user.registration.password" /></td>
<td><form:password path="password" /></td>
<td><form:errors cssClass="error" path="password" /></td>
</tr>
<tr>
<td><input type="submit" /></td>
<td></td>
<td></td>
</tr>
</tbody>
</table>
</form:form>