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

时间:2012-08-28 11:06:58

标签: jsf trim

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

由于

3 个答案:

答案 0 :(得分: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.
    }

}

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

@FacesConverter("somethingConverter")

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

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

<h:outputText value="#{bean.something}" converter="somethingConverter" />

对于您的特定功能要求,转换器实现可能如下所示(假设您实际想要在-上拆分并仅返回最后一部分,这比“显示最后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");
    }

}

答案 1 :(得分:3)

您可以尝试使用JSTL中的fn:substring函数:

${fn:substring('A-B-A03', 4, 7)}

答案 2 :(得分:2)

如果你的字符串来自bean,你可以添加一个额外的getter来返回修剪版本:

private String myString = "A-B-A03";

public String getMyStringTrimmed()
{
  // You could also use java.lang.String.substring with some ifs here
  return org.apache.commons.lang.StringUtils.substring(myString, -3);
}

现在您可以在JSF页面中使用getter:

<h:outputText value="#{myBean.myStringTrimmed}"/>
相关问题