大体思路
1)创建servletoutputstream对象out,用于以字节流的方式输出图像
2)查询数据库,用getbinarystream方法返回inputstream对象in
3)创建byte数组用作缓冲,将in读入buf[],再由out输出
注:下面的例程中数据库连接用了connectionpool,以及参数的获得进行了预处理
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() {
}
}