相关疑难解决方法(0)

Java模型验证

我们正在寻找一个Java库/系统/包,它不仅可以进行基本验证,还可以进行关系验证.我们需要能够表达基于多个相关实体的验证标准.

大多数验证模型Spring Validation,JSR303专门用于验证bean的属性.但是我们需要能够跨越bean的东西.

我们的要求是提出一种验证模型状态的方法,同时将验证逻辑外部化为java代码.

在上面的定义中,Bean只是一个POJO,而一个模型是相关Beans的集合.因此,例如,如果Account有一个Addresses集合,并且Account.countryOfResidence设置为USA,我希望有一个验证规则,确保所有地址都包含USA的国家/地区.

因此,在向帐户添加地址的"操作"期间,将启动验证以确保Address.country与Account.countryOfResidence相同.

我们正在调查DRULES,但想知道是否还有其他选择.

有关如何进行的任何建议?

java validation model relationship

8
推荐指数
1
解决办法
1422
查看次数

未调用跨领域验证的自定义类级别约束

我正在尝试在类级别上使用自定义注释实现跨场验证(JSR-303).但是不调用isValid方法(而是初始化方法).

所以我的问题是:为什么没有为这个类级验证器调用isValid方法?在物业层面定义它的作品!

我在JBoss AS 7和Websphere AS 8上尝试过它.

这是代码和JUnit测试(有效)

Test.java

public class Test {

@org.junit.Test
public void test() throws ParseException {
    Person person = new Person();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMDD");
    person.setPartyClosingDateFrom(new Date());
    person.setPartyClosingDateTo(sdf.parse("20120210"));
    Set<ConstraintViolation<Person>> violations = Validation.buildDefaultValidatorFactory().getValidator().validate(person);
    for(ConstraintViolation<Person> violation : violations) {
        System.out.println("Message:- " + violation.getMessage());
    }
}
  }
Run Code Online (Sandbox Code Playgroud)

DateCompare.java

 import static java.lang.annotation.ElementType.TYPE;
 import static java.lang.annotation.RetentionPolicy.RUNTIME;
 import java.lang.annotation.Documented;
 import java.lang.annotation.Retention;
 import java.lang.annotation.Target;
 import javax.validation.Constraint;
 import javax.validation.Payload;

 @Target({ TYPE})
 @Retention(RUNTIME)
 @Constraint(validatedBy = DateCompareValidator.class)
 @Documented
 public @interface DateCompare {

/** First date. …
Run Code Online (Sandbox Code Playgroud)

java annotations bean-validation jsf-2

8
推荐指数
1
解决办法
4876
查看次数

Spring注释验证 - 检查更新与添加的唯一性

我有一个名为sport的POJO,其属性为sportID,sportName,玩家数量.使用带注释的验证我编写了自己的注释约束来检查数据库中是否存在sportName.它在尝试添加sportName时效果很好,但是如果我尝试在不更改sportName的情况下更新玩家,则验证也会失败.

有没有办法在带注释的验证中传递参数?例如,我想将sportID传递给sportName约束检查,以便我可以在db查询中排除该ID.

或者有更好的方法吗?在我的控制器中,我应该让Spring验证输入(使用@Valid)然后如果没有错误,请调用验证函数来检查业务规则?

validation spring

8
推荐指数
1
解决办法
3687
查看次数

如何让Spring为类中的同一验证器显示不同的基于验证包的消息?

首先,让我解释一下,我使用的是Spring MVC 3.1.1和Hibernate验证4.2.0.我在Spring应用程序中使用各种表单的验证注释.由于我的应用程序需要本地化,我一直在使用资源包来查看我的验证消息:

# ValidationMessages.bundle
FieldMatch=Password and confirmation must match.
Run Code Online (Sandbox Code Playgroud)

此消息的相应类定义如下所示:

@FieldMatch.List({
    @FieldMatch(first = "password", second = "passwordConfirmation")
})
public class RegistrationForm {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

我在appContext.xml中设置了这个自定义资源包,我的消息显示在表单上没有任何问题.

然而,这是我的困境.有一项新要求,我必须确认更多字段匹配.现在我只是确认两个密码字段匹配.现在我的要求是我必须确认电子邮件地址.我知道这是一个愚蠢的要求,但我不能改变它.所以现在类定义将如下所示:

@FieldMatch.List({
    @FieldMatch(first = "password", second = "passwordConfirmation")
    @FieldMatch(first = "email", second = "emailConfirmation")
})
public class RegistrationForm {
    // ...
}
Run Code Online (Sandbox Code Playgroud)

显然,我当前的资源包不起作用,因为我需要两个单独的消息(每个匹配一个).我已尝试使用message="{emails.must.match}"然后在资源包中定义该消息,但它实际上从未显示消息,它只显示实际文本{email.must.match}.

所以解释之后,我的问题很简单:如何让FieldMatch类级别的每个验证器都有一个在资源包中定义的不同消息,以便它可以被本地化?

在此先感谢您的帮助!

[编辑]对于那些好奇的人,FieldMatch我正在使用的验证器.

更新5/23/2012 这是其他人要求的bean定义:

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames">
        <list>
            <value>ErrorBundle</value>
            <value>ForgotPasswordBundle</value>
            <!-- etc etc -->
        </list>
    </property>
</bean> …
Run Code Online (Sandbox Code Playgroud)

java spring-mvc hibernate-validator bean-validation

8
推荐指数
1
解决办法
2869
查看次数

如何访问注释属性中描述的字段

是否可以访问字段值,其中字段名称在注释中描述,注释对类中的另一个字段进行注释。

例如:

@Entity
public class User {

    @NotBlank
    private String password;

    @Match(field = "password")
    private String passwordConfirmation;
}
Run Code Online (Sandbox Code Playgroud)

注解:

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = FieldMatchValidator.class)
@Documented
public @interface Match {

    String message() default "{}";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    String field();
}
Run Code Online (Sandbox Code Playgroud)

现在,是否可以从 ConstraintValidator 实现类中的 User 类访问字段密码?


编辑:

我写了这样的东西:

public class MatchValidator implements ConstraintValidator<Match, Object> {

private String mainField;
private String secondField;
private Class clazz;

@Override
public void initialize(final Match match) {
    clazz = User.class;

    final …
Run Code Online (Sandbox Code Playgroud)

java reflection annotations hibernate-validator

7
推荐指数
2
解决办法
7851
查看次数

使用JSR-303和Spring的Validator的组合为Spring引导端点实现自定义验证逻辑

我试图实现使用的组合弹簧引导终点一些自定义的验证逻辑JSR-303 Bean Validation APISpring's Validator.

基于Validator类图,似乎可以扩展其中一个CustomValidatorBean,SpringValidatorAdapter或者LocalValidatorFactoryBean将一些自定义验证逻辑添加到重写方法中validate(Object target, Errors errors).

验证器类图.

但是,如果我创建一个验证器来扩展这三个类中的任何一个并使用@InitBindervalidate(Object target, Errors errors)方法注册它,则永远不会调用它,也不会执行验证.如果我删除@InitBinder然后默认弹簧验证器执行JSR-303 Bean Validation.

休息控制器:

@RestController
public class PersonEndpoint {

    @InitBinder("person")
    protected void initBinder(WebDataBinder binder) {
        binder.setValidator(new PersonValidator());
    }

    @RequestMapping(path = "/person", method = RequestMethod.PUT)
    public ResponseEntity<Person> add(@Valid @RequestBody Person person) {

        person = personService.save(person);
        return ResponseEntity.ok().body(person);
    }
}
Run Code Online (Sandbox Code Playgroud)

自定义验证器:

public class PersonValidator extends CustomValidatorBean {

    @Override
    public …
Run Code Online (Sandbox Code Playgroud)

java validation spring bean-validation spring-boot

7
推荐指数
2
解决办法
2万
查看次数

如何在将来参考另一个日期验证该日期?

我有以下bean:

class CampaignBeanDto {

    @Future
    Date startDate;

    Date endDate;

    ...
}
Run Code Online (Sandbox Code Playgroud)

显然我endDate应该在startDate之后.我想验证它.

我知道我可以为此手动实现注释@FutureAfterDate,验证器并手动初始化阈值日期但我想使用@Validatedspring mvc注释.

我怎样才能实现它?

java validation date spring-mvc hibernate-validator

6
推荐指数
2
解决办法
5969
查看次数

在方法中使用@AssertTrue时,该方法在验证期间被调用4次(Bean Validation)

@AssertTrue当使用bean验证来验证对象的状态时,每当调用验证时,使用注释的方法就会被调用4次。每次调用只应调用一次。

Hibernate 验证器版本:5.1.3.Final

这是一个例子:

对于以下类别的摩托车:

import javax.validation.constraints.AssertTrue;
class Motorcycle{
    private int fuel;
    private int tireDurability;

    @AssertTrue(message = "motorcycle.not.available.to.use")
    public boolean isAvailable(){
        return fuel > 0 && tireDurability > 0;
    }

    public void toUse(){...}
}
Run Code Online (Sandbox Code Playgroud)

以及主要的:

import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
public class Main{
    public static void main(String []args){
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Validator validator = factory.getValidator();

        Set<ConstraintViolation<Motorcycle>> violations = validator.validate(new Motorcycle());

    }
}
Run Code Online (Sandbox Code Playgroud)

validator.validate(new Motorcycle())调用时,该方法isAvailable()被调用4次。

任何人都可以帮助我解决这种情况吗?这是一个错误吗?我该如何解决这个问题?

java validation custom-validators hibernate-validator bean-validation

6
推荐指数
1
解决办法
3567
查看次数

@RequestParam验证

有没有一种方法可以使用 spring 验证请求参数,而无需在每个函数中检查它?例如,控制器中的每个方法都会生成元素列表,并且每个方法接受“from”和“to”参数,因此验证是: from >=0 && to > 0 && from < to

我想配置 spring 返回BAD_REQUEST或其他一些状态,就像它无法将 string 转换为 int 参数时一样。

谢谢。

java validation spring spring-mvc

5
推荐指数
1
解决办法
2380
查看次数

JSR 303实现提供了ClassCastException

我正在使用JSR 303实现自定义验证批注,但出现错误。我正在关注使用Hibernate Validator(JSR 303)进行跨字段验证时提供的详细信息

java.lang.ClassCastException: com.sun.proxy.$Proxy95 cannot be cast to com.my.validator.FieldMatch
at com.my.validator.FieldMatchValidator.initialize(FieldMatchValidator.java:14) ~[classes/:na]
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.initializeConstraint(ConstraintValidatorManager.java:261) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.createAndInitializeValidator(ConstraintValidatorManager.java:183) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorManager.getInitializedValidator(ConstraintValidatorManager.java:122) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorNoUnwrapping(ConstraintTree.java:303) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getConstraintValidatorInstanceForAutomaticUnwrapping(ConstraintTree.java:244) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.getInitializedConstraintValidator(ConstraintTree.java:163) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:116) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]
at org.hibernate.validator.internal.engine.constraintvalidation.ConstraintTree.validateConstraints(ConstraintTree.java:87) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]
at org.hibernate.validator.internal.metadata.core.MetaConstraint.validateConstraint(MetaConstraint.java:73) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]
at org.hibernate.validator.internal.engine.ValidatorImpl.validateMetaConstraint(ValidatorImpl.java:617) ~[hibernate-validator-5.2.4.Final.jar:5.2.4.Final]
Run Code Online (Sandbox Code Playgroud)

有人可以帮帮我吗?

java spring hibernate hibernate-validator spring-validator

5
推荐指数
1
解决办法
602
查看次数