如何使用托管bean从JSF页面内的数据库加载图像? [英] How do I load an image from a DB inside a JSF page using managed beans?

查看:168
本文介绍了如何使用托管bean从JSF页面内的数据库加载图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一些图像的数据库。任何人都可以解释我如何在JSF页面中加载图像吗?

I have a database with some images. Could anyone explain me how I could load an image in a JSF page?

我已经有一个托管bean将Image对象转换为streamcontent。这个streamcontent是从标签< h:graphicImage> 中的页面调用的,但当我检查页面的源代码时,没有 src 可以加载图像。

I already have a managed bean that converts an Image object into a streamcontent. This streamcontent is called from the page in a tag <h:graphicImage>, but when I check the source code of the page, there's no src where the image could be loaded.

推荐答案

JSF < h :graphicImage> 呈现为HTML < img> 元素。它的 src 属性应该指向一个URL,而不是指向二进制内容。因此,您应该将URL(或至少一些标识符作为请求参数或pathinfo)存储在JSF bean中,并创建一个单独的servlet以将图像从数据库流式传输到HTTP响应。

The JSF <h:graphicImage> get rendered as a HTML <img> element. Its src attribute should point to an URL, not to the binary contents. So you should store the URL (or at least some identifier as request parameter or pathinfo) in the JSF bean and create a separate servlet to stream the image from the DB to the HTTP response.

在JSF页面中使用它:

Use this in your JSF page:

<h:graphicImage value="images/#{bean.imageId}">

假设 bean.getImageId()返回 123 ,这在HTML中呈现为:

Assuming that bean.getImageId() returns 123, this get rendered in HTML as:

<img src="images/123">

创建一个映射到的 Servlet web.xml url-pattern / images / * 并按如下方式实现其 doGet()方法。:

Create a Servlet class which is mapped in web.xml on an url-pattern of /images/* and implement its doGet() method as follows.:

Long imageId = Long.valueOf(request.getPathInfo().substring(1)); // 123 (PS: don't forget to handle any exceptions).
Image image = imageDAO.find(imageId); // Get Image from DB.
// Image class is just a Javabean with the following properties:
// private String filename;
// private Long length;
// private InputStream content;

response.setHeader("Content-Type", getServletContext().getMimeType(image.getFilename()));
response.setHeader("Content-Length", image.getLength());
response.setHeader("Content-Disposition", "inline; filename=\"" + image.getFilename() + "\"");

BufferedInputStream input = null;
BufferedOutputStream output = null;

try {
    input = new BufferedInputStream(image.getContent());
    output = new BufferedOutputStream(response.getOutputStream());
    byte[] buffer = new byte[8192];
    int length;
    while ((length = input.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    }
} finally {
    if (output != null) try { output.close(); } catch (IOException logOrIgnore) {}
    if (input != null) try { input.close(); } catch (IOException logOrIgnore) {}
}

中ImageDAO#find()您可以使用 ResultSet#getBinaryStream() 以图像 InputStream

可以在这篇文章

这篇关于如何使用托管bean从JSF页面内的数据库加载图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆