Converting Line Breaks to <br/>
Recently I was investigating an annoying problem using Struts. A user enters text into an htmls form's text area field. That information contains line breaks (\n) and is stored in a DB. When later on you retrieve the data and portray it in your browser - the line breaks are gone. While Struts is escaping automatically html entities (e.g. HTML tags in your text etc.) it does not automatically convert line breaks. If you have ever programmed in PHP you will be definitely familiar with a small little function that is doing preciselythat job called: nl2br (http://us2.php.net/manual/en/function.nl2br.php) Doing a little bit of research, it looks like there is no equivalent in J2EE. But but there are easy solutions. So by showing them here, I hope to save you some time searching the web. To me there are 2 viable ways of showing my DB results correctly. Either you do this little conversion it in either your Struts Action or in your Action Form. There you would simply do a: text = dbtext.replaceAll("\n", "<br />"); In my case, I got the data "buried" in a List containing multiple transfer objects, which would have made it necessary to iterate through the whole list, retrievingthe object, gettingthe String, do the conversion etc.. So I opted for solution 2 by doing the conversion straight in my JSP using JSTL. However the there is a little issue to keep in mind. <c:out value="${fn:replace(article.text,'\n','<br/>')}" escapeXml="false"/> This does not work and you get an ugly exception. What you need to do is to use instead <% pageContext.setAttribute("lf", "\n"); %> This works and was the solution I was finally ended up using. An alternative may be using the Jakarta Taglibs: http://jakarta.apache.org/taglibs/doc/string-doc/intro.html Sources: http://www.php.net |