我需要帮助。我想在 Spring 3 MVC 中使用自定义验证器验证表单输入。一切正常,但在出现错误时不会在表单上显示错误
这是控制器
public class ContactController {
@ModelAttribute("Contact")
public Contact getContactObject() {
return new Contact();
}
@RequestMapping(value = "/addContact", method = RequestMethod.POST)
public String processValidatinForm(@Valid Contact contact, BindingResult result, Map model,Errors e) {
UserValidator validator = new UserValidator();
validator.validate(contact, result);
if (result.hasErrors()) {
System.out.println("found Errors");
return "contact";
}
// Add the saved validationForm to the model
model.put("Contact", contact);
return "successs";
}
@RequestMapping("/contacts")
public String showValidatinForm(Map model) {
Contact contact = new Contact();
model.put("Contact", contact);
return "contact";
}
} 用户验证器
public class UserValidator implements Validator {
@Override
public boolean supports(Class clazz) {
return Contact.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "Enter user name");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "age", "Enter Age");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "Enter password.");
}
}
这是表单jsp页面
<form:form method="post" action="addContact.html" commandName="Contact">
<table>
<tr>
<td>User Name:<font color="red"><form:errors path="userName" /></font></td>
<tr>
<td><form:input path="userName" /></td>
</tr>
<tr>
<td>Age:<font color="red"><form:errors path="age" /></font></td>
</tr>
<tr>
<td><form:input path="age" /></td>
</tr>
<tr>
<td>Password:<font color="red"><form:errors path="password" /></font></td>
</tr>
<tr>
<td><form:password path="password" /></td>
</tr>
<tr>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form:form>
怎么做才对?
谢谢您的回复。