-1

I am using primefaces and I would like to display to users the non-printable characters ( \n,\t,\r - should be shown as they are, not rendered).

I use the <h:outputText> command. I read the content from a file.

For example, the file has the following content:

test new line a new line

In java, windows this renders as: test\n new line\n a new line. The output should be the same :Hello\n newline\n a new line.

How can I do that? The values are not printed at all: "Hello new line a new line".

Found solution: To render properly (e.g '\n' should be displayed) I added a new backslash: \n became \\n.

Thank you, Luisa

  • 1
    Please learn how to actually display a \n in html. If that works, you have the JSF solution to (not even PF related since `h:outputText` is plain jsf – Kukeltje Jan 20 '17 at 15:14
  • Indeed. If you stumble upon a basic HTML problem in JSF, first try to solve it in plain HTML rather than JSF. Once found the solution in plain HTML, simply rewrite JSF code in such way that it produces exactly the desired HTML output. It will end up in less confusion and a more understandable solution. – BalusC Jan 20 '17 at 15:26
  • Thank you, I found the solution by adding another backslash: e.g. \n became \\n. – Luisa Bradusca Jan 26 '17 at 10:11

2 Answers2

-1

You can use the following method from the Apache Commons project on the desired strings in your backing bean (it escapes all Java-like special characters):

https://commons.apache.org/proper/commons-lang/javadocs/api-3.5/org/apache/commons/lang3/StringEscapeUtils.html#escapeJava-java.lang.String-

Example:

private String escapeString = StringEscapeUtils.escapeJava("Hello \\n this is new line");

public String getEscapeString() {
    return escapeString;
}

with

<h:outputText value="#{testViewBean.escapeString}"/>

prints

Hello \\n this is new line
Tomek
  • 494
  • 2
  • 11
  • 1
    But in HTML this shows nothing special since in html a \n means nothing. (unless you use 'preformatted text'). \n should be replaced by `
    `
    – Kukeltje Jan 20 '17 at 15:13
  • I thought, this was his intention, I misunderstood the question. – Tomek Jan 20 '17 at 15:30
  • It is not strange you misunderstood. That tagging was not that good. For plain java you are right. – Kukeltje Jan 21 '17 at 16:23
-2

You need to set escape property false as by default it is true. As explained by MkYong.

https://www.mkyong.com/jsf2/jsf-2-outputtext-example/

  • 1
    This won't work, because it only escapes characters that are sensitive in HTML and XML markup. – Tomek Jan 20 '17 at 14:42