我需要验证我的JSP表单。带有JSR 303注释的Hibernate验证器非常适合简单验证(如@NotEmpty)。对于更复杂的验证,我需要验证器类。 但是当我注入自己的验证器时,内置注释的JSR 303没有做任何事情!
如何一起使用注释和类验证?
JSP表单:
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%-- ... --%>
<div>
<c:url var="address" value="/form" />
<c:if test="${not empty message}">${message}</c:if>
<form:form action="${address}" method="POST" commandName="user">
<%-- ... --%>
<form:label path="nickname">Nickname</form:label>
<form:input type="text" path="nickname" />
<form:errors path="nickname" cssClass="error"></form:errors>
<form:label path="password">Password</form:label>
<form:input type="password" path="password" />
<form:errors path="password" cssClass="error"></form:errors>
<form:label path="password2">Password</form:label>
<form:input type="password" path="password2" />
<button type="submit">Send</button>
</form:form>
</div>
实体:
@Entity
@Table(name = "User")
public class User implements Serializable {
// ...
@NotEmpty(message="Missing name!")
@Column(name = "name", nullable = false)
private String name;
@NotEmpty
@javax.validation.constraints.Size.List(value = {
@Size(min=5, message="Min 5 chars!"),
@Size(max=10, message="Max 10 chars!")
})
@Column(name = "nickname", nullable = false)
private String nickname;
@NotEmpty
@Column(name = "password", nullable = false)
private String password;
@Transient
@NotEmpty
private String password2;
public User() {}
// setters and getters...
}
验证
@Component
public class FormValidator implements Validator {
@Override
public boolean supports(Class<?> clazz) {
return User.class.isAssignableFrom(clazz);
}
@Override
public void validate(Object target, Errors errors) {
ValidationUtils.rejectIfEmpty(errors, "password", "password.not.empty", "Enter password!");
ValidationUtils.rejectIfEmpty(errors, "password2", "password.not.empty");
User u = (User) target;
if ( ! u.getPassword().equals(u.getPassword2()) ) {
errors.rejectValue("password", "password.not.equals");
}
}
控制器:
@Controller
public class FormController {
@Autowired
private UserManager userManager;
@RequestMapping(value="/form", method = RequestMethod.GET)
public String login(ModelMap model) {
model.addAttribute("user", new User());
return "register";
}
@RequestMapping(value="/form", method = RequestMethod.POST)
public String registerSave(ModelMap model, @Valid @ModelAttribute("user") User user, BindingResult result) {
if (result.hasErrors()) {
model.addAttribute("message", "ERROR");
return "register";
}
user.setPassword(password);
/...
userManager.save(user);
model.addAttribute("message", "OK");
return "register";
}
@InitBinder("user")
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new FormValidator());
}
}