1

I need to retrieve values from a map of type Map <String, String> in jsp based on a condition. The condition is to compare map key with variable and if the key equals the variable show the value pertaining to that key. Here's what I am doing:

<c:if test="${ myMap.key eq myVariable }">
<jsp:getvalueof var="testVariable" value = "${ myMap.value }" />
</c:if>

What I am expecting to get is if the myMap.key equals myVariable, I should get the value pertaining to that key in "test" variable.

But this thing is not working. Please any idea anyone?

Thanks in advance :)

ATG Pune
  • 13
  • 4

3 Answers3

3

You can directly access the map and get the value into a 'test' variable:

<c:set var="test" value="${myMap[myVariable]}"/>
Francisco Paulo
  • 6,284
  • 26
  • 25
  • Thanks. Ya that i know, but I need to set the value in "test" variable based on condition on key. So getting key and comparing it with some variable is an issue here. – ATG Pune Feb 20 '13 at 12:48
  • 1
    Just to clarify a little bit, the comparison which you speak of is not a simple 'equals', right? Because if it is, that's what the map accessor is doing anyway. – Francisco Paulo Feb 20 '13 at 12:53
  • The functional requirement is that I need to get the value from this map based on whether the key is equal to a variable. For example: lets say my keys are "US", "UK" and "India", So i want to compare these key with a Variable called "Country" and if it matches need to show the value of the map which is the URL for that country's website. – ATG Pune Feb 20 '13 at 12:59
  • If i'm understanding you correctly, this should still work. You have your "Country" variable, with some value (let's say that you did '' somewhere previously), in this case the '${myMap[Country]}' accessor would ask "myMap" for a key whose value is "UK" and return it if there is any. If you just want to directly write it on the jsp, then you wouldn't even need the assignment, you can just do ${myMap[Country]} directly (or use c:out if you want to escape entities) – Francisco Paulo Feb 20 '13 at 13:19
  • Thanks a lot !! It was so simple and I was overlooking this thing and was trying all other options. – ATG Pune Feb 20 '13 at 14:11
0
//use like this in jsp
<%
String val;
for(String key : myMap.keyset()){
    if(key.equals(myVariable )){
        val = myMap.get(key);
    }
}
%>
//on js use like this
var test = '<%=val%>';
Dinoop paloli
  • 633
  • 2
  • 8
  • 25
0

Since, you want to retrieve values from the map based on a condition, you can use the ternary operator instead. Try this :

<c:set var="testVariable" value='${ myMap.key eq myVariable ? myMap[myVariable] : "defaultValue" }'/>
Dimitri
  • 8,122
  • 19
  • 71
  • 128
  • Thanks for the solution. But I guess the suggestion made by Francisco is the simplest and best way to resolve the issue. – ATG Pune Feb 20 '13 at 14:12