JSF trimming white spaces

≯℡__Kan透↙ 提交于 2019-12-10 04:09:59

问题


HI,

I have an input field in which I want to trim any leading/trailing whitespaces. We are using JSF and binding the input field to a backing bean in the jsp using:

<h:inputText id="inputSN" value="#{regBean.inputSN}" maxlength="10"/>

My question is that besides validation can this be done in the jsp? I know we can also do this using the trim() java function in the Handler, but just wondering if there is a more elegant way to achieve this in JSF.

Thanks.


回答1:


You could use a Converter (tutorial).




回答2:


As suggested by McDowell and BalusC, you can create a Converter, and register it with @FacesConvert annotation for the String class. And then in the getAsObject method check the UIComponent type and apply the trimming only for the HtmlInputText components.

@FacesConverter(forClass = String.class)
public class StringTrimConverter implements Serializable, javax.faces.convert.Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent cmp, String value) {

        if (value != null && cmp instanceof HtmlInputText) {
            // trim the entered value in a HtmlInputText before doing validation/updating the model
            return value.trim();
        }

        return value;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent cmp, Object value) {

        if (value != null) {
            // return the value as is for presentation
            return value.toString();
        }
        return null;
    }

}



回答3:


I answered a similar question here

Basically you can either create your own component that is a copy of inputText which automatically trims, or you can extend the inputText and add trim attribute that trims if true.




回答4:


I resolved this by just using the trim() function in the handler before doing any processing. it just seemed like the most straight forward way of doing this.



来源:https://stackoverflow.com/questions/2030086/jsf-trimming-white-spaces

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