有什麼方法可以將JSF字符串h:outPutTextValue?我的字符串是A-B-A03,我只想顯示最後3個字符。是否有openfaces有任何avialable功能來做到這一點?在JSF中修剪字符串h:outputText值
感謝
有什麼方法可以將JSF字符串h:outPutTextValue?我的字符串是A-B-A03,我只想顯示最後3個字符。是否有openfaces有任何avialable功能來做到這一點?在JSF中修剪字符串h:outputText值
感謝
你可以使用一個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")
(其中「東西」應該代表你想轉換,如「郵政編碼」模型值的具體名稱或不管它是什麼)
,這樣就可以引用它,如下:
<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");
}
}
你可以嘗試從使用fn:substring
功能:
${fn:substring('A-B-A03', 4, 7)}
如果字符串來從豆你可以添加一個額外的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頁面:
<h:outputText value="#{myBean.myStringTrimmed}"/>
非常感謝@BalusC提供的詳細解決方案,它確實有所幫助。 –
不客氣。 – BalusC