tags:

views:

66

answers:

1

How do I concatenate strings in EL?

I want to do something like this but it doesn't work:

${var1 == 0 ? 'hi' : 'hello ' + var2}

It throws an exception trying to cast 'hello' to a Double

+1  A: 

The + operator always means numerical addition in jsp el. To do string concatenation you would have to use multiple adjacent el expressions like ${str1}${str2}. If I read your example correctly this could be written as:

${var1 == 0 ? 'hi' : 'hello '}${var1 == 0 ? '' : var2}

Edit: Another possibility would be to use jstl, which is longer but might be clearer if there is more text that depends on var1:

<c:choose>
    <c:when test="${var1 == 0}">hi</c:when>
    <c:otherwise>hello <c:out value="${var2}"/></c:otherwise>
</c:choose>

the c:out might not be needed, depending on the jsp version.

Jörn Horstmann
I was hoping I wouldn't have to do that... repeating the condition every time. My example is a simplification, in the real scenario I would have to repeat the example 3 times each time i want to do it :(
Kyle