我有一个用于 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 文档本身被解析。
如果尝试将不相关的属性与给定标签一起指定,以便可以省略转换器中的多个条件测试并且用户或应用程序开发人员使用可以警告转换器不要过早在标签中使用不相关的属性吗?
最佳答案
不幸的是,不能通过 .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.");
}
}
}
关于jsf - 如果要在标签中指定不相关的标签属性,则强制 XML 解析器引发解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35885311/