Servlet| Data | General idea of database
1 Create the Servletoutputstream object out to output the image as a byte stream
2) Query the database, using the Getbinarystream method to return the InputStream object in
3 creates a byte array as a buffer, reads in into buf[], and then outputs the
Note: In the following routine, the database connection is ConnectionPool, and the parameters are obtained by preprocessing
Package net.seasky.music;
Import javax.servlet.*;
Import javax.servlet.http.*;
Import java.io.*;
Import java.util.*;
Import java.sql.*;
Import net.seasky.util.*;
Import Net.seasky.database.DbConnectionManager;
public class Coverservlet extends HttpServlet {
private static final String Content_Type = "Image/gif";
public void init (ServletConfig config) throws servletexception {
Super.init (config);
}
public void doget (HttpServletRequest request, httpservletresponse response
) throws Servletexception, IOException {
Response.setcontenttype (Content_Type);
int albumid;
Servletoutputstream out = Response.getoutputstream ();
try {
albumID = Parammanager.getintparameter (Request, "albumID", 0);
}
catch (Exception e) {
Response.sendredirect ("http://www.kissjava.com/doc/J2EE/jdbc_jdo/images/h00/h39/ErroePage.jsp");
Return
}
try {
InputStream In=this.getcover (albumID);
int Len;
byte buf[]=new byte[1024];
while ((Len=in.read (buf,0,1024))!=-1) {
Out.write (Buf,0,len);
}
}
catch (IOException IoE) {
Ioe.printstacktrace ();
}
}
Private InputStream getcover (int albumid) {
InputStream In=null;
Connection cn = NULL;
PreparedStatement PST = NULL;
try {
Cn=dbconnectionmanager.getconnection ();
Cn.setcatalog ("Music");
Pst=cn.preparestatement ("select img from cover where ID =?");
Pst.setint (1,albumid);
ResultSet Rs=pst.executequery ();
Rs.next ();
In=rs.getbinarystream ("img");
}
catch (SQLException Sqle) {
System.err.println ("Error in Coverservlet:getcover ()-" + Sqle);
Sqle.printstacktrace ();
}
finally {
try {
Pst.close ();
Cn.close ();
}
catch (Exception e) {
E.printstacktrace ();
}
}
return in;
}
public void Destroy () {
}
}