Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call parameterized method from JSP using JSTL/EL

How to call a Java method with arguments which is defined in Java class, from JSP using JSTL/EL. The method is returning arrays. Any return value can be used.

like image 846
sachin gk Avatar asked Aug 19 '11 12:08

sachin gk


2 Answers

You can only invoke methods with arguments in EL if you're targeting and running a Servlet 3.0 compatible container (e.g. Tomcat 7, Glassfish 3, JBoss AS 6, etc) with a web.xml declared conform Servlet 3.0. This servlet version comes along with EL 2.2 which allows invoking arbitrary instance methods with arguments.

Assuming that you've a ${bean} in the scope which refers to an instance of a class which has a method something like public Object[] getArray(String key), then you should be able to do this:

<c:forEach items="${bean.getArray('foo')}" var="item">     ${item} <br /> </c:forEach> 

or even with another variable as argument

<c:forEach items="${bean.getArray(foo)}" var="item">     ${item} <br /> </c:forEach> 

But if you don't target a Servlet 3.0 container, then you cannot invoke methods with arguments in EL at all. Your best bet is to just do the job in the preprocessing servlet as suggested by Duffymo.

Object[] array = bean.getArray("foo"); request.setAttribute("array", array); // ... 

As a completely different alternative, you could create an EL function which delegates the method call. You can find a kickoff example somewhere near the bottom of this blog. You'd like to end up something like as:

<c:forEach items="${util:getArray(bean, 'foo')}" var="item">     ${item} <br /> </c:forEach> 

with

public static Object[] getArray(Bean bean, String key) {     return bean.getArray(key); } 
like image 168
BalusC Avatar answered Sep 19 '22 18:09

BalusC


The above solution didnt work for me. I had a function getRemitanceProfileInformation(user) in my java class. I created a usebean of java class and then invoked

<c:set var="paymentValueCode" value='remittanceaddr.getRemitanceProfileInformation("${user}")'/> 

and it worked.

like image 30
user1417914 Avatar answered Sep 17 '22 18:09

user1417914