JSP EL String concatenation [duplicate]

2019-01-21 06:25发布

问题:

This question already has an answer here:

  • How to concatenate a String in EL? 5 answers

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:

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.



回答2:

Using java string concatenation works better.

#{var1 == 0 ? 'hi' : 'hello'.concat(var2)}

The benefit here is you can also pass this into a function, for instance

#{myCode:assertFalse(myVar == "foo", "bad myVar value: ".concat(myVar).concat(", should be foo"))}


回答3:

I know this is an old topic, but the answer to this question has changed in the past six months, and it's important to note that change, IMO (since I found this by Googling "el concatenate strings").

As of EL Expression 3.0 (public ballot approved August 2012, released with Java EE 7), a twist on the syntax the questioner originally used is now valid:

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

There was much disagreement with the use of += instead of +, but it is what it is. This will correctly evaluate and concatenate the strings as expected. You can also use the cat operator instead of the += operator:

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

While this is now legal, note that you won't be able to use it until your web container (Tomcat, Jetty, GlassFish, etc.) releases a new version that supports Java EE 7/EL 3.0. This is expected sometime before the end of 2013, perhaps as early as the fall.

Edited 2015-02-19 to note that the final operator was += and not + as originally answered.



回答4:

One more alternative to all that was already mentioned:

<c:set var="hellovar2" value="hello ${var2}" />
${var1 == 0 ? 'hi' : hellovar2}


标签: jsp el