问题
${x}="mit"
${Place['name_mit']}
will give result as US.
But if I try ${Place['name_'+x]}
I get error.
How to resolve this ?
回答1:
Yes, it fails to compile as +
operator is not used for string concatination (before EL 3.0, Java EE 7).
Just use concat
${Place['name_'.concat(x)]}
From Expression Language 3.0,
It is valid to use +
operator for concatenation of two strings.
${Place['name_'+x]} //valid as of EL 3.0
From EL 3.0 Specs
String Concatenation Operator
To evaluate
A += B
- Coerce A and B to String.
- Return the concatenated string of A and B.
回答2:
You can't concatenate the map key inline like that. This worked for me:
<%
Map<String, String> things = ImmutableMap.of("thing1", "a", "thing2", "b", "thing3", "c");
pageContext.setAttribute("things", things);
for (int i = 1; i <= 3; i++) {
String key = "thing" + i;
pageContext.setAttribute("key", key);
%>
<c:out value="${key}"/>: <c:out value="${things[key]}"/> <br>
<%
}
%>
Obviously, without context from your use case, I had to cobble together an appropriate page context state on my own. Substitute as necessary.
来源:https://stackoverflow.com/questions/19819475/concatenate-of-a-string-within-a-loop-in-jsp