'StringEscapeUtils is unescaping everything, except newlines (\n)

I try to escape and unescape large text using the StringEscapeUtils from Apache Commons library (v. 1.7) that will be stored and retrieved from a database, in this case a H2 database. Almost every special character is escaped and unescaped successfully except for the new line. I am using Spring Boot (v2.1.3.) with thymeleaf.

So for instance, if I try to store the following text:

 He didn't say, "Stop!"

 This is a new line!

It will store the text as:

He didn't say, \"Stop!\"\r\n\r\nThis is a new line!

Which is good. But when I unescape it with the unescapeJava method the new line character is not working correctly. I get

He didn't say, "Stop!" This is a new line!

Edit:

The unescapeJava method works when the text is displayed in a html textarea. But when it is rendered as plain html, the linebreak is not working.



Solution 1:[1]

The unescapeJava method works when the text is displayed in a html textarea. But when it is rendered as plain html, the linebreak is not working.

Please check your HTML source, it most likely is there

In HTML a newline in source does not introduce a newline on screen, if you want that you should replace newlines with for example <br/> tags.

See more at:

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/br

Solution 2:[2]

What @Martin van Wingerden says is correct. A newline in source does not introduce / render it on screen. I found this thread

Render a string in HTML and preserve spaces and linebreaks

which explains that you can use CSS white-space: pre-wrap that will preserve white spaces and line breaks in formatting.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Martin van Wingerden
Solution 2 EnJoY