【问题标题】:How to access a property value of an object that is a Hashset when iterating in Struts2在Struts2中迭代时如何访问作为Hashset的对象的属性值
【发布时间】:2013-12-23 22:48:45
【问题描述】:

我对 Struts 2 标签的了解并不多,因为我正在努力学习。我知道在访问集合中对象的属性值时,您会迭代集合(在示例中我将放置“产品”),然后您可以访问该属性(甚至可以是一个对象,在我的案例是图像):

<s:iterator value="products">
  <img src="<s:property value="image.route"/>"/>
</s:iterator>

当 products 集合携带的对象内部有一个带有图像的 HashSet 时,问题就来了:

public class Product implements java.io.Serializable{
    ...
    private Set images = new HashSet(0);
    ...
}

所以问题是:我现在如何访问图像的路由?

除了有几个图像,我只想要一个名为“main”的布尔参数被标记为 true 的图像,因为其他图像在幻灯片中是次要的。

【问题讨论】:

  • 根据代码,它是一组通用对象。显示您将其对象放入images 集合的类。

标签: java jsp struts2 ognl


【解决方案1】:

给你:

<s:iterator value="products">
  <s:iterator value="images">
     <s:property value="main"/>
     <s:property value="route"/>
     <s:if test="main==true">
           //other code
     </s:if>
  </s:iterator>
</s:iterator>

【讨论】:

  • @Moises 如果它解决了您的问题,请考虑升级并接受它。
【解决方案2】:

以前没有使用过Struts标签,但是对于产品的MAIN图像,你可以这样做:

public class Product implements java.io.Serializable{
    ...
    private Set images = new HashSet(0);
    ...

    // Public a getter for main image -> Easy to access 'mainImage' in JSTL
    public Object getMainImage() {
        // Find your main image here. You can replace Object by your image type.
    }
}

【讨论】:

  • 谢谢你。我知道这一点,但我真的想用 struts 标签来做这件事,这似乎比普通的 JSTL 更容易使用。
【解决方案3】:

使用OGNL selection

<img src="<s:property value="images.{? #this.main == true}[0].route"/>"/>

并进一步阅读选择第一个匹配项

<img src="<s:property value="images.{^ #this.main == true}.route"/>"/>

【讨论】:

  • 我会检查这个选项。感谢您的帮助!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-07-14
  • 1970-01-01
  • 1970-01-01
  • 2017-10-15
  • 1970-01-01
  • 2014-07-03
  • 1970-01-01
相关资源
最近更新 更多