How would I redisplay user-controlled input from a h:inputTextarea preserving linebreaks with JSF?

111 views Asked by At

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.

0

There are 0 answers