📅  最后修改于: 2023-12-03 14:52:02.027000             🧑  作者: Mango
开发一个 web 应用程序,常常涉及到操作数据库和上传、下载、展示图像等操作。本文将介绍如何使用 Servlet 和 JDBC 技术,在 MySql 数据库中保存和展示图像。
在 MySql 数据库中创建一个表,用于存储图像。
CREATE TABLE images (
id INT(11) PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(255),
image LONGBLOB
);
创建一个 Servlet,用于上传图像到服务器并将图像的信息保存到数据库中。其中 com.mysql.jdbc.Driver
是 MySql 的 JDBC 驱动。
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet(name = "UploadServlet", urlPatterns = {"/upload"})
@MultipartConfig(maxFileSize = 1024 * 1024 * 5)
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 获取上传的图像信息
String name = request.getParameter("name");
InputStream inputStream = null;
Part filePart = request.getPart("image");
if (filePart != null) {
inputStream = filePart.getInputStream();
}
Connection conn = null;
String message = null;
try {
// 连接数据库
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 插入数据到数据库
String sql = "INSERT INTO images (name, image) values (?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, name);
if (inputStream != null) {
statement.setBlob(2, inputStream);
}
int row = statement.executeUpdate();
if (row > 0) {
message = "图像上传成功";
}
} catch (SQLException e) {
message = "SQL 错误: " + e.getMessage();
} catch (ClassNotFoundException e) {
message = "JDBC 驱动错误: " + e.getMessage();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
message = "SQL 错误: " + e.getMessage();
}
}
}
request.setAttribute("message", message);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
}
创建一个上传表单,用于上传图像。
<form method="POST" action="upload" enctype="multipart/form-data">
<input type="text" name="name">
<input type="file" name="image">
<input type="submit" value="上传">
</form>
创建一个页面,用于从数据库中获取图像并展示。
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 java.sql.SQLException;
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(name = "ImageServlet", urlPatterns = {"/image"})
public class ImageServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
String message = null;
try {
// 连接数据库
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
// 获取图像信息
int id = Integer.parseInt(request.getParameter("id"));
String sql = "SELECT * FROM images WHERE id = ?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setInt(1, id);
ResultSet result = statement.executeQuery();
if (result.next()) {
String name = result.getString("name");
response.setContentType("image/jpeg"); // jpg 格式的图像
response.setContentLength((int) result.getBlob("image").length());
OutputStream outputStream = response.getOutputStream();
outputStream.write(result.getBlob("image").getBytes(1, (int) result.getBlob("image").length()));
outputStream.close();
} else {
message = "无法找到指定的图像";
}
} catch (SQLException e) {
message = "SQL 错误: " + e.getMessage();
} catch (ClassNotFoundException e) {
message = "JDBC 驱动错误: " + e.getMessage();
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
message = "SQL 错误: " + e.getMessage();
}
}
}
request.setAttribute("message", message);
}
}
在页面中创建一个链接,用于从数据库中获取图像并展示。
<a href="image?id=1">展示图像</a>
使用 Servlet 和 JDBC 技术,可以将图像保存到 MySql 数据库中,并在 web 页面中展示图像。本文介绍了上传和展示图像的方法,读者可以根据需求进行修改和拓展。