用JSP从数据库中读取图片并显示在网页上

<1>先在mysql下建立如下的table. 并insert图像. 
mysql.sql文件如下: 

[sql] view plain copy
 
  1. CREATE TABLE photo (   
  2. photo_no int(6) unsigned NOT NULL auto_increment,   
  3. image blob,   
  4. PRIMARY KEY (`photo_no`)   
  5. )   


<2>把show.jsp放在tomcat的任意目录下. show.jsp作用:从数据库中读出blob,并产生image/jpg. 

show.jsp文件如下: 

[html] view plain copy
 
  1. <%@ page contentType="text/html; charset=gbk" %>   
  2. <%@ page import="java.io.*"%>   
  3. <%@ page import="java.sql.*, javax.sql.*" %>   
  4. <%@ page import="java.util.*"%>   
  5. <%@ page import="java.math.*"%>   
  6. <%   
  7. String photo_no = request.getParameter("photo_no");   
  8. //mysql连接   
  9. Class.forName("com.mysql.jdbc.Driver").newInstance();   
  10. String URL="jdbc:mysql://localhost:3306/job?user=root&password=111111";   
  11. Connection con = DriverManager.getConnection(URL);   
  12.   
  13. //oracle连接   
  14. //String URL="jdbc:oracle:thin@localhost:1521:orcl2";   
  15. //user="system";   
  16. //password="manager";   
  17. //Connection con = DriverManager.getConnection(URL,user,password);   
  18.   
  19.   
  20. try{   
  21. // 准备语句执行对象   
  22. Statement stmt = con.createStatement();   
  23. String sql = " SELECT * FROM PHOTO WHERE photo_no = "+ photo_no;   
  24. ResultSet rs = stmt.executeQuery(sql);   
  25. if (rs.next()) {   
  26. Blob b = rs.getBlob("photo_image");   
  27. long size = b.length();   
  28. //out.print(size);   
  29. byte[] bs = b.getBytes(1, (int)size);   
  30. response.setContentType("image/jpeg");   
  31. OutputStream outs = response.getOutputStream();   
  32. outs.write(bs);   
  33. outs.flush();   
  34. rs.close();   
  35. }   
  36. else {   
  37. rs.close();   
  38. response.sendRedirect("./images/error.gif");   
  39. }   
  40. }   
  41. finally{   
  42. con.close();   
  43. }   
  44. %>   

<3>把如下文件放在show.jsp的同一目录下. 
index.html文件如下: 

[html] view plain copy
 
    1. <html>  
    2. <head>  
    3. <title> 图像测试 </title>  
    4. </head>  
    5. <body>  
    6. <table>  
    7. <tr>  
    8.     <td>  
    9.         图像测试  
    10.     </td>  
    11. </tr>  
    12. <tr>  
    13.     <td>  
    14.         <img src="show.jsp?photo_no=2">  
    15.     </td>  
    16. </tr>  
    17. </table>  
    18. </body>  
    19. </html>  
原文地址:https://www.cnblogs.com/dahaoheshan/p/7305024.html