How to access a property value of an object that is a Hashset when iterating in Struts2

694 Views Asked by At

I do not have a super great knowledge on Struts 2 tags as I am trying to learn. I know that when accessing a property value of an object that is in a collection you iterate the collection (in the example I'll put is "products") and then you can access the property (that can even be an object, in my case is an image):

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

The problem comes when the object that the products collection carries has a HashSet inside with the images:

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

So the question is: How can I access now the route of the image?

Besides that there are several images and I only want the one which a boolean parameter named "main" is marked as true, as the other images are secondary to use in a slideshow.

3

There are 3 best solutions below

1
On BEST ANSWER

Here you go :

<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>
1
On

Not used Struts tag before but for MAIN image of a product, you can do like below:

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.
    }
}
0
On

Use the OGNL selection.

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

and read further to a selecting first match

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