How do I call an object's method from EL?
Give the object:
public class TestObj {
public testObj() { };
public String test() { return "foo"; }
public String someOtherMethod(String param) { return param + "_bar"; }
}
and the obj is added to the pageContext
pageContext.setAttribute("t", new TestObj());
How would I perform the equivalent of:
<%= t.test() %>
<%= t.someOtherMethod("foo") %>
using EL?
It's supported since EL 2.2 which has been out since December 10, 2009 (over 2.5 years ago already!). EL 2.2 goes hand in hand with Servlet 3.0, so if you target a Servlet 3.0 container (Tomcat 7, Glassfish 3, etc) with a Servlet 3.0 compatible web.xml
which look like follows
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<!-- Config here. -->
</web-app>
then you'll be able to invoke methods with or without arguments in EL in the following forms:
${t.test()}
${t.someOtherMethod('foo')}
According to this Method calls in EL method calls in Expression Language are currently in JSR status and not implemented yet. What I use is JST facilities for JavaBean components to do some invocations. For example, if you modify your test
method signature to:
public class TestObj {
public TestObj() { };
public String getTest() { return "foo"; }
}
You can invoke getTest()
method with this syntax:
${t.test}
Now, if you need something more elaborate -like with parameter passing- you could use Custom Method features that EL offer. That requires public static methods declared in a public class, and also a TLD file. A nice tutorial can be found here.
Update:
As @BalusC states, later specifications now support method invocations. If you're deploying to a Java EE 6 compatible container, this Oracle Site shows how to properly use the feature.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With