明輝手游網(wǎng)中心:是一個免費提供流行視頻軟件教程、在線學習分享的學習平臺!

從數(shù)據(jù)庫中讀取并生成圖片的Servlet

[摘要]大體思路 1)創(chuàng)建ServletOutputStream對象out,用于以字節(jié)流的方式輸出圖像 2)查詢數(shù)據(jù)庫,用getBinaryStream方法返回InputStream對象in 3)創(chuàng)建byt...
大體思路
1)創(chuàng)建ServletOutputStream對象out,用于以字節(jié)流的方式輸出圖像
2)查詢數(shù)據(jù)庫,用getBinaryStream方法返回InputStream對象in
3)創(chuàng)建byte數(shù)組用作緩沖,將in讀入buf[],再由out輸出

注:下面的例程中數(shù)據(jù)庫連接用了ConnectionPool,以及參數(shù)的獲得進行了預處理

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() {
}