栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在JSF数据表中显示来自MySQL数据库的图像[关闭]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在JSF数据表中显示来自MySQL数据库的图像[关闭]

您可以使用

<p:graphicImage>
来显示存储在中的图像
byte[]
,而不管其
byte[]
来源(数据库,磁盘文件系统,网络等)如何。最简单的例子是:

<p:graphicImage value="#{bean.streamedContent}" />

指的是

StreamedContent
财产。

但是,这有一个陷阱,尤其是在用于数据表之类的迭代组件中时:getter方法将被调用两次;第一次由JSF本身生成URL,

<imgsrc>
第二次由webbrowser生成,它需要基于中的URL下载图像内容
<imgsrc>
。为了提高效率,您不应在第一个getter调用中访问数据库。另外,要对getter方法调用进行参数化,以便可以使用传递特定图像ID的通用方法,则应使用
<f:param>
(请注意,传递方法参数的EL
2.2功能根本无法使用,因为这样做不行。不能以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>

#{item.imageId}
明显返回在DB的图像的独特idenfitier(主键),从而
byte[]
内容。该
#{imageStreamer}
是一个应用范围的bean看起来是这样的:

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

Image
在这个特定示例中,该类只是一个
@Entity
具有
@Lob
on
bytes
属性的类(当您使用JSF时,我当然假定您正在使用JPA与DB进行交互)。

@Entitypublic class Image {    @Id    @GeneratedValue(strategy = IDENTITY) // Depending on your DB, of course.    private Long id;    @Lob    private byte[] bytes;    // ...}

ImageService
仅仅是一个标准的
@Stateless
EJB,没有什么特别在这里看到:

@Statelesspublic class ImageService {    @PersistenceContext    private EntityManager em;    public Image find(Long id) {        return em.find(Image.class, id);    }}

也可以看看:

  • 使用p:graphicImage和StreamedContent从数据库显示动态图像


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/432798.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号