Access map with integer key from JSF EL
Asked Answered
B

2

7

In a backing bean I have defined a Map<Integer,String> property. When trying to access the map from EL inside an xhtml-file, I get nothing back.

<h:outputLabel value="#{bean.myMap[0]}">

does not return the value for key 0. With a String key it works.

It works with a List<String>, but I want the Map to have some kind of sparse array (not all indexes have values)

Broncobuster answered 17/6, 2013 at 8:4 Comment(8)
You should use omnifaces: showcase.omnifaces.orgExcellency
@RongNK which component of omnifaces would be applicable here?Nephograph
possible duplicate of JSTL access a map value by keyNephograph
@LuiggiMendoza So sorry, i have an mistake in memory :-)Excellency
@LuiggiMendoza Ok, didn't know that EL in JSF is the same as JSTL.Withdrawn
@BjörnMilcke EL and JSTL are not the same.EL is declared by ${} and #{} while JSTL is a tag library that helps working with EL. More info in their respective stackoverflow wiki pages: EL and JSTL. Also, refer to JSTL in JSF2 Facelets… makes sense?Nephograph
@LuiggiMendoza So, then I assume this question is no duplicate to the JSTL question, although the answers are the same.Withdrawn
It's a duplicate question because they face the same problem and same answer.Nephograph
A
8

EL interprets your literal number 0 as long type. Try a Map<Long,String> instead of Map<Integer,String>.

This is what you are supposedly doing :

myMap.put(Integer.valueOf(0), "SomeValue"); 

This is what EL does to get back the value :

String value = myMap.get(Long.valueOf(0));
Anatomy answered 17/6, 2013 at 8:5 Comment(0)
L
3

I had the same problem and found this when I was googling for a solution. Changing the map wasn't really an option for me, since it was auto-generated code, so here's what I ended up doing.

I created a managed bean:

package my.bean.tool;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ApplicationScoped;

@ManagedBean
@ApplicationScoped
public class Caster {

    public Caster() {
    }

    public int toInt(long l) {
        return (int) l;
    }
}

Then I simply did what in your case would have been:

<h:outputLabel value="#{bean.myMap.get(caster.toInt(0))}">
Lidia answered 16/4, 2015 at 7:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.