How to concatenate Strings in EL? [duplicate]

2019-04-17 08:36发布

问题:

This question already has an answer here:

  • How to concatenate a String in EL? 5 answers

Apparently, you cannot use the normal + operator to append strings in jsp...at least its not working for me. Is there a way to do it? Fragment of my code that is relevant...

${fn:length(example.name) > 15 ? fn:substring(example.name,0,14) + '...' : example.name} // does not work because of + operator

回答1:

EL does not know a string concatenation operator. Instead, you would just inline multiple EL expressions together. The + operator is in EL exclusively a sum operator for numbers.

Here's one of the ways how you could do it:

<c:set var="tooLong" value="${fn:length(example.name) > 15}" />
${tooLong ? fn:substring(example.name,0,14) : example.name}${tooLong ? '...' : ''}

Another way is to use an EL function for this wherein you can handle this using pure Java. For an example, see the "EL functions" chapter near the bottom of my answer in Hidden features of JSP/Servlet. You would like to end up as something like:

${util:ellipsis(example.name, 15)}

with

public static String ellipsis(String text, int maxLength) {
    return (text.length() > maxLength) ? text.substring(0, maxLength - 1) + "..." : text;
}


标签: jsp el