Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

whitespace - How to prevent spaces form JSF h:inputText

In my JSF 2.2 application, when I create JSF form, the problem is that I can put spaces in the beginning of <h:inputText> when I insert it from my form and it will return these spaces with my value that I inserted in it. So I should handle each value with mystring.tirm() to void the spaces. Can I use any something else to return this value without spaces? I know about converter and JavaScript, so can you give me another option to use? I don't want to use any converter and JavaScript.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I don't want to use any converter and JavaScript

There's no magic here. You have to write code to do the job. I gather that your concern is more that you don't want to repeat the same conversion job over every single input field.

In that case, just register a converter specifically on String.class via the forClass attribute of the @FacesConverter like below.

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

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        String trimmed = (submittedValue != null) ? submittedValue.trim() : null;
        return (trimmed == null || trimmed.isEmpty()) ? null : trimmed;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        return (modelValue != null) ? modelValue.toString() : "";
    }

}

This way you don't need to declare the converter in every single input field. It will get applied transparently on every String model value which doesn't already have an explicit converter registered.

The JavaScript way is not recommended as it runs entirely at the client side and endusers can easily disable and manipulate JavaScript. The JSF converter runs at server side and its outcome is not manipulatable by the enduser.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...