此行为由 HTML 规范定义:
对于除PRE 之外的所有 HTML 元素,空格序列分隔“单词”(我们在这里使用术语“单词”来表示“非空格字符的序列”)。在格式化文本时,用户代理应该识别这些词,并根据特定的书面语言(脚本)和目标媒体的约定对它们进行布局。
请注意,如果您使用的是 XHTML,attributes 和 code point U+000C 的处理方式会有所不同。
对于大多数文本,空白序列的呈现与单个空格没有任何不同。
由于这是用于outputText 控件,因此您可以使用单向转换器来实现不间断空间解决方案:
package myconverters;
// imports
public class SpacePreserver implements Converter {
private static final char NO_BREAK_SPACE = '\u00A0';
public String getAsString(FacesContext context, UIComponent component,
Object value) {
if (component instanceof EditableValueHolder) {
throw new IllegalArgumentException(
"Cannot use SpacePreserver converter on editable controls.");
}
return value == null ? null : value.toString().replace(' ', NO_BREAK_SPACE);
}
public Object getAsObject(FacesContext context, UIComponent component,
String value) {
throw new UnsupportedOperationException("Output converter only");
}
}
这可以使用 faces-config.xml 条目定义(以及其他方式):
<converter>
<converter-id>spacePreserver</converter-id>
<converter-class>myconverters.SpacePreserver</converter-class>
</converter>
然后您可以将其添加到您的输出控件中:
<h:outputText id="text1" value="a b c" converter="spacePreserver" />
此代码使用 JSF 1.1 和 UTF-8 编码的 JSP 2.0 视图进行了测试。请注意,使用不间断空格将禁止换行。