How to concatenate Strings in EL? [duplicate]

2019-04-17 08:16发布

This question already has an answer here:

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

标签: jsp el
1条回答
smile是对你的礼貌
2楼-- · 2019-04-17 08:55

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;
}
查看更多
登录 后发表回答