如何使用<p:media>绑定动态内容?

Ven*_*idu 7 media jsf dynamic-content primefaces jsf-2

我用它<p:media>来显示静态PDF内容.

<p:media value="/resource/test.pdf" 
         width="100%" height="300px" player="pdf">  
</p:media>
Run Code Online (Sandbox Code Playgroud)

如何更改它以显示动态内容?

Bal*_*usC 10

与中一样<p:graphicImage>,该value属性可以指向返回的bean属性StreamedContent.这只需要一个特殊的getter方法,原因在下面的答案中详细解释了如何使用<p:graphicImage>来自数据库的动态资源:使用p:graphicImage和StreamedContent从数据库显示动态图像.

在您的特定示例中,它看起来像这样:

<p:media value="#{mediaManager.stream}" width="100%" height="300px" player="pdf">
    <f:param name="id" value="#{bean.mediaId}" />
</p:media>
Run Code Online (Sandbox Code Playgroud)

@ManagedBean
@ApplicationScoped
public class MediaManager {

    @EJB
    private MediaService service;

    public StreamedContent getStream() throws IOException {
        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 media. Return a real StreamedContent with the media bytes.
            String id = context.getExternalContext().getRequestParameterMap().get("id");
            Media media = service.find(Long.valueOf(id));
            return new DefaultStreamedContent(new ByteArrayInputStream(media.getBytes()));
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

  • 如果我将ManagedBean保存在@ViewScoped中怎么办? (4认同)