I'm having some trouble accessing a specific object attribute of a list of objects when the attribute name is a variable.
This is an example, where users is a list of User and userAttributeList
is a list of String which contains the name of user attribute.
<%
.......
ActionContext.getContext().put("userAttributeList", request.getAttribute("userAttributeList"));
%>
<s:iterator value="users">
<s:iterator value="%{userAttributeList}" var="userAttribute">
... <s:property value="%{#userAttribute}" />
</s:iterator>
</s:iterator>
In this case, the property tag not return value of attribute like John, 20-05-1990 and so on , but return the name of attribute like username, birthDate and so on.
public class UserAction extends ActionSupport {
@Override
public String execute()
throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
ArrayList userAttributeList= new ArrayList();
// some logic implementation and populate the `userAttributeList`(username, birthDate, password etc)
request.setAttribute(userAttributeList, userAttributeList);
return SUCCESS;
}
}
The userAttributeList
ArrayList contain the name of attribute of an User. This ArrayList is used to simplify the implementation and create a dynamicaly solution for this:
<s:iterator value="users">
<s:property value="%{username}" />
<s:property value="%{birthDate}" />
<s:property value="%{password}" />
....
</s:iterator>
You have populated only names of attributes of the user object. But didn't put values. Instead of ArrayList
you should use a Map
if you want to have dynamic fields of the user object.
Map<String, Object> userAttributeMap= new HashMap<>();
userAttributeMap.put("username", "John");
userAttributeMap.put("birthDate", "20-05-1990");
....
Now in the JSP you should evaluate map keys using OGNL
<s:iterator value="%{userAttributeMap}" var="userAttribute">
... <s:property value="%{#userAttribute['username']}" />
<s:property value="%{#userAttribute['birthDate']}" />
</s:iterator>