![](/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.