3

JSF h:outPutTextValue をストリングする方法はありますか? 私の文字列は AB-A03 です。最後の 3 文字だけを表示したいのですが、openfaces にはこれを行うための利用可能な機能がありますか?

ありがとう

4

3 に答える 3

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

}
于 2012-08-28T11:50:36.120 に答える
4

JSTLfn:substringの関数を試して使用できます。

${fn:substring('A-B-A03', 4, 7)}
于 2012-08-28T11:50:15.030 に答える
2

文字列が Bean からのものである場合は、追加のゲッターを追加して、トリミングされたバージョンを返すことができます。

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}"/>
于 2012-08-29T19:30:21.853 に答える