Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
836 views
in Technique[技术] by (71.8m points)

jsf - h:outputText does not break characters into new lines

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

text = "Text1
Text2
Text3";

I'm presenting it using <h:outputtext>.

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

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

Text1 Text2 Text3

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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" />

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" />

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>.

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.

E.g.

<h:outputText value="#{bean.text}" styleClass="preformatted" />
.preformatted {
    white-space: pre-wrap;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...