【问题标题】:Access object attribute when object name is variable in struts2当对象名称在struts2中可变时访问对象属性
【发布时间】:2017-10-15 12:24:23
【问题描述】:

当属性名称是变量时,我在访问对象列表的特定对象属性时遇到了一些问题。

这是一个示例,其中 users 是用户列表,userAttributeList 是包含用户属性名称的字符串列表。

<%
    .......
    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>

在这种情况下,属性标签不会返回John, 20-05-1990等属性的值,而是返回username,birthDate等属性的名称> 等等。

    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;

        }
}

userAttributeList ArrayList 包含用户的属性名称。此 ArrayList 用于简化实现并为此创建动态解决方案:

<s:iterator value="users">
         <s:property value="%{username}" />
         <s:property value="%{birthDate}" />
         <s:property value="%{password}" />
         ....
   </s:iterator>

【问题讨论】:

  • 贴出你填写的代码userAttributeList
  • @Roman C 我编辑了我的帖子

标签: jsp struts2 ognl


【解决方案1】:

您只填充了用户对象的属性名称。但没有放价值观。如果你想拥有用户对象的动态字段,你应该使用Map 而不是ArrayList

Map<String, Object> userAttributeMap= new HashMap<>();
userAttributeMap.put("username", "John");
userAttributeMap.put("birthDate", "20-05-1990");
....

现在在 JSP 中,您应该使用 OGNL 评估地图键

<s:iterator value="%{userAttributeMap}" var="userAttribute">
...  <s:property value="%{#userAttribute['username']}" />
     <s:property value="%{#userAttribute['birthDate']}" />
</s:iterator>

【讨论】:

    猜你喜欢
    • 2012-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-14
    • 2015-09-22
    • 1970-01-01
    相关资源
    最近更新 更多