2016-02-11 38 views
1

如下使用<p:graphicImage>顯示BLOB圖像。在標記文件中使用p:graphicImage顯示BLOB圖像

<p:graphicImage value="#{categoryBean.image}"> 
    <f:param name="id" value="7"/> 
</p:graphicImage> 

其中CategoryBean已被定義如下。

@Named 
@ApplicationScoped 
public class CategoryBean { 

    @Inject 
    private CategoryService service; 

    public CategoryBean() {} 

    public StreamedContent getImage() throws IOException { 
     FacesContext context = FacesContext.getCurrentInstance(); 

     if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) { 
      return new DefaultStreamedContent(); 
     } else { 
      String id = context.getExternalContext().getRequestParameterMap().get("id"); 
      byte[] bytes = Utils.isNumber(id) ? service.findImageById(Long.parseLong(id)) : null; 
      return bytes == null ? null : new DefaultStreamedContent(new ByteArrayInputStream(bytes)); 
     } 
    } 
} 

關於上述方法,下面的自定義標籤應該完美地工作,但它未能在<p:graphicImage>沒有錯誤/異常顯示圖像。

<my:image bean="#{categoryBean}" property="image" paramName="id" paramValue="7"/> 

標籤文件位於/WEB-INF/tags/image.xhtml下。

<ui:composition xmlns="http://www.w3.org/1999/xhtml" 
       xmlns:p="http://primefaces.org/ui" 
       xmlns:ui="http://xmlns.jcp.org/jsf/facelets" 
       xmlns:f="http://xmlns.jcp.org/jsf/core"> 

    <p:graphicImage value="#{bean[property]}"> 
     <f:param name="#{paramName}" value="#{paramValue}"/> 
    </p:graphicImage> 
</ui:composition> 

生成<img>標籤似乎看起來罰款:

<img id="form:j_idt4" 
    src="/ContextPath/javax.faces.resource/dynamiccontent.properties.xhtml?ln=primefaces&amp;v=5.3&amp;pfdrid=IA0%2F7ZuBnGS%2BSzeb%2BHyPOTo4Pxp4hjI6&amp;pfdrt=sc&amp;id=7&amp;pfdrid_c=true" 
    alt=""/> 

它只返回一個HTTP 404錯誤。

給出的自定義標籤的定義是否存在缺陷?

+1

我沒覺得不好,但有一些變相PrimeFaces球員誰不喜歡公開他們的軟件不斷暴露錯誤下投票,當我張貼問題揭示了長期存在的BUG? – Tiny

回答

1

這是由PrimeFaces <p:graphicImage>如何識別圖像請求引起的。基本上,它將精確值表達式#{bean[property]}轉換爲字符串,對其進行加密,然後將其作爲pfdrid值傳遞。當網頁瀏覽器需要通過全新的HTTP請求下載圖像時,該值表達式將在「當前」EL上下文中解密並評估。然而,在那一刻,在EL上下文中沒有任何地方可以使用#{bean}#{property},因爲沒有使用tagfiles和all的JSF視圖。在EL上下文中只有請求,會話和應用程序範圍的bean可用。

除了在PrimeFaces傢伙報告問題之外,沒有任何可以做的。

至於備用解決方案,OmniFaces <o:graphicImage>通過在渲染響應期間檢查目標bean /方法而不是在流式傳輸圖像期間做得更好。它立即檢查#{bean[property]},發現它實際上代表#{categoryBean.image},然後成功。只是爲了確保我像標記文件一樣對它進行了測試,並且它對我來說工作正常,而PF則確實如所述那樣失敗。

<o:graphicImage value="#{bean[property](paramValue)}" /> 

public byte[] getImage(Long id) throws IOException { 
    return service.findImageById(id); 
} 
+0

有一個'java.lang.NullPointerException'直接使用'''(OmniFaces 2.2/Mojarra 2.2.12) - 'java.lang.NullPointerException at org.omnifaces.el.MethodReference。 (MethodReference.java:45)'。 – Tiny

+0

屬性當然必須是'getImage'。 NPE至少是不正確的,代碼必須在這裏拋出一個'MethodNotFoundException'。 – BalusC

+0

原因被報告爲java.lang.NullPointerException。 – Tiny