JSP调用Servlet显示图片

来源:互联网 发布:烟台苹果网络营销策划 编辑:程序博客网 时间:2024/05/16 04:43

原文地址:http://www.zhuoda.org/elite/34511.html

 

下在这个 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 程序开始 ===================================

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);
//读数据
hFile.close();
res.setContentType(
"image/*"); //设置返回的文件类型
OutputStream toClient=res.getOutputStream();
//得到向客户端输出二进制数据的对象
toClient.write(data);
//输出数据
toClient.close();
}
catch(IOException e)
//错误处理
{
PrintWriter toClient = res.getWriter();
//得到向客户端输出文本的对象
res.setContentType(
"text/html;charset=gb2312");
toClient.write(
"无法打开图片!");
toClient.close();
}
}
}