0

After some googling I found that JSF generally sanitizes all user-input during display through any component by default, the best option I see is displaying the user-input through an h:outputText with escaping explicitly disabled, like so:

<h:outputText value="#{bean.userInput}" escape="false" />

But this requires me to sanitize the input myself, then replacing linebreaks by <br /> tags manually and hoping it is all stable and safe (what if the doctype switches from XHTML to HTML5 for example? I would have to manually change the <br /> to a <br> in my code etc.). For sanitation I was thinking of using the Apache Commons helper function StringEscapeUtils.escapeHtml():

myBean.setUserInput(StringEscapeUtils.escapeHtml(userInput)
    .replaceAll("(\r\n|\r|\n|\n\r)", "<br />"));

..but this leaves me with another depedency and writing my own HTML escape function probably just opens Pandora's outputbox..

So is there a "best practice" clean and solid JSF way to accomplish this seemingly simple and common use case?

(I'm also already using RichFaces if that helps)


Edit: The apparent duplicate isn't one, as it also introduces another dependency and ignores my core question: whether there is a way to preserve the linebreaks without doing my own escaping and without replacing linebreaks by literal <br /> tags myself in the first place. Just preserving the linebreaks.

Edit 2: Question sufficiently answered by the links in the comments.

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
user777
  • 906
  • 5
  • 16
  • 1
    As you seem to worry more about linebreaks than about sanitizing, here are other dupes: http://stackoverflow.com/questions/3410526/how-to-implement-a-possibility-for-user-to-post-some-html-formatted-data-in-a-sa/ and http://stackoverflow.com/questions/18210987/textarea-preformatting-and-wrapping-in-houtputtext/ – BalusC Jun 16 '15 at 17:33
  • I've seen the edit. Still looks like a dupe to me. As BalusC says, [CSS white-space](https://developer.mozilla.org/en-US/docs/Web/CSS/white-space) is probably what you're looking for, but that's just basic CSS, nothing to do with JSF or any other web framework. – DavidS Jun 16 '15 at 18:35
  • You can always use `
    `. The linebreaks are being preserved, browsers just ignore them.
    – Makhiel Jun 17 '15 at 11:02
  • Thanks guys that's true – user777 Jun 17 '15 at 16:05

0 Answers0