java - 如何从 mysql 数据库检索图像并将其显示在 HTML 中的 <td> 和 <img> 标记内?

标签 java html jsp servlets

如何从 mysql 数据库检索图像并将其显示在 HTML 标记内,并且该 img 标记应放置在内部?这是我的代码: 它仅显示图像。它不显示除图像之外的任何内容。

提前致谢。

 <%@ 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>Insert title here</title>
</head>
<body>
<%@ page import="java.io.*"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.text.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="javax.servlet.http.HttpSession"%>
<%@ page language="java"%>
<%@ page session="true"%>
<%
  try{
   //PrintWriter out=response.getWriter();

  out.println("Retrieve Image Example!");
  String driverName = "com.mysql.jdbc.Driver";
  String url = "jdbc:mysql://localhost:3306/";
  String dbName = "db";
  String userName = "root";
  String password = "root";
  Connection con = null;
  Class.forName(driverName);
  con = DriverManager.getConnection(url+dbName,userName,password);
  Statement st = con.createStatement();

 %>
  <table border='1'>
 <tr>
 <td>Name:</td><td>
 </td>My Name</td>
 </tr>
 <tr>
 <td>Image:</td>
 <td width=10px;>
 <%
 PreparedStatement pre1 = con.prepareStatement("select * from image where id="+8);
 ResultSet rs1=pre1.executeQuery();
 while(rs1.next())   
 {byte[] bytearray1 = new byte[4096];  
              int size1=0;  
             InputStream sImage1;  
               sImage1 = rs1.getBinaryStream(2);  
               response.reset();  
              response.setContentType("image/jpeg");  
              response.addHeader("Content-Disposition","filename=logo.jpg");  
              while((size1=sImage1.read(bytearray1))!= -1 )  
                {  
                  response.getOutputStream().write(bytearray1,0,size1);  
                }  
              response.flushBuffer(); 
              sImage1.close();  
              rs1.close();  
           }


    out.println("Retrieved Successfully!");
  pre.close();
  con.close();  
  }
  catch (Exception e){
  out.println(e.getMessage());
  }
%>
</td></tr>
 </table>
</body>
  </html>

最佳答案

图像作为单独的请求加载到加载 html 的请求中。因此,您需要:

  • 建立在指定 img 元素的 src 时使用的 URL 编码方案。
  • 将 servlet(或类似的)映射到该 URL。 servlet 根据在其响应中返回该图像的 URL 参数加载图像。

关于java - 如何从 mysql 数据库检索图像并将其显示在 HTML 中的 <td> 和 <img> 标记内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14584630/

相关文章:

html - 在 float DIV 中放置相对定位的元素

jsp - 自定义404错误页面不适用于Struts 2

java - 在同一页面中的 javascript 中检索 arraylist 的值

java - Gremlin drop() 无法通过 java api 工作

java - 将结果集从 SQL 数组转换为字符串数组

html - 在 css 之后 Bootstrap 空白空间

javascript - 将函数内部定义的javascript变量传递给jsp而不重新加载

java - 乔达日期时间 : Parse date with "CEST" in string

java - 从子树节点聚合值的算法

javascript - 不要在触摸设备上显示悬停状态