2

我有一个 JSF 转换器的基本标记处理程序,如下所示(为简洁起见,省略了几件事)。

<tag>
    <description>
        <![CDATA[
            Converts a string representation to 
            <code>java.math.BigDecimal</code> based on attribute values given.
        ]]>
    </description>
    <tag-name>convertBigDecimal</tag-name>
    <converter><converter-id>bigDecimalConverter</converter-id></converter>

    <attribute>
        <description>
            <![CDATA[
                <a href="https://en.wikipedia.org/wiki/ISO_4217">ISO 4217 currency code</a> such as INR, USD, GBP, NZD etc.
            ]]>
        </description>
        <name>currency</name>
        <type>java.lang.String</type>
    </attribute>

    <attribute>
        <description>
            <![CDATA[
                A boolean value or flag indicating whether to transform 
                this value to percentage or not. The default is false.
            ]]>
        </description>
        <name>percent</name>
        <type>java.lang.Boolean</type>
    </attribute>

    <attribute>
        <description>
            <![CDATA[
                A boolean value or flag indicating whether to use a 
                currency symbol (such as $) or not. The default is true.
            ]]>
        </description>
        <name>useCurrencySymbol</name>
        <type>java.lang.Boolean</type>
    </attribute>

    <!-- Other attributes. -->
</tag>

它有几个属性,旨在将字符串表示形式转换为其等效java.math.BigDecimal值和java.math.BigDecimal各种显示格式,例如带或不带货币符号的货币、百分比、带分组的数字、小数中的小数位数等。

当然,在给出的示例中,百分比和货币不能一起使用。因此,以下是完全有效的。

<my:convertBigDecimal currency="#{currencyCode}" groupingUsed="true" locale="#{locale}"/>

但是,以下内容将是无效的,并且如果尝试,预计会引发解析错误。

<my:convertBigDecimal percent="true"
                      currency="#{currencyCode}"
                      useCurrencySymbol="false"
                      groupingUsed="true"
                      locale="#{locale}"/>

例如,如果percent要尝试将该属性与与货币相关的任何其他属性(如currency, )一起尝试useCurrencySymbol,则假定 XML 解析器应该发出一个解析错误,阻止 XML 文档本身被解析。

是否有可能以某种方式强制解析器发出解析错误,如果尝试将不相关的属性与给定标记一起指定,以便可以省略转换器中的几个条件测试并且使用转换器的用户或应用程序开发人员可以被警告不要过早在标签中使用不相关的属性?

4

1 回答 1

2

不幸的是,不是通过.taglib.xml文件中的 XML 配置。只有通过注册的真实标签处理程序类才有可能<converter><handler-class>

<converter>
    <converter-id>bigDecimalConverter</converter-id>
    <handler-class>com.example.BigDecimalConverterHandler</handler-class>
</converter>

public class BigDecimalConverterHandler extends ConverterHandler {

    public BigDecimalConverterHandler(ConverterConfig config) {
        super(config);

        if (getAttribute("percent") != null && getAttribute("currency") != null) {
            throw new IllegalArgumentException("Hey there, it does not make sense to specify both 'percent' and 'currency' attributes.");
        }
    }

}
于 2016-03-09T10:53:02.870 回答