Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access map with integer key from JSF EL

Tags:

jsf

el

jsf-2

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)

like image 786
Björn Landmesser Avatar asked Jun 17 '13 08:06

Björn Landmesser


2 Answers

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));
like image 175
AllTooSir Avatar answered Sep 28 '22 13:09

AllTooSir


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))}">
like image 34
Bjørn Stenfeldt Avatar answered Sep 28 '22 12:09

Bjørn Stenfeldt