2016-05-19 52 views
0

我有一些问题显示我的数据库检索到的图像。primefaces graphicimage CDI bean不起作用

查看来电者:

<p:graphicImage value="#{appController.image}" height="200 px" > 
     <f:param name="oid" value="#{item.oid}" /> 
</p:graphicImage> 

控制器:

@Named("appController") 
@ApplicationScoped 
public class AppController { 

    @Inject 
    private MultimediaFacade multimediaFacade; 

    public StreamedContent getImage() throws IOException { 
     System.out.println("getting image") 
     FacesContext context = FacesContext.getCurrentInstance(); 
     if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) { 
      // So, we're rendering the HTML. Return a stub StreamedContent so that it will generate right URL. 
      return new DefaultStreamedContent(); 
     } else { 
      // So, browser is requesting the image. Return a real StreamedContent with the image bytes. 
      String imageId = context.getExternalContext().getRequestParameterMap().get("oid"); 
      int oid=Integer.parseInt(imageId); 
      System.out.println(oid); 
      Multimedia image = multimediaFacade.find(oid); 
      System.out.println(Arrays.toString(image.getFileBlob())); 
      return new DefaultStreamedContent(new ByteArrayInputStream(image.getFileBlob())); 
     } 
    } 
} 

这段代码说明不了什么,它看起来像的方法不会被调用(从未在控制台打印)!

经过几天的试验改变了范围,我试图使用@ManagedBean而不是@Named,它的工作原理!

有人可以解释我为什么这项工作只与@ManagedBean,而不是@Named?

+1

'javax.enterprise.context.ApplicationScoped'为CDI,'用于JSF的javax.faces.bean.ApplicationScoped'。 – Geinmachi

+0

它不是范围问题 – Marco

+0

你的意思是说,CDI bean在“常规”页面中工作正常吗? – BalusC

回答

1

检查您是否有javax.enterprise.context.ApplicationScoped进口。

如果为@ApplicationScoped不同的进口(如javax.faces.bean.ApplicationScoped),那么你就需要配置CDI发现所有的bean,而不是只与CDI注解(这是默认值)

囤发现所有的豆类,无论是加空beans.xml到WEB-INF目录下,或者如果你已经有beans.xml中出现,加bean-discovery-mode="all"<beans>元素,像这样:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd" 
     bean-discovery-mode="annotated"> 
</beans> 
+0

你是完全正确的!所以这个问题是关于CDI的实现(enterprise.contexr vs faces.beans),你可以把我链接到某个地方,我可以更好地研究CDI吗?非常感谢你 – Marco

+0

对于一些注释,你真的需要小心包名称。 javax软件包中有注释双击,它们具有相同的名称但包装不同,因此含义不同。例如。 [@Singleton](http://docs.oracle.com/javaee/7/api/javax/ejb/Singleton.html)和[@Singleton](http://docs.oracle.com/javaee/7/api /javax/inject/Singleton.html)。它们来自不同的规格,因此不能混用。 – OndrejM

+0

您可以在此页面找到关于CDI的更多信息:http://cdi-spec.org/,特别是关于这里的bean发现:http://docs.jboss.org/cdi/spec/1.2/cdi-spec。 HTML#type_discovery_steps – OndrejM