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

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

问题描述

我有一个 String 变量,它包含回车符和换行符 .

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

text = "Text1
Text2
Text3";

我使用 来呈现它.

<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

为什么 不将 分成新行?

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

我该怎么办?我是否必须将 替换为 <br/>?

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

推荐答案

HTML 中的换行符由 <br/> 元素表示,而不是由 特点.更重要的是,通过右键单击打开普通的 HTML 源代码,在浏览器中查看源代码,您将看到" 到处都是.然而,它们在最终的 HTML 演示中并未如此呈现.只有
会.

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

所以,是的,您需要将它们替换为 <br/>.您可以使用 JSTL 函数:

So, yes, you need to replace them by <br />. You can use JSTL functions for this:

<... xmlns:fn="http://xmlns.jcp.org/jsp/jstl/functions">

<h:outputText value="#{fn:replace(bean.text,'
','&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 的异常.

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" 使它对 XSS 攻击,如果该值来自最终用户输入而您没有 事先清理它.更好的选择是继续使用 并设置 CSS white-space 属性 在父元素上预先格式化.如果您想在块元素的上下文中换行,请设置 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 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 不会将 个字符分成新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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