Question

I have the following JSTL code in my JSP. I am splitting a String into an array using the newline character (\n) as the delimiter. I am then trying to add a <br /> to each member and then display it on the page, but none of the elements are being displayed. I'm just getting white space. Can anyone help me?

<c:set var="comment" value="${bulletin.note}" />
<c:set var="comment" value="${fn:split(comment, '\\\\n')}" />
<c:forEach var="line" items="${comment}">
    <c:set var="line" value="${fn.join(line, '<br />')}" />
    <c:out value="${line}" /><br>
</c:forEach>
Was it helpful?

Solution 3

I have solved this problem by writing the following custom tag:

public class NotePrint extends SimpleTagSupport {
    private String note;

    public void setNote(String note) {
        this.note = note;
    }

    public String getNote() {
        return note;
    }

    public void doTag() throws JspException, IOException {
        PageContext pageContext = (PageContext) getJspContext();
        JspWriter out = pageContext.getOut();
        note.replace("\n\n", "\n ");
        String[] noteArray = note.split("\n");

        for (int i = 0; i < noteArray.length; i++) {
            if (i == noteArray.length - 1) {
                out.println(noteArray[i]);

            } else {
                out.println(noteArray[i] + "<br />");
            }
        }
    }
}

OTHER TIPS

sample codes, like your type:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title>JSTL fn:split() example</title>
</head>
<body>
<c:set var="msg" value="This is an example of JSTL function"/>
<c:set var="arrayofmsg" value="${fn:split(msg,' ')}"/>
<c:forEach var="i" begin="0" end="6">
 arrayofmsg[${i}]: ${arrayofmsg[i]}<br>
</c:forEach>
</body>
</html>

The variable comment contains an array of data. You just have to iterate on this array using c:foreach:

<c:set var="comment" value="${bulletin.note}" />
<c:set var="comment" value="${fn:split(comment, '\\\\n')}" />
<c:forEach var="line" items="${comment}">
    <c:out value="${line}" /><br>
</c:forEach>

And if you want to use JSTL join, the syntax is fn:join (and not fn.join).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top