空的输入值不会触发@NotNull,但会触发@NotBlank [英] Empty input value does not triggger @NotNull but it triggers @NotBlank

查看:664
本文介绍了空的输入值不会触发@NotNull,但会触发@NotBlank的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个实体:

import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotBlank;

@Entity
@XmlRootElement
@Table
public class Supplier extends AbstractEntity
{
    @Column
    @NotNull
    private String name;

    @Column
    @NotBlank
    private String representative;

    ...
}

和这种jsf形式:

<h:form>
    <p:commandButton value="save" action="#{supplierController.create}" ajax="false"/>

    <h:panelGrid columns="3" cellpadding="4">
        <h:outputLabel value="#{bundle['Name']}" for="name"/>
        <p:inputText id="name" value="#{supplierController.value.name}"/>
        <p:message for="name"/>

        <h:outputLabel value="#{bundle['Representative']}" for="representative"/>
        <p:inputText id="representative" value="#{supplierController.value.representative}"/>
        <p:message for="representative"/>
    </h:panelGrid>
</h:form>

那么,为什么@NotBlank被触发而@NotNull没有被触发?

so, why is @NotBlank triggered and @NotNull is not?

我在glassfish-3.1.1下使用mojarra-2.1.3_01(hibernate-validator-4.2.0.Final吗?)

i'm using mojarra-2.1.3_01 (ships hibernate-validator-4.2.0.Final?) under glassfish-3.1.1

推荐答案

由于HTTP的本质,空请求参数将作为空字符串而不是null检索.因此,将永远不会触发@NotNull验证器.仅当表单中缺少该字段或禁用该字段时,才会触发该事件.

Due to the nature of HTTP, empty request parameters are retrieved as empty string instead of null. So the @NotNull validator will never be triggered. It will only be triggered when the field is missing in the form or when it is disabled.

不过,您可以通过将以下上下文参数添加到web.xml,来将JSF 2.x配置为将空的提交值解释为null:

You can however configure JSF 2.x to interpret empty submitted values as null by adding the following context paramter to the web.xml:

<context-param>
    <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
    <param-value>true</param-value>
</context-param>

这样,@NotNull将会为空字段触发.

This way the @NotNull will be triggered for empty fields.

这篇关于空的输入值不会触发@NotNull,但会触发@NotBlank的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆