【发布时间】:2018-09-04 07:40:06
【问题描述】:
我正在尝试从数据库中检索多个图像并将这些图像显示在另一个 JSP 页面中。 首先,我尝试使用单个图像来显示特定的 JSP 页面,我检索到但显示显示为文件类型, 我想在特定的 JSP 页面中显示该图像。 我正在使用 MySQL 数据库。
我的 servlet 代码:
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
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("/Retrieve")
public class Retrieve extends HttpServlet {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{ Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/vikas", "root", "root");
ps = con.prepareStatement("select * from rough");
rs=ps.executeQuery();
if (rs.next()) {
byte[] content = rs.getBytes("image");
response.setContentLength(content.length);
response.getOutputStream().write(content);
request.setAttribute("image", content);
RequestDispatcher rd=request.getRequestDispatcher("View.jsp");
rd.forward(request, response);
} else {
response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
}
} catch (SQLException e) {
throw new ServletException("Something failed at SQL/DB level.", e);
}
}
}
jsp代码:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Display Image</title>
</head>
<body>
<div>THE DISPLAY</div>
<div style="width:25%; height:25%">
<%request.getAttribute("image"); %>
</div>
</body>
</html>
【问题讨论】:
-
你能把你的jsp代码贴在这里
-
也许你需要添加内容类型。类似于: response.setContentType(getServletContext().getMimeType(imageName));
-
首先,如果你想转发,你不应该写入响应的输出流或设置内容长度。您可以尝试将字节转换为 Base64 图像文件字符串,例如 png 或 jpg 并将其传递给属性,然后作为请求范围属性图像传递给 img 标签上的 src。
<div style="width:25%; height:25%"> <img src="<%=request.getAttribute("image"); %>"/> </div>