I’ve made some custom beans that implement the Map interface for easy access to arbitrary data in my JSP.
Example:
${person["cellPhoneNumber"]}
This extra data may or may not be added on the back end so a Map seems like a nice flexible way to store this.
The problem arises when I try to use the getters on my bean. My Person class has a getName() method. When using the following in my JSP, the Map.get() method is called instead of my method.
${person.name}
Is there a way to get around this call to Map’s get("name") and call getName() instead?
Here is my basic (stripped down) Java class:
class Person implements Map
{
private HashMap<String, Object> myMap;
private String name;
public Object get(Object key)
{
return myMap.get(key);
}
public String getName()
{
return this.name;
}
}
Using JSTL 1.1
Looks like servlet container treats every class implementing
Mapinterface as a map and completely discards other methods, falling back to by key lookup. I see two solutions:1)
get(Object key)should be aware of normal properties:This is a bit clumsy and not very scalable. Also it’s probably easier to either use reflection and find all fields automatically or convert your bean to map (see: How to convert a Java object (bean) to key-value pairs (and vice versa)?). Even worse.
2) Expose your map as a special bean attribute:
Then your EL expression looks like this:
This is a much better approach since:
Personhas optional attributes like cell phone number.Personis not a “Map` of optional attributes.