gpt4 book ai didi

java - 方法上的 Bean 验证

转载 作者:行者123 更新时间:2023-12-01 07:11:08 25 4
gpt4 key购买 nike

public class Register {
@NotNull private String password;
@NotNull private String passwordRepeat;
@AssertTrue private boolean comparePasswords() {
return password.equals(passwordRepeat);
}

private Set<ConstraintViolation<Register>> violations;

public void doRegister(AjaxBehaviorEvent event) {
Validator validator = Validation.buildDefaultValidatorFactory().getValidator();
violations = validator.validate(this);

if(violations.isEmpty()) {
// This occurs
}
}
}

如果我的两个密码都不为空,我的验证就会通过,但它们是不同的。
似乎不会考虑最后一个约束,尽管我不知道为什么。有人有建议吗?

不,我不是在寻找@Matches 或模拟自定义 validator 的任何实现。我只是想解决这个问题。

提前致谢。

更新 1

我已经对此进行了一些测试,希望结果能够提供所需的信息。

Bean.java
@Named
@RequestScoped
public class Bean {
@NotNull private String example1;
@NotNull private String example2;
@AssertTrue private boolean examplesMatch() { return example1.equals(example2); }

private Set<ConstraintViolation<Bean>> violations;
private FacesContext context;
private Validator validator;

@PostConstruct
public void init() {
context = FacesContext.getCurrentInstance();
validator = Validation.buildDefaultValidatorFactory().getValidator();

example1 = "abc";
example2 = "def";
runValidation(false, 1);

example1 = "abc";
example2 = "abc";
runValidation(true, 2);

example1 = "abc";
example2 = null;
runValidation(false, 3);
}

private void runValidation(boolean assertion, int testNr) {
FacesMessage message;
violations = validator.validate(this);
if(violations.isEmpty() == assertion) {
message = new FacesMessage("Passed test nr. " + testNr);
}
else {
message = new FacesMessage("Failed test nr. " + testNr);
}
context.addMessage(FacesMessage.FACES_MESSAGES, message);
}

索引.xhtml
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<title>TODO supply a title</title>
</head>
<body>
#{bean}
<h:messages />
</body>
</html>

结果
beanvalidation.Bean@31c5c3da

Failed test nr. 1
Passed test nr. 2
Passed test nr. 3

最佳答案

examplesMatch() 不是有效的 Java Beans boolean 属性 getter。它需要以 get 或 is 开头。

关于java - 方法上的 Bean 验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12935360/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com