Empty input value does not triggger @NotNull but it triggers @NotBlank

▼魔方 西西 提交于 2020-01-02 10:31:18

问题


i have this entity:

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;

    ...
}

and this jsf form:

<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>

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

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


回答1:


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.

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>

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



来源:https://stackoverflow.com/questions/8235990/empty-input-value-does-not-triggger-notnull-but-it-triggers-notblank

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!