使用 struts 标记在 JSP 中迭代 HashSet

Iterating a HashSet in a JSP using struts tag

我是 JSP 的新手。我有一个雇主 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/empty,然后使用 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>

但是,它不起作用。

使用fn:length函数。

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

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

稍后在代码中

${fn:length(your_collection)}

Source

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

<!-- 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 获取容器并添加到 list/set。那么就不需要检查空值了。您仍然可以为容器(设置、列表等)保留 setter,但可能会保护它以提醒您只有接近的东西(应该在同一个包中应该能够直接添加值,希望不知道分配 null 和其他遥远的东西没有业务,但与 public getter) 一起工作。

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

<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<T> 会为您提供帮助。