如何防止空格形成JSF h:inputText [英] How to prevent spaces form JSF h:inputText

查看:135
本文介绍了如何防止空格形成JSF h:inputText的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的JSF 2.2应用程序中,当我创建JSF表单时,问题是当我从表单中插入<h:inputText>时可以在<h:inputText>的开头放置空格,并且它将返回带有我插入的值的这些空格.它.因此,我应该使用mystring.tirm()处理每个值以使空格无效.我可以使用其他方法返回此值而没有空格吗?我知道转换器和JavaScript,所以您能给我另一个选择吗?我不想使用任何转换器和JavaScript.

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.

推荐答案

我不想使用任何转换器和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.

在这种情况下,只需通过@FacesConverterforClass属性在String.class上专门注册一个转换器,如下所示.

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() : "";
    }

}

这样,您无需在每个输入字段中都声明转换器.它将透明地应用于尚未注册显式转换器的每个String模型值.

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.

不建议使用JavaScript方式,因为它完全在客户端运行,并且最终用户可以轻松禁用和操纵JavaScript. JSF转换器在服务器端运行,最终用户无法操纵其结果.

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.

这篇关于如何防止空格形成JSF h:inputText的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆