在JSF数据表中显示来自MySQL数据库的图像

NiÑ*_*iÑo 4 mysql datatable jsf image primefaces

我有MySQL数据库,它将图像存储在一blob列中.我想在PrimeFaces中展示它们<p:dataTable>.我怎样才能做到这一点?

Bal*_*usC 12

无论源(数据库,磁盘文件系统,网络等)如何,您都可以使用它<p:graphicImage>来显示存储在a中的图像.最简单的例子是:byte[]byte[]

<p:graphicImage value="#{bean.streamedContent}" />
Run Code Online (Sandbox Code Playgroud)

这是指StreamedContent财产.

然而,这有一个缺陷,特别是在迭代组件(如数据表)中使用时:getter方法将被调用两次; 第一次由JSF自己生成URL,<img src>第二次由webbrowser 生成,当需要根据URL下载图像内容时<img src>.为了提高效率,您不应该在第一次getter调用中击中DB.另外,要参数化getter方法调用以便您可以使用传递特定图像ID的通用方法,您应该使用a <f:param>(请注意,传递方法参数的EL 2.2功能根本不起作用,因为这不会t最终在URL中<img src>!).

总结一下,这应该做到:

<p:dataTable value="#{bean.items}" var="item">
    <p:column>
        <p:graphicImage value="#{imageStreamer.image}">
            <f:param name="id" value="#{item.imageId}" />
        </p:graphicImage>
    </p:column>
</p:dataTable>
Run Code Online (Sandbox Code Playgroud)

#{item.imageId}明显返回在DB的图像的独特idenfitier(主键),从而byte[]内容.这#{imageStreamer}是一个应用程序作用域bean,如下所示:

@ManagedBean
@ApplicationScoped
public class ImageStreamer {

    @EJB
    private ImageService service;

    public StreamedContent getImage() 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 image. Return a real StreamedContent with the image bytes.
            String imageId = context.getExternalContext().getRequestParameterMap().get("imageId");
            Image image = imageService.find(Long.valueOf(imageId));
            return new DefaultStreamedContent(new ByteArrayInputStream(image.getBytes()));
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

Image班是在这个特殊的例子只是一个@Entity@Lob关于bytes财产(如你使用JSF,我五言的假设你正在使用JPA与DB进行交互).

@Entity
public class Image {

    @Id
    @GeneratedValue(strategy = IDENTITY) // Depending on your DB, of course.
    private Long id;

    @Lob
    private byte[] bytes;

    // ...
}
Run Code Online (Sandbox Code Playgroud)

ImageService只是一个标准的@StatelessEJB,这里没什么特别的:

@Stateless
public class ImageService {

    @PersistenceContext
    private EntityManager em;

    public Image find(Long id) {
        return em.find(Image.class, id);
    }

}
Run Code Online (Sandbox Code Playgroud)

也可以看看: