开发者

How to concatenate Strings in EL? [duplicate]

开发者 https://www.devze.com 2023-03-22 22:35 出处:网络
This question already has answers here:开发者_Python百科 How to concatenate a String in EL? (5 answers)
This question already has answers here: 开发者_Python百科 How to concatenate a String in EL? (5 answers) Closed 6 years ago.

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


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;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消