Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing and object's method from EL

Tags:

java

jsp

el

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?

like image 555
empire29 Avatar asked May 21 '12 00:05

empire29


2 Answers

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')}
like image 148
BalusC Avatar answered Nov 09 '22 12:11

BalusC


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.

like image 43
Carlos Gavidia-Calderon Avatar answered Nov 09 '22 12:11

Carlos Gavidia-Calderon