1

My hashmap is in application scope.I have 3 hashmaps mapEnglish, mapSpanish, mapHindi. The language parameter is available in my session and it is English, or Hindi or Spanish.I can access it like : ${language}

Now I want to create the hashmap name dynamically based on the language parameter.So for example if ${language} is English the map name should be mapEnglish. How can I do that?

I tried this:

<c:forEach items="${applicationScope.map${language}}" var="orderedCityMap">
</c:forEach>

But it does not work.Could anyone suggest???

Jeets
  • 3,189
  • 8
  • 34
  • 50

2 Answers2

2

I think you cannot nest EL expressions to achieve what you need. Have a look at this question How to nest an EL expression in another EL expression

If the number of hashmap's you are accessing are limited, then you may look at using the <c:choose> tag. Here is one example.

Map<String, Integer> englishHashMap = new HashMap<String, Integer>();
Map<String, Integer> spanishHashMap = new HashMap<String, Integer>();
Map<String, Integer> hindiHashMap = new HashMap<String, Integer>();

englishHashMap.put("english", 1);
englishHashMap.put("hindi", 2);
englishHashMap.put("telugu", 3);

spanishHashMap.put("english1", 1);
spanishHashMap.put("hindi1", 2);
spanishHashMap.put("telugu1", 3);

hindiHashMap.put("english2", 1);
hindiHashMap.put("hindi2", 2);
hindiHashMap.put("telugu2", 3);

String language = "English";

context.setAttribute("mapEnglish", englishHashMap);
context.setAttribute("mapSpanish", spanishHashMap);
context.setAttribute("mapHindi", hindiHashMap);
context.setAttribute("language", language);

You can access the hashmap in the jsp page like below

<c:set var="language" value="${applicationScope.language}"/>
<c:choose>
    <c:when test="${language == 'English'}">
        <c:set var="requiredMap" value="${mapEnglish}"/>
    </c:when>
    <c:when test="${language == 'Spanish'}">
        <c:out value="Spanish"/>
        <c:set var="requiredMap" value="${mapSpanish}"/>
    </c:when>
    <c:otherwise>
        <c:out value="Hindi"/>
        <c:set var="requiredMap" value="${mapHindi}"/>
    </c:otherwise>  
</c:choose>
<c:forEach items="${requiredMap}" var="orderedCityMap">
    Key:<c:out value="${orderedCityMap.key}"/>,
    Value:<c:out value="${orderedCityMap.value}"/><br>
</c:forEach> 

The output is :

Key:telugu, Value:3
Key:hindi, Value:2
Key:english, Value:1
Community
  • 1
  • 1
Sai Upadhyayula
  • 2,404
  • 3
  • 23
  • 35
1

I would do this, especially if it's only limited to a handful of languages:

<c:choose>
<c:when test="${language == 'English'}>
    <c:set var="map" value="${applicationScope.mapEnglish}"/>
</c:when>
<c:when test="${language == 'Hindi'}>
    <c:set var="map" value="${applicationScope.mapHindi}"/>
</c:when>
<c:when test="${language == 'Spanish'}>
    <c:set var="map" value="${applicationScope.mapSpanish}"/>
</c:when>
</c:choose>

<c:forEach items="${map}" var="orderedCityMap">
...
</c:forEach>
alfreema
  • 1,308
  • 14
  • 26