Sending parameter with JSP bean accessor
I have a bean called EmployeeRoster:
public class EmployeeRoster {
protec开发者_高级运维ted 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?
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:
- Hidden features of JSP/Servlet
精彩评论