3
votes

I have a Bean which has a List of Objects, containing StreamedContent Objects (Primefaces Type) which represent Images in a Database. Now I want to iterate over this list in a JSF 2.0 Page (with Primefaces), and show the images. Showing only one Image in this way works:

<p:graphicImage value="#{ImageLoader.oneImage}" title="aImage" alt="no Img"/>

But if I nest this tag in a c:foreach, ui:repeat or p:datatable, the Images aren't loaded! The alternative text is shown instead

<ui:repeat value="#{ImageLoader.allImages}" var="img">
<p:graphicImage value="#{img}" alt="Hier sollte ein Bild sein" />
<br/>
</ui:repeat>

The Image-Loader Bean:

@Named(value = "ImageLoader")
@Stateless
public class ImageLoader {

@Inject
private ImageFacade imgFacade;

private List<StreamedContent> allImages = new ArrayList <>();

private StreamedContent oneImage;

public StreamedContent getOneImage() {
    List<Image> findAll = imgFacade.findAll();
    byte[] imagedata = findAll.get(0).getImagedata();
    StreamedContent retVal = new DefaultStreamedContent(new     ByteArrayInputStream(imagedata));
    return retVal;
}

public void setOneImage(StreamedContent oneImage) {
    this.oneImage = oneImage;
}

public List<StreamedContent> getAllImages() {
    List<Image> findAll = imgFacade.findAll();
    Logger.getLogger(ImageLoader.class.getName()).log(Level.INFO, "### COUNT: {0}", findAll.size());
    for (Image image : findAll) {
        byte[] imagedata = image.getImagedata();
        allImages.add(new DefaultStreamedContent(new ByteArrayInputStream(imagedata)));
        Logger.getLogger(ImageLoader.class.getName()).log(Level.INFO, "### Added Image {0}", image.getImagename());
    }
    return allImages;
}

public void setAllImages(ArrayList<StreamedContent> allImages) {
    this.allImages = allImages;
}

}

I don't see the problem, can you help me out please? :)

Thanks & Regards

1

1 Answers

7
votes

I broke my head on this one for a day or so, but I found a solution!

JSF:

<ui:repeat value="#{bean.images}" var="imageID">
             <p:graphicImage value="#{bean.image}">
                 <f:param name="imageID" value="#{imageID}" />
             </p:graphicImage>
 </ui:repeat>

Managed bean:

public List<String> getImages(){
        List<String> l = new ArrayList<String>();
        for(Theme t:themeFacade.findAll())
            l.add(t.getId().toString());
        return l;
    }

    public StreamedContent getImage(){
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest myRequest = (HttpServletRequest) context.getExternalContext().getRequest();
        String imageID = (String) myRequest.getParameter("imageID");
        return new DefaultStreamedContent(new ByteArrayInputStream(themeFacade.find(Long.parseLong(imageID)).getImage()));
    }