如何在JSP页面中从数据库检索和显示图像?

18 浏览
0 Comments

如何在JSP页面中从数据库检索和显示图像?

在JSP页面中,我如何从数据库中检索和显示图像?

0
0 Comments

如何从数据库中检索并在JSP页面中显示图像?

当我们需要从数据库中检索图像并在JSP页面中显示时,我们可以使用以下方法来解决这个问题:

1. 导入必要的类和包:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpSession;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

2. 创建一个名为displayfetchimage的Servlet类并扩展HttpServlet类:

@WebServlet("/displayfetchimage")
public class displayfetchimage extends HttpServlet {
    // Servlet的代码
}

3. 在doGet和doPost方法中编写代码以从数据库中检索图像并将其显示在JSP页面上:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // TODO Auto-generated method stub
    Statement stmt = null;
    String sql = null;
    BufferedInputStream bin = null;
    BufferedOutputStream bout = null;
    InputStream in = null;
    response.setContentType("image/jpeg");
    ServletOutputStream out;
    out = response.getOutputStream();
    Connection conn = employee.DbConnection.getDatabaseConnection();
    HttpSession session = (HttpSession) request.getSession();
    String ID = session.getAttribute("userId").toString().toLowerCase();
    try {
        stmt = conn.createStatement();
        sql = "select user_image from employee_data WHERE username='" + ID + "' and rownum<=1";
        ResultSet result = stmt.executeQuery(sql);
        if (result.next()) {
            in = result.getBinaryStream(1);
        }
        bin = new BufferedInputStream(in);
        bout = new BufferedOutputStream(out);
        int ch = 0;
        while ((ch = bin.read()) != -1) {
            bout.write(ch);
        }
    } catch (SQLException ex) {
        Logger.getLogger(displayfetchimage.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (bin != null)
                bin.close();
            if (in != null)
                in.close();
            if (bout != null)
                bout.close();
            if (out != null)
                out.close();
            if (conn != null)
                conn.close();
        } catch (IOException | SQLException ex) {
            System.out.println("Error : " + ex.getMessage());
        }
    }
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    // 同样的代码
}

以上就是从数据库中检索和显示图像的解决方案。通过创建一个Servlet类,并在doGet和doPost方法中编写代码来实现。代码中使用了数据库连接、会话管理和输入输出流操作来实现图像的检索和显示。

0
0 Comments

在JSP页面中从数据库中检索和显示图像的方法

在开发JSP页面时,经常会遇到需要从数据库中检索和显示图像的需求。这可能是因为我们将图像作为二进制大对象(BLOB)存储在数据库中,而不是将其保存在文件系统中。要解决这个问题,我们可以将其分为两个子问题来处理。

第一个问题是如何从MySQL中加载BLOB。我们可以使用以下代码示例来实现这一点:

try {
    // 创建数据库连接
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "username", "password");
    
    // 创建查询语句
    String sql = "SELECT image FROM images WHERE id = ?";
    PreparedStatement statement = conn.prepareStatement(sql);
    statement.setInt(1, imageId);
    
    // 执行查询
    ResultSet result = statement.executeQuery();
    
    if (result.next()) {
        // 从结果集中获取图像
        Blob blob = result.getBlob("image");
        InputStream inputStream = blob.getBinaryStream();
        
        // 将图像保存到本地文件
        File file = new File("image.jpg");
        FileOutputStream outputStream = new FileOutputStream(file);
        
        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
        
        // 关闭流和连接
        outputStream.close();
        inputStream.close();
        conn.close();
    }
} catch (SQLException e) {
    e.printStackTrace();
}

第二个问题是如何动态显示图像。我们可以使用以下代码示例来实现这一点:

try {
    // 创建数据库连接
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "username", "password");
    
    // 创建查询语句
    String sql = "SELECT image FROM images WHERE id = ?";
    PreparedStatement statement = conn.prepareStatement(sql);
    statement.setInt(1, imageId);
    
    // 执行查询
    ResultSet result = statement.executeQuery();
    
    if (result.next()) {
        // 从结果集中获取图像
        Blob blob = result.getBlob("image");
        InputStream inputStream = blob.getBinaryStream();
        
        // 将图像转换为Base64编码
        byte[] bytes = new byte[(int) blob.length()];
        inputStream.read(bytes);
        String base64Image = Base64.getEncoder().encodeToString(bytes);
        
        // 在JSP页面中显示图像
        out.println("");
        
        // 关闭流和连接
        inputStream.close();
        conn.close();
    }
} catch (SQLException e) {
    e.printStackTrace();
}

通过解决这两个问题,我们可以在JSP页面中成功从数据库中检索和显示图像。第一个问题是如何从MySQL中加载BLOB,我们可以使用JDBC API来实现。第二个问题是如何动态显示图像,我们可以将图像转换为Base64编码,并在JSP页面中使用img标签来显示。

0
0 Comments

如何从数据库中检索和显示图像在JSP页面中?

JSP基本上是一种视图技术,用于生成HTML输出。

要在HTML中显示图像,您需要使用HTML 元素。

要让它定位图像,您需要指定其src属性。

src属性需要指向有效的http:// URL,而不是本地磁盘文件系统路径file://,因为当服务器和客户端在物理上不同的机器上运行时,这是不起作用的。

图像URL需要在请求路径(例如http://example.com/context/images/foo.png)或请求参数(例如http://example.com/context/images?id=1)中具有图像标识符。

在JSP / Servlet世界中,您可以让Servlet监听特定URL模式,例如/images/*,这样您就可以在特定的URL上执行一些Java代码。

图像是二进制数据,可以从DB中获取为byte[]或InputStream,JDBC API提供ResultSet#getBytes()和ResultSet#getBinaryStream(),JPA API提供Lob。

在Servlet中,您可以以通常的Java IO方式将此byte[]或InputStream写入响应的OutputStream。

客户端需要被指示将数据处理为图像,因此至少需要设置Content-Type响应头。您可以使用ServletContext#getMimeType()根据图像文件扩展名获取正确的Content-Type响应头。

这就是全部。它几乎可以自己编写代码。让我们从HTML(在JSP中)开始:

如果有必要,您还可以在使用JSTL迭代时使用EL动态设置src:

然后定义/创建一个监听URL模式为/images/*的servlet。下面的示例使用普通的JDBC:

("/images/*")

public class ImageServlet extends HttpServlet {

// content=blob, name=varchar(255) UNIQUE.

private static final String SQL_FIND = "SELECT content FROM Image WHERE name = ?";

(name="jdbc/yourDB") // For Tomcat, define as in context.xml and declare as in web.xml.

private DataSource dataSource;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String imageName = request.getPathInfo().substring(1); // Returns "foo.png".

try (Connection connection = dataSource.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_FIND)) {

statement.setString(1, imageName);

try (ResultSet resultSet = statement.executeQuery()) {

if (resultSet.next()) {

byte[] content = resultSet.getBytes("content");

response.setContentType(getServletContext().getMimeType(imageName));

response.setContentLength(content.length);

response.getOutputStream().write(content);

} else {

response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.

}

}

} catch (SQLException e) {

throw new ServletException("Something failed at SQL/DB level.", e);

}

}

}

就是这样。如果您担心HEAD和缓存头以及在这些请求上正确响应,请使用此静态资源servlet的抽象模板。

此外,您还可以参考以下内容:

- 如何在基于servlet的应用程序中连接到JDBC数据库/数据源?

- 如何上传图像并将其保存在数据库中?

- 从Java Web应用程序中的应用程序服务器外部提供静态数据的最简单方法。

请注意,这个问题和答案是基于纯JSP / Servlet的,而不是Spring MVC。如果您真的需要发布Spring MVC相关的答案/评论,请寻找正确的问题。

0