【问题标题】:Iterating a HashSet in a JSP using struts tag使用 struts 标签在 JSP 中迭代 HashSet
【发布时间】:2017-06-20 14:22:36
【问题描述】:

我是 JSP 的新手。我有一个具有 Employee info 属性的 Employer bean 对象列表。

   List<Employer> employerList;

   class Employer{
      private Set<EmployeeInfo> employeeInfo;

      public Set<EmployeeInfo> getEmployeeInfo() {
        return employeeInfo;
      }

     public void setEmployeeInfo(Set<EmployeeInfo> employeeInfo) {
       this.employeeInfo= employeeInfo;
     }
  }

class EmployeeInfo{
      private String name;

      public setName(String name){
         this.name=name;
      }

       public getName(){
          return name;
      }
}

我正在尝试检查 employeeSetInfo 是否不为 null/空,然后使用 struts 2 标记在 jsp 中显示每个员工的姓名。

<s:if test="%{employerList.employeeInfo.size>0}">
    <s:iterator value="employerList.employeeInfo" var="employee">
        <s:property value="#employee.name" />
    </s:iterator>
</s:if>

但是,它不起作用。

【问题讨论】:

  • employerList 是我认为的雇主列表。
  • 您的employerList 是一个列表。你需要迭代它。尝试在 java 类中编写该代码,然后在 JSP 中执行相同的操作。

标签: jsp struts2


【解决方案1】:

一些事情,首先要直接回答你的问题,正如评论中提到的你需要迭代你的列表:

<!-- the "test" attribute is evaluated by default so we don't need to wrap it with 
%{}, also note that you are not testing for null so this isn't safe, your code 
should be modified to prevent nulls, where reasonable. For this reason the
if can be omitted-->

<s:iterator value="employerList"> <!-- will push each Employer's attributes to the top of the stack exposing its values --> 
   <s:iterator value="employeeInfo"> <!-- same at other iterator -->
      <s:property value="name"/>
   </s:iterator>
</s:iterator>

现在减少空值检查(这只是为了避免在 JSP 中进行疯狂的空值检查,并且对答案并不重要)...

在EmployeeInfo 中放置一个构造函数,并且不允许设置null,因为它没有意义。在构造过程中初始化数据结构(静态初始化很好)。然后使用 getter 获取容器并添加到列表/集合中。那么就不需要检查空值了。您仍然可以保留容器的设置器(set、list 等),但可能会对其进行保护以提醒您只有接近的东西(应该在同一个包中应该能够直接添加值,并希望知道不要分配 null 和其他远方的事情除了与公众吸气剂合作之外没有任何关系)。

如果您不想这样做,您可以包装所有这些迭代器和属性访问:

<s:if test="something != null">
   <!-- Do stuff with verified to be safe reference -->
</s:if>
<s:else>
   <!-- maybe state there are no values so you aren't left wondering -->
</s:else> 

还有你不能遵循这个建议的地方(这种情况经常发生)Optional&lt;T&gt; 来救你。

【讨论】:

    【解决方案2】:

    使用 fn:length 函数。

    在 JSP 文件的开头声明 fn 命名空间

    <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    

    代码后面

    ${fn:length(your_collection)}
    

    https://stackoverflow.com/a/26962901/4525175

    Source

    【讨论】:

    • OP 问题中的your_collection 是什么?
    • 这是您要循环遍历的列表。
    猜你喜欢
    • 2020-07-08
    • 2013-07-19
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-02
    • 1970-01-01
    相关资源
    最近更新 更多