2013-02-28 69 views
0

我使用的是與primefaces的JSF,並希望顯示來自java代碼的圖像。JSF/primefaces以代碼形式顯示圖像 - 圖像位置?

我已經看到了http://www.primefaces.org/showcase/ui/dynamicImage.jsf

的教程,但我不是我怎麼能得到正確我的映像文件的路徑清晰:

代碼:

豆:

@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}" /> 

回報:

java.io.FileNotFoundException:\影像\ reddot.png

我希望在哪裏顯示,當它形成的代碼,以及如何做到這一點儲存我的形象的最佳實踐。

+0

實際上你的圖像位於哪裏? – partlov 2013-02-28 16:01:46

+0

我的圖像位於WebContent/images /中 - 但我也打開了一個新的結構來存儲我的圖像以用於java代碼。 – ctekk 2013-02-28 16:03:08

回答

4

由於您的圖片位於您的網頁文件夾中,因此您並不需要使用DefaultStreamedContent。對於在飛行中生成的圖像,我只會在上留下

對於你的情況,我只是創建一個簡單的方法,返回基於布爾變量的圖像路徑(在你的web文件夾中)。事情是這樣的:

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

而且在graphicImage的,你可以直接引用:

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

注意,你可能需要調整graphicImage的標籤,如果你的網絡環境是不是root。

編輯 實際上,你可以讓這個更簡單:

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

只要確保有連接的屬性爲getter。

+0

感謝您的最佳實踐! – ctekk 2013-03-01 08:54:38

+0

如果我在像D:/ Images這樣的位置上有圖像,那我該怎麼辦?你可以給我任何提示.. – Yubaraj 2015-02-23 10:16:07

+0

@Yubaraj除非你的網絡服務器配置爲提供文件關閉D:/圖像,你將無法指出P:graphicImage到該文件夾​​。您需要編寫一個servlet來讀取特定URL(即/ public/images)的請求,並將這些請求映射到D:/ Images文件夾中的文件。祝你好運 – Andre 2015-02-23 15:19:14

2

創建StreamedContent如下:

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

當您創建​​這將是你的磁盤絕對路徑,不只是在你的應用程序。

+0

謝謝你簡潔地回答我的q! – ctekk 2013-03-01 08:55:12