欢迎光临
我们一直在努力

从数据库中读取并生成图片的Servlet-JSP教程,Jsp/Servlet

建站超值云服务器,限时71元/月

大体思路
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("../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() {
  }

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 从数据库中读取并生成图片的Servlet-JSP教程,Jsp/Servlet
分享到: 更多 (0)

相关推荐

  • 暂无文章