![](/img/trans.png)
[英]Java - How to combine Validation and AOP annotations and use it in Spring Controller?
[英]spring combine two validation annotations in one
我正在使用Spring + Hibernate + Spring-MVC 。
我想定义一个自定义约束,结合其他两个预定义的验证注释: @NotNull @Size
如下所示:
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
@NotNull
@Size(min=4)
public @interface JPasswordConstraint {
} // this is not correct. It's just a suggestion.
我想在我的表单模型中使用此注释。
public class ChangePasswordForm {
@NotNull
private String currentPass;
@JPasswordConstraint
private String newPass;
@JPasswordConstraint
private String newPassConfirm;
}
@RequestMapping(value = "/pass", method = RequestMethod.POST)
public String pass2(Model model, @Valid @ModelAttribute("changePasswordForm") ChangePasswordForm form, BindingResult result) {
model.addAttribute("changePasswordForm", form);
try {
userService.changePassword(form);
} catch (Exception ex) {
result.rejectValue(null, "error.objec", ex.getMessage());
System.out.println(result);
}
if (!result.hasErrors()) {
model.addAttribute("successMessage", "password changed successfully!");
}
return "user/pass";
}
但它不起作用。 它接受少于4个字符的密码。
我怎么解决这个问题?
这有点晚了,但结合了验证注释的技术
在撰写本文时,可能没有它,但解决方案正在跟进
@NotNull
@Size(min=4)
@Target({ METHOD, FIELD, ANNOTATION_TYPE })
@Retention(RUNTIME)
@Constraint(validatedBy = { })
@Documented
public @interface JPasswordConstraint {
String message() default "Password is invalid";
Class<?>[] groups() default { };
Class<? extends Payload>[] payload() default { };
}
你可以加
@ConstraintComposition
默认情况下,谁是AND,如果有一天你想要@NotNull或@Size你添加
@ConstraintComposition(OR)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.