5

I have a web application running Java Tapestry, with a lot of user-inputted content. The only formatting that users may input is linebreaks.

I call a text string from a database, and output it into a template. The string contains line breaks as /r, which I replace with < br >. However, these are filtered on output, so the text looks like b<br>text text b<br> text. I think I can use outputRaw or writeRaw to fix this, but I can't find any info for how to add outputRaw or writeRaw to a Tapestry class or template.

The class is:

 public String getText() {
    KMedium textmedium = getTextmedium();
    return (textmedium == null || textmedium.getTextcontent() == null) ? "" : textmedium.getTextcontent().replaceAll("\r", "<br>");
    }

The tml is:

<p class="categorytext" id="${currentCategory.id}">
${getText()}
</p>

Where would I add the raw output handling to have my line breaks display properly?

Ila
  • 3,528
  • 8
  • 48
  • 76

3 Answers3

4

To answer my own question, this is how to output the results of $getText() as raw html:

Change the tml from this:

<p class="categorytext" id="${currentCategory.id}">
${getText()}
</p>

To this:

<p class="categorytext" id="${currentCategory.id}">
<t:outputraw value="${getText()}"/>
</p>
Andremoniy
  • 34,031
  • 20
  • 135
  • 241
Ila
  • 3,528
  • 8
  • 48
  • 76
3

Note that this is quite dangerous as you are likely opening your site to an XSS attack. You may need to use jsoup or similar to sanitize the input.

lance-java
  • 25,497
  • 4
  • 59
  • 101
2

An alternative might be:

<p class="categorytext" id="${currentCategory.id}">
   <t:loop source="textLines" value="singleLine">
    ${singleLine}  <br/>
   </t:loop>
 </p>

This assumes a a getTextLines() method that returns a List or array of Strings; it could use the same logic as your getText() but split the result on CRs. This would do a better job when the text lines contain unsafe characters such as & or <. With a little more work, you could add the <br> only between lines (not after each line) ... and this feels like it might be a nice component as well.

Howard M. Lewis Ship
  • 2,247
  • 15
  • 23