JSF与Bean Validation结合使用:ConstraintViolationException

时间:2014-04-09 09:30:22

标签: jsf bean-validation jsf-2.2

我尝试将JSF与Bean Validation结合使用。基本上,一切运行良好,验证按预期工作,我得到正确的消息,但我的Glassfish控制台有一个例外:

Warnung:   EJB5184:A system exception occurred during an invocation on EJB MyEntityFacade, method: public void com.mycompany.testbv.AbstractFacade.create(java.lang.Object)
Warnung:   javax.ejb.EJBException
at com.sun.ejb.containers.EJBContainerTransactionManager.processSystemException(EJBContainerTransactionManager.java:748)
....
....
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
Caused by: javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.

如果我使用自定义约束以及预定义约束,则会发生此异常。

这是我的示例代码。

示例实体:

@Entity
@ValidEntity
public class MyEntity implements Serializable {

    private static final long serialVersionUID = 3104398374500914142L;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
    @Size(min = 2)
    private String name;

    public MyEntity(String name) {
        this.name = name;
    }

    public MyEntity() {

    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

自定义约束:

@Constraint(validatedBy = MyValidator.class)
@Target({FIELD, METHOD, TYPE})
@Retention(RUNTIME)
public @interface ValidEntity {
    String message() default "fail";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

自定义验证器:

public class MyValidator implements ConstraintValidator<ValidEntity, MyEntity>{

    @Override
    public void initialize(ValidEntity a) {
    }

    @Override
    public boolean isValid(MyEntity t, ConstraintValidatorContext cvc) {
        return false;
    }
}

样本控制器:

@Named
@SessionScoped
public class MyController implements Serializable {

    private static final long serialVersionUID = -6739023629679382999L;

    @Inject
    MyEntityFacade myEntityFacade;
    String text;

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }

    public void saveNewEntity() {
        try {
            myEntityFacade.create(new MyEntity(text));
        } catch (Exception e) {
            Throwable t = e;
            while (t != null) {
                if (t instanceof ConstraintViolationException) {
                    FacesContext context = FacesContext.getCurrentInstance();
                    Set<ConstraintViolation<?>> constraintViolations = ((ConstraintViolationException) t).getConstraintViolations();
                    for (ConstraintViolation<?> constraintViolation : constraintViolations) {
                        FacesMessage facesMessage = new FacesMessage(constraintViolation.getMessage());
                        facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
                        context.addMessage(null, facesMessage);
                    }
                }
                t = t.getCause();
            }
        }
    }
}

示例jsf页面:

<html xmlns="http://www.w3.org/1999/xhtml"
  xmlns:h="http://xmlns.jcp.org/jsf/html">
    <h:head></h:head>
    <h:body>
        <h:form>
            <h:messages id="messages" />
            <h:inputText value="#{myController.text}" />
            <h:commandButton value="Save" action="#{myController.saveNewEntity()}" />
        </h:form>
    </h:body>
</html>

MyEntityFacade仅从实体管理器调用persist。

如前所述,应用程序运行正常并且正确的消息是shwon,但我想在Glassfish控制台中避免此异常。

如讨论here所述,将persistence.xml中的验证模式设置为NONE是不可取的,因为我想要验证。

我在2.2版中使用JSF,实现是Mojarra。 Bean Validation的版本是1.1,实现是Hibernate Validator。 Application Server是Glassfish 4.0。

1 个答案:

答案 0 :(得分:1)

类级别约束不适用于JSF。看看this answer。当您按下“保存”按钮时,JSF仅检查名称是否至少有2个字符,并且不考虑ValidEntity约束。另一方面,JPA抱怨bean无效并抛出异常。

<强>更新

1)@Size约束在MyEntity.name属性上,而在facelet中有MyController.text属性。在JSF的角度来看,没有什么可以验证的。它根本不了解MyEntity。

2)ValidEntity始终无效,因此即使您在facelet中正确设置MyEntity.name,JPA也会始终抛出异常(除非您禁用验证)。