How to avoid repetitions / use constants in Facelets page?

一个人想着一个人 提交于 2019-12-02 18:52:05

问题


In a Facelets page, I have various <h:inputText> and <h:outputText> components, which all need the same converter.

I'd like to avoid repeating the converter with all its parameters, like this:

<h:inputText id="bla" value="#{mybean.val}" >
  <f:convertNumber locale="en" maxFractionDigits="3" minFractionDigits="3"/>
</h:inputText>
[...]
<h:outputText id="bla2" value="#{mybean.val2}" >
  <f:convertNumber locale="en" maxFractionDigits="3" minFractionDigits="3"/>
</h:outputText>
[...]
<h:inputText id="bla3" value="#{mybean.val3}" >
  <f:convertNumber locale="en" maxFractionDigits="3" minFractionDigits="3"/>
</h:inputText>

What is the best way to avoid these repetitions?

I think I could use <ui:include>, but that would mean I'd have to have a separate file just for a single line, which seems a bit silly. Is there an alternative?


回答1:


Subclass the converter whereby you set the defaults in the constructor.

@FacesConverter("defaultNumberConverter")
public class DefaultNumberConverter extends NumberConverter {

    public DefaultNumberConverter() {
        setLocale(Locale.ENGLISH);
        setMinFractionDigits(3);
        setMaxFractionDigits(3);
    }

}

And use it as follows:

<h:inputText id="bla" value="#{mybean.val}" converter="defaultNumberConverter" />
[...]
<h:outputText id="bla2" value="#{mybean.val2}" converter="defaultNumberConverter" />
[...]
<h:inputText id="bla3" value="#{mybean.val3}" converter="defaultNumberConverter" />

To get a step further, create a tag file or perhaps a composite wrapping the desired components:

<my:inputNumber id="bla" value="#{mybean.val}" />
[...]
<my:outputNumber id="bla2" value="#{mybean.val2}" />
[...]
<my:inputNumber id="bla3" value="#{mybean.val3}" />


来源:https://stackoverflow.com/questions/16919199/how-to-avoid-repetitions-use-constants-in-facelets-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!