如何将小于号放入 ChoiceFormat 模式中?

How can I put a less-than symbol into a ChoiceFormat pattern?

我有一条消息要放入 HTML 页面,我希望它对打印的内容数量敏感。 java.text.ChoiceFormat 救援,对吗?

text.messages=You have {0,choice,1#<b>one</b> message|1<<b>{0}</b> messages} waiting for you

这会导致 ChoiceFormat 的构造函数出错:

 java.lang.IllegalArgumentException: Choice Pattern incorrect: 1#<b>one</b> message|1<'<b>'{0}'</b>' messages

我已将问题缩小到消息中的 < 符号。没问题:我将使用 MessageFormat 的引用功能来解决这个问题:

text.messages=You have {0,choice,1#'<b>'one'</b>' message|1<'<b>'{0}'</b>' messages} waiting for you

不幸的是,这也失败了:

java.lang.IllegalArgumentException: Choice Pattern incorrect: 1#<b>one</b> message|1<''<b>''{0}''</b>'' messages

请注意单引号字符(MessageFormat 的转义字符)在错误消息中是如何加倍的。我觉得我很接近,但我似乎找不到任何解释如何在 ChoiceFormat 模式中使用 < 等特殊字符的文档。

这是我在失败时得到的完整堆栈跟踪:

Caused by: java.lang.IllegalArgumentException: Choice Pattern incorrect: 1#''<b>''one''</b>'' message|1<''<b>''{0}''</b>'' messages
        at java.text.MessageFormat.makeFormat(MessageFormat.java:1519)
    at java.text.MessageFormat.applyPattern(MessageFormat.java:479)
    at java.text.MessageFormat.<init>(MessageFormat.java:362)
    at org.apache.struts.util.MessageResources.getMessage(MessageResources.java:305)
    at org.apache.velocity.tools.struts.MessageTool.get(MessageTool.java:158)
    at org.apache.velocity.tools.struts.MessageTool.get(MessageTool.java:125)
    at org.apache.velocity.tools.struts.MessageTool.get(MessageTool.java:192)
[...]

您要找的是"escape sequences/characters"。在 HTML 中,您可以将 < 替换为 &lt;,将 > 替换为 &gt;

虽然我不记得 Java 中的 < 需要转义,但您可以在 Java 中的字符前加一个反斜杠 \ 来转义它.

希望对您有所帮助!

转义表:

对于Java

对于HTML

你走在正确的轨道上,但没有引用所有的人:

text.messages=You have {0,choice,1#'<b>'one'</b>' message|1<'<b>'{0}'</b>' messages} waiting for you

或者:

text.messages=You have {0,choice,1#'<b>one</b> message'|1<'<b>'{0}'</b> messages'} waiting for you

Apache Struts 1.x "helpfully" 在资源包中转义 single-quotes...大概是这样一个流浪 single-quote 不会破坏 MessageFormat.这是实现它的修订版:

http://svn.apache.org/viewvc?view=revision&revision=48526

可以禁用此转义,但必须在 per-MessageResources-basis:

上完成
<message-resources key="MyProperties" parameter="MyProperties">
  <set-property property="escape" value="false" />
</message-resources>

如果你想要一些属性被转义而另一些没有,你可以很容易地使用这样的技巧:

<message-resources key="MyProperties" parameter="MyProperties">
  <set-property property="escape" value="false" />
</message-resources>
<message-resources key="MyPropertiesEscaped" parameter="MyPropertiesEscaped">
  <set-property property="escape" value="true" />
</message-resources>