h:outputText不会将\ r \ n字符分成新行 [英] h:outputText does not break \r\n characters into new lines

查看:122
本文介绍了h:outputText不会将\ r \ n字符分成新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个String变量,其中包含回车符和换行\r\n.

I have a String variable which contains carriage returns and new lines \r\n.

text = "Text1\r\nText2\r\nText3";

我正在使用<h:outputtext>展示它.

<h:outputText value="#{bean.text}" />

但是它不能识别换行符,并在网络浏览器中显示如下.

But it doesn't recognize the new line characters and shows as below in webbrowser.

文本1文本2文本3

Text1 Text2 Text3

<h:outputText>为什么不将\n分解为新行?

Why doesn't the <h:outputText> break \n into new lines?

我该怎么办?我必须用<br />替换\n吗?

What should I do? Do I have to replace \n with <br />?

推荐答案

HTML中的换行符由<br />元素表示,而不由\n字符表示.甚至更多,通过右键单击打开平均HTML源代码,在浏览器中查看源代码,您将在所有位置看到" \n.但是,它们不会在最终的HTML演示文稿中呈现.只有<br />会.

Linebreaks in HTML are represented by <br /> element, not by the \n character. Even more, open the average HTML source code by rightclick, View Source in browser and you'll "see" \n over all place. They are however not presented as such in the final HTML presentation. Only the <br /> will.

所以,是的,您需要用<br />替换它们.

So, yes, you need to replace them by <br />.

<h:outputText value="#{fn:replace(bean.text,'\n','&lt;br/&gt;')}" escape="false" />

注意:当使用Apache EL而不是Oracle EL时,请像\\n一样两次转义反斜杠.

Note: when using Apache EL instead of Oracle EL, double-escape the backslash as in \\n.

<h:outputText value="#{fn:replace(bean.text,'\\n','&lt;br/&gt;')}" escape="false" />

否则,您将遇到消息Failed to parse the expression with root cause org.apache.el.parser.ParseException: Encountered <ILLEGAL_CHARACTER>的异常.

Otherwise you will face an exception with the message Failed to parse the expression with root cause org.apache.el.parser.ParseException: Encountered <ILLEGAL_CHARACTER>.

然而,这一切都很丑陋,escape="false"使其对将其消毒.更好的选择是继续使用\n并设置 CSS white-space属性,以在父元素上进行预格式化.如果要将行换行到block元素的上下文中,请设置pre-wrap.或者,如果您也想折叠空格和制表符,请设置pre-line.

This all is however ugly and the escape="false" makes it sensitive to XSS attacks if the value comes from enduser input and you don't sanitize it beforehand. A better alternative is to keep using \n and set CSS white-space property to preformatted on the parent element. If you'd like to wrap lines inside the context of a block element, then set pre-wrap. Or if you'd like to collapse spaces and tabs as well, then set pre-line.

例如

<h:outputText value="#{bean.text}" styleClass="preformatted" />

.preformatted {
    white-space: pre-wrap;
}

这篇关于h:outputText不会将\ r \ n字符分成新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆