Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is possible to use ${object.method} in jsp with parameters?

Tags:

java

jsp

el

I have an object like this

public class Employee {

  public String getName() {
    return "tommaso";
  }

  public String getName(String name) {
    return "tommaso "+name;
  }

}

In my action (I use Struts) I set a parameter of object Employee.

request.setAttribute("emp",employeeInstance);

After that in jsp I write this code

${emp.name}

and the output is

tommaso

If I want to use the second method, public String getName(String name) { ... }, using same formal text, ${emp. ...something passing a parameter... }, is possible?

like image 377
Tommaso Taruffi Avatar asked Feb 21 '23 19:02

Tommaso Taruffi


1 Answers

If you target a Servlet 3.0 container like Tomcat 7, Glassfish 3, JBoss AS 6, etc with a web.xml conform Servlet 3.0 spec, then you'll be able to invoke methods with arguments in EL. Your particular case can then be solved as follows:

${emp.getName('foo')}

If you aren't on Servlet 3.0 yet or can't upgrade to it, then you'd need to create a custom EL function which takes 2 arguments: the Employee and the name.

public static String getEmployeeName(Employee employee, String name) {
    return employee.getName(name);
}

which you then use as follows:

${my:getEmployeeName(emp, 'foo')}
like image 82
BalusC Avatar answered Mar 02 '23 20:03

BalusC