gpt4 book ai didi

redirect - Spring MVC : Displaying of validation messages after redirect

转载 作者:行者123 更新时间:2023-12-02 02:00:44 25 4
gpt4 key购买 nike

我在重定向后显示错误消息时遇到一些非常奇怪的问题。我使用 RedirectAttributes 将带有错误消息的 BindingResult 对象传递给 View ,但此解决方案不起作用。

当我只返回一个没有重定向的 View 名称时,一切正常。

有人可以提供建议,但没有使用 session 吗?

@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;

}

}

和 View 代码:

<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>

最佳答案

可能想看看这个:

https://jira.springsource.org/browse/SPR-8968

并尝试返回一个 String 而不是 ModelAndView

关于redirect - Spring MVC : Displaying of validation messages after redirect,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17364486/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com