Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make JSF access a Map<String, ?> values from an EL instead of a bean fields?

Is there any proper way to override the way JSF accesses the beans fields from an Expression Language? The idea is to mimic this behavior in order to access a Map<String, ?> values, where the bean fields would be the map keys.

In other words, is it possible anyhow to use #{beanContainingNestedMap.keyOfSaidNestedMap}, just as if keyOfSaidNestedMap were a field of the beanContainingNestedMap?

If not, what other solution may I have?


Example:

Holder.java

public class Holder {

    private Map<String, Object> objects = new HashMap<String, Object>();

    public void add(String key, Object value) {
        objects.put(key, value);
    }

    public Object getObject(String key) {
        return objects.get(key);
    }

}

ExampleBean.java

public class ExampleBean {

    private Holder holder = new Holder();

    public ExampleBean() {
        holder.add("foo", 42);
        holder.add("bar", 'X');
    }

    public Holder getHolder() {
        return holder;
    }

}

example.xhtml

<c:out value="#{exampleBean.holder.foo}" /> <!-- should print "42" -->
<c:out value="#{exampleBean.holder.bar}" /> <!-- should print "X" -->

What would be great is if I could do something like (kind of pseudo-code since I don't know if such a method exists ;)):

@Override // override JSF's (if any...)
public Object resolveEl(String el) {
    try {
        super.resolveEl(el);
    } catch (ElException e) {
        Object bean = e.getBean();
        String fieldName = e.getFieldName();
        if (bean instanceof Holder) {
            Holder holder = (Holder) bean;
            Object value = holder.getObject(fieldName);
            if (value == null) {
                throw e;
            } else {
                return value;
            }
        }
    }
}
like image 206
sp00m Avatar asked Jul 26 '13 14:07

sp00m


1 Answers

You can directly use map by EL.

Holder.java

public class Holder {

    private Map<String, Object> objects = new HashMap<String, Object>();

    public void add(String key, Object value) {
        objects.put(key, value);
    }

    public Map<String, Object> getObjectsMap() {
        return objects;
    }

}

EL

#{exampleBean.holder.objectsMap[your-key]}
like image 97
Zaw Than oo Avatar answered Nov 08 '22 15:11

Zaw Than oo