Use a custom tag.
Hi,
I had the same problem. I though I'd post my code as I haven't found the solution elsewhere, and I expect it's a very common problem. I'm not saying it's the best code in the world, but it works.
My solution was to use a custom tag with a parameter. I'm assuming that most people are trying to get this to work in a JSP view, and would prefer to avoid scripting.
Given that I'm using a custom tag, I created my TLD and stuck it in WEB-INF:
Code:
<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" ...... etc. your IDE should do this bit for you ......>
<tlib-version>1.0</tlib-version>
<short-name>foo</short-name>
<uri>/WEB-INF/foo</uri>
<tag>
<name>nl2br</name>
<tag-class>foo.bar.NewLine2PageBreak</tag-class>
<body-content>scriptless</body-content>
<attribute>
<name>text</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
<type>java.lang.String</type>
</attribute>
</tag>
</taglib>
Now you need your tag handler class:
Code:
public class NewLine2PageBreak extends SimpleTagSupport {
private String text;
@Override
public void doTag() throws JspException {
JspWriter out = getJspContext().getOut();
try {
out.println(Utils.nl2br(text));
} catch (java.io.IOException ex) {
throw new JspException("Error in NewLine2PageBreak tag", ex);
}
}
public void setText(String text) {
this.text = text;
}
}
You'll notice I'm calling a static utility method from my Utils class. You don't have to separate it out like this, of course.
Code:
public static String nl2br(String myString) {
return myString.replaceAll(getLineSeparator(), "<br/>");
}
public static String getLineSeparator() {
return System.getProperty("line.separator");
}
You need a reference to the taglib in the JSP:
Code:
<%@taglib uri="/WEB-INF/foo" prefix="foo" %>
And this is how to use the custom tag:
Code:
<foo:nl2br text="${yourText}"/>
I hope that is of use to someone.