Access map value in EL using a variable as key

前端 未结 5 950
野性不改
野性不改 2020-12-14 03:08

I have a Map in EL as ${map} and I am trying to get the value of it using a key which is by itself also an EL variable ${key} with the

相关标签:
5条回答
  • 2020-12-14 03:31

    I think that you should access your map something like:

    ${map.key}
    

    and check some tutorials about jstl like 1 and 2 (a little bit outdated, but still functional)

    0 讨论(0)
  • 2020-12-14 03:32

    My five cents. Now I am working with EL 3.0 (jakarta impl) and I can access map value using three ways:

     1. ${map.someKey}
     2. ${map['someKey']}
     3. ${map[someVar]} //if someVar == 'someKey'
    
    0 讨论(0)
  • 2020-12-14 03:38

    $ is not the start of a variable name, it indicates the start of an expression. You should use ${map[key]} to access the property key in map map.

    You can try it on a page with a GET parameter, using the following query string for example ?whatEver=something

    <c:set var="myParam" value="whatEver"/>
    whatEver: <c:out value="${param[myParam]}"/>
    

    This will output:

    whatEver: something
    

    See: https://stackoverflow.com/tags/el/info and scroll to the section "Brace notation".

    0 讨论(0)
  • 2020-12-14 03:39

    I have faced this issue before. This typically happens when the key is not a String. The fix is to cast the key to a String before using the key to get a value from the map

    Something like this:

    <c:set var="keyString">${someKeyThatIsNotString}</c:set>

    <c:out value="${map[keyString]}"/>

    Hope that helps

    0 讨论(0)
  • 2020-12-14 03:43

    You can put the key-value in a map on Java side and access the same using JSTL on JSP page as below:

    Prior java 1.7:

    Map<String, String> map = new HashMap<String, String>();
    map.put("key","value");
    

    Java 1.7 and above:

    Map<String, String> map = new HashMap<>();
    map.put("key","value");
    

    JSP Snippet:

    <c:out value="${map['key']}"/>
    
    0 讨论(0)
提交回复
热议问题