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

1

5

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?

Unmusical answered 17/4, 2012 at 14:7 Comment(1)
There's no such method as setParameter() on request. Please be careful that you don't introduce red herrings in your question.Selfrealization
S
9

If you target at least a Servlet 3.0 container like Tomcat 7+, Glassfish 3+, JBoss AS 6+, etc with a web.xml conform at least Servlet 3.0 spec, then EL will let you invoke methods with arguments. 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')}
Selfrealization answered 17/4, 2012 at 14:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.