THIS IS A TEST INSTANCE. ALL YOUR CHANGES WILL BE LOST!!!!
...
- Create a JSP page with the name
ImageDownload.jsp
. - Add the following code to
ImageDownload.jsp
:
As can be seen from <form action="/WebJDBC/ImageDownload"> this JSP requests the ImageDownload servlet when the form is submitted.Code Block title ImageDownload.jsp borderStyle solid <%@ 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>Download Image</title> </head> <body> <h2>Name a Image to download</h2> <form action="/WebJDBC/ImageDownload"> <table> <tr> <td> Name of the Image </td> <td> <Input type="text" name="ImageName"> </td> </tr> <tr> <td> <Input type="submit" value="submit"> </td> <tr> </table> </form> </body> </html>
- Create a new servlet
ImageDownload.java
and add the following code:Code Block title ImageDownload.java borderStyle solid package jdbc; import java.io.IOException; import java.io.OutputStream; import java.sql.Blob; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.sql.DataSource; public class ImageDownload extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { @Resource(name = "jdbc/userds") private DataSource ds; static final long serialVersionUID = 1L; public ImageDownload() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request, response); } protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Connection dbconnect = null; ResultSet rs = null; PreparedStatement stmnt = null; try { dbconnect = ds.getConnection(); String s=request.getParameter("ImageName"); stmnt = dbconnect.prepareStatement("SELECT PIC FROM PICTURES WHERE NAME=?"); stmnt.setString(1, s); rs = stmnt.executeQuery(); if (rs.next()) { // Get as a BLOB Blob aBlob = rs.getBlob(1); byte[] b = new byte[4096]; java.io.InputStream ip = aBlob.getBinaryStream(); OutputStream out = null; int c = 0; out = response.getOutputStream(); response.setContentType("image/jpeg"); while (c != -1) { c = ip.read(b); if (c > 0) { out.write(b); , 0, c); out.flush(); } ip.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try{ dbconnect.close(); stmnt.close(); rs.close(); }catch(SQLException e){ e.printStackTrace(); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doProcess(request, response); } }
...