i'm trying to figure out how to most elegantly integrate something like PHP's nl2br() function into a current project done with JSF2/Spring. I could easily create getters using something like return text.replaceAll("\n","<br/>");
in my model classes, however that does seem like putting view related code where it does not belong. I have the same feeling about storing actual html content in my database.
I guess the cleanest solution would be using tags/EL for this, however i couldn't find something that seemed to do just that. How would you guys implement something like this? Thank you in advance, any hints are highly appreciated!

- 1,247
- 4
- 13
- 32
2 Answers
Well, in the first place JSF is a Web UI framework. So, anything that you expect to output to the user will end as HTML (with the only exception of javascript, though). So, I don't find it a grave violation of MVC (if any at all). Maybe you could even push the envelope and directly use <br/>
inside the text, instead of replacing \n
In a more general sense, if you have different lines/paragraphs in your text, the more flexible/standard solution would be break your text in the different elements and let your presentation logic handle it. So, instead of a properties with
presentationPage.introductionText=Ipse Lorum ...sum.\nVini vidi vinci.
You would end with
presentationPage.introductionText.par1=Ipse Lorum ...sum.
presentationPage.introductionText.par2=vini vidi vinci.

- 24,532
- 6
- 47
- 87
-
thanks for your answer, however as the backend is pure java, i can generate pretty much any view formats, not only html. The solution you proposed is pretty much what i did, since it seemed to be the cleanest way, however it is not a very good choice if the content is supposed to be editable via the frontend... – user871784 Nov 23 '12 at 09:56
-
You should have told it is user generated content, I was thinking more of application static content. With user code that must accessible from several interfaces you have to standarize in some way and make the "client" interfaces stick to it; `\n` for page breaks is as good as any other solution and it is easier to understand. – SJuan76 Nov 23 '12 at 10:19
-
Thank you, as for now it is in fact static site content, but i would like to have something like a standard concept for this kind of things that can also be used for user generated content or whatever may come along if needed. But thanks man, you definitly helped me to clarify the topic for me!Cheers – user871784 Nov 23 '12 at 11:19
Use either CSS, assuming that the text doesn't contain any HTML
<div style="white-space: pre">#{bean.text}</div>
Or create a custom EL function and then display it unescaped (Facelets implicitly escapes HTML)
<div><h:outputText value="#{my:nl2br(bean.text)}" escape="false" /></div>
You should only make absolutely sure that it's free of XSS.