public class Servlet04 extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("响应图片...");
// 设置图片的响应类型
resp.setContentType("image/jpeg");
// 得到项目在服务器中的真实路径
String path = req.getServletContext().getRealPath("/");
// 得到图片的存放路径,和真实路径拼接在一起
String filePath = path + "/WEB-INF/jay.jpg";
// 通过路径得到file对象
File file = new File(filePath);
// 判断文件是否存在并且是一个标准文件
if (file.exists() && file.isFile()) {
// 得到输出流
ServletOutputStream out = resp.getOutputStream();
// 得到file对象的输入流
InputStream in = new FileInputStream(file);
// 输出
byte[] car = new byte[1024];
int len = 0;
while((len = in.read(car)) != -1) {
out.write(car, 0, len);
}
// 关闭资源
out.flush(); // 刷新流
in.close();
out.close();
} else {
System.out.println("文件不存在!");
}
System.out.println(path);
}
}