想象一下,用户提供电子邮件的单个字段的表单。在POST时,控制器操作方法向该电子邮件发送确认代码并显示第二表单,其中用户应输入他们收到的确认码。如果代码不匹配,则返回原始视图,我想在电子邮件旁边显示错误消息("电子邮件未确认")。
以下示例代码:
<div>
Please provide the following information to sign-up:
<form:form modelAttribute="newAccountInfo" action="signup-submit.do" method="POST">
<div><form:label path="email">Email:</form:label>
<form:input type="text" path="email"/><form:errors path="email" cssClass="error" element="div"/>
</div>
...
@RequestMapping(path="/signup-submit", method=RequestMethod.POST)
public String signupSubmit(HttpServletRequest request
, @ModelAttribute("newAccountInfo") @Valid NewAccountInfo newAccountInfo
, BindingResult result
, Model model) {
String confirmCode = generateRandomSecret();
// send confirmCode by email to newAccountInfo.email (omitted)
model.addAttribute("emailConfirmation" , new EmailConfirmation());
request.getSession().setAttribute("newAccountInfo", newAccountInfo);
request.getSession(false).setAttribute("email-code", confirmCode);
return View.SIGNUP_EMAIL_CONFIRMATION.name;
}
<div>
Enter the confirmation code that was sent to your email:
<form:form modelAttribute="emailConfirmation" action="signup-email-confirmation-submit.do" method="POST">
<form:label path="code">Confirmation code:</form:label>
<form:input type="text" path="code"/>
<input type="submit" value="Submit" />
</form:form>
@RequestMapping(path="/signup-email-confirmation-submit", method=RequestMethod.POST)
public String signupEmailConfirmationSubmit(
@ModelAttribute("emailConfirmation") EmailConfirmation emailConfirmation
, BindingResult result
, Model model) {
if (emailConfirmation.getCode().equals(request.getSession(false).getAttribute("email-code")))
return View.SIGNUP_SUCCESS.name;
else {
model.addAttribute("newAccountInfo", request.getSession(false).getAttribute("newAccountInfo"));
request.getSession(false).invalidate();
// TODO - what should I do here ?
return View.SIGNUP.name;
}
假设未正确输入确认代码,我应该在第二个视图控制器方法中做什么,以便在显示第一个视图时(第二次),电子邮件旁边有一个字段验证错误消息,其中包含说明&#34;电子邮件未得到确认&#34; ?
在标有TODO评论的行中,我尝试了以下内容:
result.rejectValue("email", null, "email was not confirmed");
...但这会导致以下异常:
org.springframework.beans.NotReadablePropertyException: Invalid property 'email' of bean class [EmailConfirmation]: Bean property 'email' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
(这是有道理的,因为电子邮件不是EmailConfirmation
的字段)。
然而,下面也失败了(默默地,没有例外,显示第一个视图,我只是没有看到验证错误消息):
result.addError(new FieldError("newAccountInfo", "email", "email could not be confirmed"));
最后,我能让这个工作的唯一方法是通过添加以下内容来添加自定义模型属性(总是在第二个视图控制器方法的TODO
行中):
model.addAttribute("emailConfirmationError", true);
...然后按如下方式修改第一个视图:
<div><form:label path="email">Email:</form:label>
<form:input type="text" path="email"/>
<form:errors path="email" cssClass="error" element="div"/>
<c:if test="${not empty emailConfirmationError}">
<span class="error">The email could not be confirmed</span>
</c:if>
</div>
以上成功但感觉就像是黑客,因为我没有使用Spring MVC的验证机制。
我的问题是: