?? 0125.htm
字號(hào):
<html>
<head>
<title>新時(shí)代軟件教程:操作系統(tǒng) 主頁(yè)制作 服務(wù)器 設(shè)計(jì)軟件 網(wǎng)絡(luò)技術(shù) 編程語(yǔ)言 文字編輯</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<style>
<!--
body, table {font-size: 9pt; font-family: 宋體}
a {text-decoration:none}
a:hover {color: red;text-decoration:underline}
.1 {background-color: rgb(245,245,245)}
-->
</style>
</head>
<p align="center"><script src="../../1.js"></script></a>
<p align="center"><big><strong>從數(shù)據(jù)庫(kù)中讀取并生成圖片的Servlet</strong></big></p>
<div align="right">(文/邵望)</div>
<pre>
大體思路
1)創(chuàng)建ServletOutputStream對(duì)象out,用于以字節(jié)流的方式輸出圖像
2)查詢數(shù)據(jù)庫(kù),用getBinaryStream方法返回InputStream對(duì)象in
3)創(chuàng)建byte數(shù)組用作緩沖,將in讀入buf[],再由out輸出
注:下面的例程中數(shù)據(jù)庫(kù)連接用了ConnectionPool,以及參數(shù)的獲得進(jìn)行了預(yù)處理
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() {
}
}
</pre>
</table>
<p align="center"><script src="../../2.js"></script></a>
</body>
</html>
?? 快捷鍵說(shuō)明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號(hào)
Ctrl + =
減小字號(hào)
Ctrl + -