由于我工作需要,開始學習 java 和 jsp, 這段時間會多寫點關于 jsp 的文章,以加強自己對jsp的了解。 這篇文章主要是介紹如何調用 servlet 顯示圖片,其實也讓大家知道如何在向客戶端輸出二進制數(shù)據(jù)。
下在這個 1.htm 用來調用servlet
<!------------ 文件 1.htm 開始--------------------> <html> <head><title>用servlet 顯示圖片</title></head>
<body> <img src="http://localhost:8080/servlet/showimage">
</body> </html>
<!------------ 文件 1.htm 結束 ---------------->
在Servlet 中,是靠 doGet()、 doPost() 等方法來響應 GET POST 方法的,這里我們響應的是GET,所以定義了一個 doGet() 方法下面是源程序:
//====================== showimage.java 程序開始 ===================================
在html 調用時只 import java.io.*; import java.text.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*;
public class showimage extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
try{ FileInputStream hFile = new FileInputStream("d:\\1.gif"); // 以byte流的方式打開文件 d:\1.gif int i=hFile.available(); //得到文件大小 byte data[]=new byte[i]; hFile.read(data); //讀數(shù)據(jù) hFile.close(); res.setContentType("image/*"); //設置返回的文件類型 OutputStream toClient=res.getOutputStream(); //得到向客戶端輸出二進制數(shù)據(jù)的對象 toClient.write(data); //輸出數(shù)據(jù) toClient.close(); } catch(IOException e) //錯誤處理 { PrintWriter toClient = res.getWriter(); //得到向客戶端輸出文本的對象 res.setContentType("text/html;charset=gb2312"); toClient.write("無法打開圖片!"); toClient.close(); }
}
}
|