JSP(Java Server Pages)是一种动态网页技术,它允许在HTML或XML文档中直接嵌入Java代码片段和表达式。通过JSP,可以方便地从数据库中读取数据并生成动态内容。
JSP主要用于服务器端的网页开发,可以与Servlet、JavaBean等技术结合使用,实现复杂的业务逻辑。
适用于需要动态生成网页内容的场景,如电子商务网站、社交媒体平台等。
CREATE TABLE images (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
image_data LONGBLOB
);
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
@WebServlet("/getImage")
public class GetImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int imageId = Integer.parseInt(request.getParameter("id"));
byte[] imageData = getImageFromDatabase(imageId);
if (imageData != null) {
response.setContentType("image/jpeg"); // 根据实际图片类型设置
OutputStream os = response.getOutputStream();
os.write(imageData);
os.flush();
os.close();
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
}
}
private byte[] getImageFromDatabase(int imageId) {
String url = "jdbc:mysql://localhost:3306/your_database";
String username = "your_username";
String password = "your_password";
byte[] imageData = null;
try (Connection conn = DriverManager.getConnection(url, username, password);
PreparedStatement ps = conn.prepareStatement("SELECT image_data FROM images WHERE id = ?")) {
ps.setInt(1, imageId);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
imageData = rs.getBytes("image_data");
}
} catch (SQLException e) {
e.printStackTrace();
}
return imageData;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Image Viewer</title>
</head>
<body>
<img src="getImage?id=1" alt="Image">
</body>
</html>
Content-Type
设置不正确。Content-Type
,例如image/jpeg
、image/png
等。通过以上步骤和示例代码,你可以实现从数据库中读取图片并在JSP页面中显示的功能。
领取专属 10元无门槛券
手把手带您无忧上云