需求:java
經過servlet讀取圖片地址,而後顯示在jsp頁面上web
jsp頁面:app
1 <img style="width:240px; height:200px;" src="<%=request.getContextPath()%>/chartServlet"> jsp
wel.xml 配置:url
1 <servlet> 2 <servlet-name>chartServlet</servlet-name> 3 <servlet-class>com.stronginfo.transenly.website.servlet.chartServlet</servlet-class> 4 </servlet> 5 <servlet-mapping> 6 <servlet-name>chartServlet</servlet-name> 7 <url-pattern>/chartServlet</url-pattern> 8 </servlet-mapping>
java代碼:spa
1 package com.stronginfo.transenly.website.servlet; 2 3 import java.io.FileInputStream; 4 import java.io.IOException; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.ServletOutputStream; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 import com.stronginfo.core.dao.OrderDao; 13 import com.stronginfo.transenly.util.ConfigManager; 14 15 public class chartServlet extends HttpServlet 16 { 17 18 private static final long serialVersionUID = 1L; 19 20 21 22 23 public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException 24 { 25 26 27 ServletOutputStream outStream = res.getOutputStream();// 獲得向客戶端輸出二進制數據的對象 28 FileInputStream fis = new FileInputStream(圖片路徑); // 以byte流的方式打開文件 29 // 讀數據 30 byte data[] = new byte[1000]; 31 while (fis.read(data) > 0) 32 { 33 outStream.write(data); 34 } 35 fis.close(); 36 res.setContentType("image/*"); // 設置返回的文件類型 37 outStream.write(data); // 輸出數據 38 39 outStream.close(); 40 41 } 42 43 }