tags:

views:

20

answers:

1

I have a bean called EmployeeRoster:

public class EmployeeRoster {
  protected List<Employee> janitors;
  protected List<Employee> teachers;
}

In JSP, I want to access the different lists of Employees by type. I know that I can do something like:

${employeeRoster.getJanitors}

However, I have many different types of employees and rather than creating an accessor in the EmployeeRoster for every type, I was hoping to be able to do something like this:

${employeeRoster.get(EmployeeType.JANITOR)}  // obviously, not valid

Is this possible in JSP? Can I apply a parameter to a bean accessor call?

A: 

You can make use of a Map<String, List<Employee>> property. E.g.

public class EmployeeRoster {
    private Map<String, List<Employee>> types = new HashMap<String, List<Employee>>();

    public EmployeeRoster() {
        // Fill the map here?
    }

    // Add/generate getter.
}

You can then access the map value as follows:

${employeeRoster.types.janitor}

which basically does the same as employeeRoster.getTypes().get("janitor"). You can also use a dynamic key using the brace notation:

${employeeRoster.types[type]}

which does basically employeeRoster.getTypes().get(type).

See also:

BalusC