1

I have text that the user input in a textarea and I want to display it on a another page.

The first issue is that the linebreaks coming from the textarea are \r\n instead of br, but I could simply just replace all of them. The actual problem I need help with is displaying it after that:

h:outputText by default escapes everything, so to get the linebreaks to work I need to do escape="false", but for obvious reasons I don't want the user to be able to mess up the page by inputting other HTML tags or even worse, Javascript. So I need to somehow escape everything but the linebreaks.

How should I do this? Or is there maybe a different JSF component that would make this more simple?

Unfortunately pre tags or CSS white-space are not an option.

  • Try to use regex that might solve your problem – Noman ali abbasi Dec 12 '13 at 12:45
  • @Noman: Never ever suggest to use regex to parse HTML, let alone to sanitize input from attack vectors. This is plain stupid. Use a normal stack based parser and use regex only for the job it's designed for: regular language pattern matching. HTML is not a regular language. – BalusC Dec 12 '13 at 13:13
  • @BalusC thanks, I will keep it in mind :) – Noman ali abbasi Dec 12 '13 at 13:23

1 Answers1

2

Instead of replacing \n by <br> and using <h:outputText escape="false">, you can also just display the text preformatted so that \n appears as a true newline. You can use the element's CSS white-space property for this which can be set to pre, pre-wrap or pre-line.

E.g.

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

with

.preformatted {
    white-space: pre;
}

If you really intend to present the text as unescaped HTML, then you can sanitize XSS attack vectors away by using a HTML parser capable of the job, such as Jsoup. See also this answer which I posted yesterday: JSF OutputText with html style.

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • Unfortunately I can't use white-space in this specific case, but I'll take a look at Jsoup. Bummer that there is no built in way of doing this in JSF. You'd think that printing text from a textarea is quite a common usecase... – user3095339 Dec 12 '13 at 13:31
  • JSF is a HTML generator, not a HTML parser. Just use the right tool for the job. CSS would be the right tool for the job of styling the HTML presentation. It isn't JSF's fault that you for some unclear reason can't do that. – BalusC Dec 12 '13 at 13:32