修饰JSF中的字符串h:outputText值

Ber*_*Ali 3 jsf trim

有没有办法把字符串JSF h:outPutTextValue?我的字符串是AB-A03,我只想显示最后3个字符.开放面具有任何可用的功能吗?

谢谢

Bal*_*usC 6

你可以用Converter这个工作.JSF有几个内置转换器,但没有人适合这个非常具体的功能要求,所以你需要创建一个自定义的转换器.

它相对简单,只需Converter根据合同实现接口:

public class MyConverter implements Converter {

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) throws ConverterException {
        // Write code here which converts the model value to display value.
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) throws ConverterException {
        // Write code here which converts the submitted value to model value.
        // This method won't be used in h:outputText, but in UIInput components only.
    }

}
Run Code Online (Sandbox Code Playgroud)

如果您正在使用JSF 2.0(您的问题历史记录确认了这一点),您可以使用@FacesConverter注释来注册转换器.您可以使用(默认)value属性为其分配转换器ID:

@FacesConverter("somethingConverter")
Run Code Online (Sandbox Code Playgroud)

(其中"something"应代表您尝试转换的模型值的具体名称,例如"zipcode"或其他任何内容)

以便您可以按如下方式引用它:

<h:outputText value="#{bean.something}" converter="somethingConverter" />
Run Code Online (Sandbox Code Playgroud)

对于您的特定功能要求,转换器实现可能如下所示(假设您实际上想要拆分-并仅返回最后一部分,这比"显示最后3个字符"更有意义):

@FacesConverter("somethingConverter")
public class SomethingConverter implements Converter {

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) throws ConverterException {
        if (!(modelValue instanceof String)) {
            return modelValue; // Or throw ConverterException, your choice.
        }

        String[] parts = ((String) modelValue).split("\\-");
        return parts[parts.length - 1];
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) throws ConverterException {
        throw new UnsupportedOperationException("Not implemented");
    }

}
Run Code Online (Sandbox Code Playgroud)