我有一些非常奇怪的問題,顯示重定向後的錯誤消息。我使用RedirectAttributes將帶有錯誤消息的BindingResult對象傳遞給視圖,但此解決方案不起作用。Spring MVC:重定向後顯示驗證消息
當我只返回一個視圖名稱與重定向,一切工作正常。
有人可以給出建議,但沒有會話使用?
@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>
另一種想法,可能是因爲您將ModelAndView設置爲GET映射中的新對象,它會覆蓋您傳入的重定向Flash變量? 模型也許並看到如果重定向Flash變量存在: 「公衆的ModelAndView registrationPage(型號模型){ ....」 –
關於鏈接JIRA:我使用3.2.3版本的春天 –