且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

h:outputText不会将\ r \ n字符分成新行

更新时间:2023-12-04 10:56:58

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;
}