Concatenate of a string within a loop in JSP

守給你的承諾、 提交于 2019-12-25 06:59:33

问题


${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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!