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

无论byte []源(DB,磁盘文件系统,网络等)如何,您都可以使用

来显示存储在byte []中的图像.最简单的例子是:

它引用了StreamedContent属性.

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

总结一下,这应该做到:

#{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()));

}

}

}

在这个特定的例子中,Image类只是一个带有@Lob on bytes属性的@Entity(因为你使用的是JSF,我的cource假设你正在使用JPA与数据库进行交互).

@Entity

public class Image {

@Id

@GeneratedValue(strategy = IDENTITY) // Depending on your DB, of course.

private Long id;

@Lob

private byte[] bytes;

// ...

}

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

@Stateless

public class ImageService {

@PersistenceContext

private EntityManager em;

public Image find(Long id) {

return em.find(Image.class, id);

}

}

也可以看看:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值