tags:

views:

479

answers:

3

Let just say i have the following java object that I wish to read in my jsp using el:

class A {

 Map map = new HashMap();
 int count;

        String getAttribute(String attrName)
        {
                return map.get(attrName);
        }

       String getCount()
       { 
               return count;
      }

}

I can call count by doing ${a.count}

But how How do I call the getAttribute using el ?

+2  A: 

You cannot!

See the guide for what you can do and what not.

The reasoning behind this is that el is supposed to be a thin layer in your application that just gives access to data that sits behind pages for presentation purposes.

It should not replace the business logic of the application. While your getAttribute method is trivial enough several people could misuse it and convert it into a big fat method that performs a lot of stuff and has side-effects when it is run. This is exactly what el wants to avoid.

kazanaki
I'm more of the opinion that EL just wasn't thought through well enough. It's too simple in too many cases.
skaffman
Note that if the method were named just "get()" then he could access it with as "a[someThing]".
Joachim Sauer
+1  A: 

What you need is for your class to implement the java.util.Map interface, simply by wrapping the internal map. Then you can use the following EL expression:

${a["attribute"]}
David Rabinowitz
+2  A: 

JEE6 (e.g. Glassfish 3 would accept ${a.getAttribute('foo')}) supports method invocations, JEE5 doesn't. Here, you would need to expose your Map like this:

public Map getAttributes() {
  return map;
}

to make expression ${a.attributes['foo']}) work.

If you're outside JEE/JSP, you could use a EE6 complient implementation like JUEL 2.2.x which supports method invocations.

chris