45

I have a list of bean objects passed into my JSP page, and one of them is a comment field. This field may contain newlines, and I want to replace them with semicolons using JSTL, so that the field can be displayed in a text input. I have found one solution, but it's not very elegant. I'll post below as a possibility.

parkerfath
  • 1,648
  • 1
  • 12
  • 18

14 Answers14

55

Here is a solution I found. It doesn't seem very elegant, though:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<% pageContext.setAttribute("newLineChar", "\n"); %>

${fn:replace(item.comments, newLineChar, "; ")}
parkerfath
  • 1,648
  • 1
  • 12
  • 18
  • I'm accepting this, even though it's my own answer, because it's simplest and I've found it to actually work. – parkerfath Feb 12 '09 at 00:06
  • That's unnecessary. Just escape the backslash: http://stackoverflow.com/questions/58054/how-can-i-replace-newline-characters-using-jsp-and-jstl/1690942#1690942 – BalusC Feb 11 '10 at 11:37
  • 2
    I tried just escaping the backslash, which didn't work either. My above-listed method of setting the pageContext attribute is still the only way I can get it working. Though as BalusC says, you may have better luck with some of the simpler methods. Probably good to have all the options here. – parkerfath Feb 19 '10 at 19:44
  • As always, be careful about the different between Windows and Unix newlines (use "\r\n" for the former). – pimlottc Jul 12 '10 at 17:01
  • Nothing worked for me except this one. Neither escaping the backslash, nor using c:set. – Amir M Nov 07 '16 at 07:45
19

Just use fn:replace() function to replace \n by ;.

${fn:replace(data, '\n', ';')}

In case you're using Apache's EL implementation instead of Oracle's EL reference implementation (i.e. when you're using Tomcat, TomEE, JBoss, etc instead of GlassFish, Payara, WildFly, WebSphere, etc), then you need to re-escape the backslash.

${fn:replace(data, '\\n', ';')}
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
16

This is similar to the accepted answer (because it is using Java to represent the newline rather than EL) but here the <c:set/> element is used to set the attribute:

<c:set var="newline" value="<%= \"\n\" %>" />
${fn:replace(myAddress, newline, "<br />")}

The following snippet also works, but the second line of the <c:set/> element cannot be indented (and may look uglier):

    <c:set var="newline" value="
" /><!--this line can't be indented -->
    ${fn:replace(myAddress, newline, "<br />")}
andy
  • 2,953
  • 2
  • 24
  • 26
8

This solution is more elegant than your own solution which is setting the pagecontext attribute directly. You should use the <c:set> tag for this:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

<c:set var="newLine" value="\n"/>
${fn:replace(data, newLine, "; ")}

BTW: ${fn:replace(data, "\n", ";")} does NOT work.

simon
  • 12,666
  • 26
  • 78
  • 113
bousch
  • 281
  • 2
  • 4
  • 1
    This doesn't work for me in Resin 3, whereas the top answer using the pageContext scriptlet does. – pimlottc Jul 12 '10 at 16:45
  • I guess that would be a bug because according to the standards it should work. – bousch Jul 14 '10 at 13:01
  • 1
    @pimlottc Replace the `"` with `'` in `${fn:replace(data, "\n", ";")}` and it should work: `${fn:replace(data, '\n', ';')}`. Otherwise this, for example, will not work: `` because of the double quotes after value. – MartijnvdB Dec 28 '11 at 13:50
  • @HeadFirst - his solution is intended for use in an HTML page; your modification makes the solution work in XHTML – Daniel F. Thornton Dec 15 '12 at 19:04
4

This does not work for me:

<c:set var="newline" value="\n"/>
${fn:replace(data, newLine, "; ")}

This does:

<% pageContext.setAttribute("newLineChar", "\n"); %> 
${fn:replace(item.comments, newLineChar, "; ")}
4

You could create your own JSP function. http://java.sun.com/j2ee/1.4/docs/tutorial/doc/JSPTags6.html

This is roughly what you need to do.

Create a tag library descriptor file
/src/META-INF/sf.tld

<?xml version="1.0" encoding="UTF-8"?>
<taglib version="2.0" xmlns="http://java.sun.com/xml/ns/j2ee" 
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee web-jsptaglibrary_2_0.xsd">
  <tlib-version>1.0</tlib-version>
  <short-name>sf</short-name>
  <uri>http://www.stackoverflow.com</uri>
  <function>
    <name>clean</name>
    <function-class>com.stackoverflow.web.tag.function.TagUtils</function-class>
    <function-signature>
      java.lang.String clean(java.lang.String)
    </function-signature>
  </function>
</taglib>

Create a Java class for the functions logic.
com.stackoverflow.web.tag.function.TagUtils

package com.stackoverflow.web.tag.function;

import javax.servlet.jsp.tagext.TagSupport;

public class TagUtils extends TagSupport {
  public static String clean(String comment) {
    return comment.replaceAll("\n", "; ");
  }
}

In your JSP you can access your function in the following way.

<%@ taglib prefix="sf" uri="http://www.stackoverflow.com"%>
${sf:clean(item.comments)}
Geekygecko
  • 3,942
  • 2
  • 25
  • 21
  • should be ${sf:clean(item.comments)} ... I used this solution.. seems cleaner than the scriptlet – danb Feb 09 '10 at 18:35
  • @danb: you missed my answer? http://stackoverflow.com/questions/58054/how-can-i-replace-newline-characters-using-jsp-and-jstl/1690942#1690942 – BalusC Feb 11 '10 at 11:36
4

If what you really need is a \n symbol you can use the advice from here:

${fn:replace(text, "
", "<br/>")}

or

<c:set var="nl" value="
" /><%-- this is a new line --%>

This includes the new line in your string literal.

Leonid
  • 184
  • 4
2

This is a valid solution for the JSP EL:

"${fn:split(string1, Character.valueOf(10))}"
josliber
  • 43,891
  • 12
  • 98
  • 133
2

You should be able to do it with fn:replace.

You will need to import the tag library into your JSP with the following declaration:

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>

Then you can use the following expression to replace occurrences of newline in ${data} with a semicolon:

${fn:replace(data, "\n", ";")}

The documentation is not great on this stuff and I have not had the opportunity to test it.

Brian Matthews
  • 8,506
  • 7
  • 46
  • 68
  • I'm pretty sure this is what I tried first, and it didn't work. I don't really have time to re-test it, though, so I may be wrong. – parkerfath Sep 12 '08 at 22:52
  • I think this answer is pretty much the same as mine (see below), but without the additional pageContext.setAttribute(). Do you know if there is maybe some setting that I haven't set that causes me to need to call this extra method? – parkerfath Sep 30 '08 at 22:16
  • I get this error: org.apache.jasper.JasperException: /WEB-INF/jsp/team/alarms.jsp(11,2) "${fn:replace(blob, "\n", ";")}" contains invalid expression(s): javax.servlet.jsp.el.ELException: Encountered ""\n", expected one of [, , etc. – parkerfath Feb 12 '09 at 00:06
2

\n does not represent the newline character in an EL expression.

The solution which sets a pageContext attribute to the newline character and then uses it with JSTL's fn:replace function does work.

However, I prefer to use the Jakarta String Tab Library to solve this problem:

<%@ taglib prefix="str" uri="http://jakarta.apache.org/taglibs/string-1.1" %>
...
<str:replace var="result" replace="~n" with=";" newlineToken="~n">
Text containing newlines
</str:replace>
...

You can use whatever you want for the newlineToken; "~n" is unlikely to show up in the text I'm doing the replacement on, so it was a reasonable choice for me.

Matt
  • 2,187
  • 1
  • 16
  • 23
1

More easily:

<str:replace var="your_Var_replaced" replace="\n" with="Your ney caracter" newlineToken="\n">${your_Var_to_replaced}</str:replace>  
brunohop
  • 11
  • 1
0

For the record, I came across this post while tackling this problem:

A multi-line string in JSTL gets added as the title attribute of a textarea. Javascript then adds this as the default text of the textarea. In order to clear this text on focus the value needs to equal the title... but fails as many text-editors put \r\n instead of \n. So the follownig will get rid of the unwanted \r:

<% pageContext.setAttribute("newLineChar", "\r"); %> 
<c:set var="textAreaDefault" value="${fn:replace(textAreaDefault, newLineChar, '')}" />
wheresrhys
  • 22,558
  • 19
  • 94
  • 162
0

In the value while setting the var, press ENTER between the double quotes.

${fn:replace(data, newLineChar, ";")}

0

You could write your own JSP function to do the replacement.

This means you'd end up with something like:

<%@ taglib prefix="ns" uri="..." %>
...
${ns:replace(data)}

Where ns is a namespace prefix you define and replace is your JSP function.

These functions are pretty easy to implement (they're just a static method) although I can't seem to find a good reference for writing these at the moment.

Walter Rumsby
  • 7,435
  • 5
  • 41
  • 36