开发者

Empty string with multiple blank problem in JSF - SPRING - HIBERNATE

i have a simple problme. I need to catch when a user enter an empty string in a form and display the appropriate error message. I'm trying with jsf required attribute, but if the user enter " " a string like that the validation go next without error. I had try Spring annotatio开发者_如何学JAVAn @NotNull and Hibernate @NotEmpty, but nothing solve the problem. Any idea?


I'm not sure about the Spring part, but in Hibernate you can use @NotBlank annotation for this:

@NotBlank
private String value;

Or, you could create a JSF converter for String.class which does the job:

package com.example;

import javax.faces.component.EditableValueHolder;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter(forClass=String.class)
public class EmptyToNullConverter implements Converter {

    public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
        if (value == null || value.trim().isEmpty()) {
            if (component instanceof EditableValueHolder) {
                ((EditableValueHolder) component).setSubmittedValue(null);
            }
            return null;
        }
        return value;
    }

    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
        return (value == null) ? null : value.toString();
    }

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜