【问题标题】:Empty input value does not triggger @NotNull but it triggers @NotBlank空输入值不会触发@NotNull,但会触发@NotBlank
【发布时间】:2011-11-23 00:47:11
【问题描述】:

我有这个实体:

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 没有被触发?

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

【问题讨论】:

    标签: jsf-2 bean-validation


    【解决方案1】:

    由于 HTTP 的性质,空请求参数被检索为空字符串而不是 null。所以@NotNull 验证器永远不会被触发。仅当表单中缺少该字段或禁用该字段时才会触发它。

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

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

    这样,@NotNull 将针对空字段触发。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-04-13
      • 1970-01-01
      • 2020-05-22
      • 1970-01-01
      • 2012-04-17
      • 2021-02-01
      • 1970-01-01
      相关资源
      最近更新 更多