如何在jsp页面中数据库图片

3811 2025-10-08 00:55:03

import java.io.IOException;

import java.io.OutputStream;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.sql.ResultSet;

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

@WebServlet("/DisplayImage")

public class DisplayImage extends HttpServlet {

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

String url = "jdbc:mysql://localhost:3306/yourdatabase";

String username = "yourusername";

String password = "yourpassword";

Connection conn = null;

PreparedStatement pstmt = null;

ResultSet rs = null;

try {

Class.forName("com.mysql.cj.jdbc.Driver");

conn = DriverManager.getConnection(url, username, password);

pstmt = conn.prepareStatement("SELECT image FROM images WHERE id = ?");

pstmt.setInt(1, Integer.parseInt(request.getParameter("id")));

rs = pstmt.executeQuery();

if (rs.next()) {

response.setContentType("image/jpeg");

OutputStream os = response.getOutputStream();

os.write(rs.getBytes("image"));

os.flush();

os.close();

}

} catch (Exception e) {

e.printStackTrace();

} finally {

try {

if (rs != null) rs.close();

if (pstmt != null) pstmt.close();

if (conn != null) conn.close();

} catch (Exception e) {

e.printStackTrace();

}

}

}

}

蓍蔡的解释
游戏玩家必看!揭秘怪多久刷新的秘密与技巧