Search code examples
primefacescdijsf-2.2managed-beanpayara

primefaces graphicimage CDI bean doesn't work


i had some problem showing images retrieved by my db.

View caller:

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

Controller:

@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()));
        }
    }
}

this code shows nothing and it looks like the method is never called (never print in console)!

after days of trial changing the scope, i tried to use @ManagedBean instead of @Named, and it works!!!

can someone explain me why this work only with @ManagedBean and not with @Named?


Solution

  • Check that you have javax.enterprise.context.ApplicationScoped in imports.

    If you have a different import for @ApplicationScoped (e.g. javax.faces.bean.ApplicationScoped), then you need to configure CDI to discover all beans instead of only those with CDI annotations (which is the default)

    To tun discovery for all beans, either add empty beans.xml into WEB-INF directory, or if you already have beans.xml there, add bean-discovery-mode="all" into the <beans> element, like this:

    <?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>