2012-12-15

PHP's nl2br equivalent in JSPs

Some of PHP’s built-in functions can be quite handy. One of these is nl2br, which transforms newlines (\n and other variants) into HTML line breaks (<br>) — more precisely, it puts a <br> before each newline.
It has been used, and sometimes is still used, when echoing a CLOB on a webpage.

Actually, this function is no longer necessary: with the CSS property white-space you can do the same on the client-side in a neat and efficient way. However, this post is just an example on how to create something resembling PHP’s built-in functions using the instruments of Java EE.

The best way is to use a Tag Library (aka “taglib”). As you probably know, the JSP standard supports “actions”: basically they are XML tags being parsed on the server-side that provide a clean alternative to messy scripting (i.e. <% ... %>) for running server-side logic like, for example, iterate over a collection. Have a look to the JSTL (JavaServer Pages Standard Tag Library) to learn about the “server-side tags” provided by the JSP standard.

OK, let’s get to the point. First of all, create a file named myutils.tld under the /WEB-INF/ directory of your web project.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN"
"http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd">
<taglib>
    <tlib-version>1.0</tlib-version>
    <jsp-version>1.2</jsp-version>
    <short-name>myutils</short-name>
    <tag>
        <name>nl2br</name>
        <tag-class>somepackage.Nl2br</tag-class>
        <body-content>JSP</body-content>
    </tag>
</taglib>

Please notice the reference to a class named Nl2br under the package somepackage (change it to whatever you want). Here is the Nl2br class:

package somepackage;

import java.io.IOException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class Nl2br extends BodyTagSupport {

    private static final long serialVersionUID = 7176638069994199184L;

    @Override
    public int doAfterBody() throws JspException {
        try {
            BodyContent bodycontent = getBodyContent();
            String body = bodycontent.getString();
            JspWriter out = bodycontent.getEnclosingWriter();
            if (body != null) {
                out.print(nl2br(body));
            }
        } catch (IOException ioe) {
            throw new JspException("Error:" + ioe.getMessage());
        }
        return SKIP_BODY;
    }

    private static String nl2br(String s) {
        return s.replaceAll("\n", "<br>\n");
    }

}

In order to use the new tag, get into your JSP and put this line after the <%@ page ... %> directive:

<%@ taglib prefix="u" uri="/WEB-INF/myutils.tld"%>

Then, you can use the tag as follows:

<u:nl2br>Put anything here</u:nl2br>

You can extend the myutils.tld tag library adding whatever you want, by declaring more <tag> blocks. You can easily adapt the Nl2br class by replacing line 21 with any operation you need for processing the body of the tag.

Actually, Tag Libraries can be quite complex, and I cannot deal with all their features in this post! Just to make some example, custom tags can have parameters, can be body-less and can even be nested.
For more information, I suggest you to read this tutorial.

Tags: java, php
comments powered by Disqus
Fork me on GitHub