gpt4 book ai didi

image - 如何使用托管 bean 从 JSF 页面内的数据库加载图像?

转载 作者:行者123 更新时间:2023-12-04 17:05:16 25 4
gpt4 key购买 nike

我有一个包含一些图像的数据库。谁能解释我如何在 JSF 页面中加载图像?

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

最佳答案

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

在您的 JSF 页面中使用它:

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

假设 bean.getImageId()返回 123 ,这在 HTML 中呈现为:
<img src="images/123">

创建一个 Servlet映射在 web.xml 中的类在 url-pattern 上的 /images/*并实现其 doGet()方法如下:
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从数据库。

可以在 this article 中找到扩展示例.

关于image - 如何使用托管 bean 从 JSF 页面内的数据库加载图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2848964/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com