Arian
Arian

Reputation: 3241

JSF/primefaces display image out of code - Image Location?

I'm using JSF with primefaces and want to display an image from java code.

I already saw the tutorial on http://www.primefaces.org/showcase/ui/dynamicImage.jsf

But I'm not clear on how I can get the path to my image file correctly:

Code:

Bean:

@ManagedBean
public class ABean {

    private StreamedContent bStatus;

    public ABean() {
        try {
            Boolean connected = false;
            if (connected == true) {
                bStatus = new DefaultStreamedContent(new FileInputStream(new File("/images/greendot.png")), "image/jpeg");
            } else {                
                bStatus = new DefaultStreamedContent(new FileInputStream(new File("/images/reddot.png")), "image/jpeg");
            }
        } catch(Exception e) {
            e.printStackTrace();
        }

    }

    public StreamedContent getBStatus() {
        return bStatus;
    }

    public void setBStatus(StreamedContent bStatus) {
        this.bStatus = bStatus;
    }
}

xhtml:

<p:graphicImage value="#{ABean.bStatus}" />

returns:

java.io.FileNotFoundException: \images\reddot.png

I would appreciate best practices on where to store my image when displaying it form code and how to do it.

Upvotes: 0

Views: 5479

Answers (2)

Andre
Andre

Reputation: 3904

Since your images are in your web folder, you don't really need to use DefaultStreamedContent. I'd leave that only for images generated on the fly.

For your case, I'd just create a simple method that returns the image path (in your web folder) based on the boolean variable. Something like this:

public String getImagePath(){
    return connected ? "/images/greendot.png" : "/images/reddot.png";
}

And on the graphicImage, you can just reference that:

<p:graphicImage value="#{yourBean.imagePath}"/>

Note that you might have to adjust the graphicImage tag if your web context is not root.

EDIT You can actually make this even simpler:

 <p:graphicImage value="#{yourBean.connected ? '/images/greendot.png' : '/images/reddot.png'}"/>

Just make sure to have a getter for the connected property.

Upvotes: 4

partlov
partlov

Reputation: 14277

Create your StreamedContent as follows:

bStatus = new DefaultStreamedContent(FacesContext.getCurrentInstance().getExternalContext().getResourceAsStream("/images/greendot.png"), "image/jpeg");

When you are creating new File() this will be absolute path in your disk, not just in your application.

Upvotes: 2

Related Questions