无论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);
}
}
也可以看看: