场景
我在开发修改密码功能,通过原密码和新密码及确认新密码,希望通过constraintvalidator这个方式来校验新密码和确认新密码,规则是这两个密码需要是相同的。
参考文档
- https://github.com/micronaut-projects/micronaut-core/issues/3243
- https://stackoverflow.com/questions/37750656/how-to-access-a-field-which-is-described-in-annotation-property
- https://discourse.hibernate.org/t/how-can-i-retrieve-current-validation-contexts-groups-in-a-validator/414/4
实现
定义matches注解
@constraint(validatedby = samecontentmatchesvalidator.class)
@target({ elementtype.field })
@retention(retentionpolicy.runtime)
public @interface samecontentmatches {
string message() default "内容不一致";
class<?>[] groups() default {};
class<? extends payload>[] payload() default {};
string field(); // 新增属性,指定要比较的字段
}定义dto对象
@data
public class usermodifypassworddto implements userdto {
@notnull
private string username;
@notnull
private string password;
private string newpassword;
@samecontentmatches(field = "newpassword")
private string confirmpassword;
}定义matchesvalidator对象,实现验证的代码逻辑
public class samecontentmatchesvalidator implements constraintvalidator<samecontentmatches, string> {
private string field;
@override
public void initialize(samecontentmatches constraintannotation) {
this.field = constraintannotation.field();
}
@override
public boolean isvalid(string object, final constraintvalidatorcontext context) {
return true;
}
}遇到的问题
- 在matchesvalidator类中,无法获取到当前对象,除非把samecontentmatches注解作用到当前类上面,而非字段上面。
- 这个问题应该主是无法解决的,因为你拦截的是字段,在这个constraintvalidatorcontext处理的都是和当前字段有关的信息
应用到类上,代码调整,问题解决
@constraint(validatedby = samecontentmatchesvalidator.class)
@target({ elementtype.type })
@retention(retentionpolicy.runtime)
public @interface samecontentmatches {
string message() default "内容不一致";
class<?>[] groups() default {};
class<? extends payload>[] payload() default {};
/**
* 源字段名
* @return
*/
string sourcefield();
/**
* 目标字段名
* @return
*/
string destinationfield();
}
public class samecontentmatchesvalidator implements constraintvalidator<samecontentmatches, object> {
private string sourcefield;
private string destinationfield;
@override
public void initialize(samecontentmatches constraintannotation) {
this.sourcefield = constraintannotation.sourcefield();
this.destinationfield = constraintannotation.destinationfield();
}
@override
public boolean isvalid(object o, final constraintvalidatorcontext context) {
final object sourcefieldval = beanutil.getproperty(o, this.sourcefield);
final object destinationfieldval = beanutil.getproperty(o, this.destinationfield);
return sourcefieldval.equals(destinationfieldval);
}
}
@data
@samecontentmatches(sourcefield = "confirmpassword", destinationfield = "newpassword")
public class usermodifypassworddto implements userdto {
@notnull
private string username;
@notnull
private string password;
private string newpassword;
private string confirmpassword;
}上面的代码samecontentmatches注解出现了弱编码,这块需要再进行优化。
到此这篇关于springboot中使用constraintvalidatorcontext验证两个字段内容相同的文章就介绍到这了,更多相关springboot验证字段内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论