Executing and object's method from EL
Asked Answered
P

2

8

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?

Pattern answered 21/5, 2012 at 0:23 Comment(1)
For anyone else suffering the same silly mistake as me, note the round brackets for a method call as opposed to square ones for accessing lists, maps, etc.Cheke
N
9

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')}
Noumenon answered 22/5, 2012 at 4:35 Comment(2)
Looks like my container is using Servlet 2.3. oh well.Pattern
So you're using for exampe Tomcat 5.0? It can also happen that you're actually running Tomcat 7.0 but that the web.xml is incorrectly declared conform Servlet 2.3 and thus Tomcat 7.0 would run in Servlet 2.3 fallback modus.Noumenon
K
3

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.

Kattie answered 21/5, 2012 at 1:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.