2017-05-31 80 views
0

你好,我不知道爲什麼會發生這種情況,當我嘗試從servlet加載圖片。從servlet加載圖片到JSP

這是我的JSP:

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %> 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 

<!DOCTYPE html> 
<html> 
    <head> 
    </head> 
    <body bgcolor="${pickedBgCol}"> 
    <h3><a href="/webapp2">Home</a></h3> 
    <h3>OS usage</h3> 
    <p>Here are the results of OS usage in survey that we completed.</p> 
    <img src="reportImage" /> 
    </body> 
</html> 

,這是我的servlet:

package hr.fer.zemris.java.servlets; 

import java.awt.image.RenderedImage; 
import java.io.IOException; 

import javax.imageio.ImageIO; 
import javax.servlet.ServletException; 
import javax.servlet.ServletOutputStream; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import org.jfree.chart.ChartFactory; 
import org.jfree.chart.JFreeChart; 
import org.jfree.chart.plot.PiePlot3D; 
import org.jfree.data.general.DefaultPieDataset; 
import org.jfree.data.general.PieDataset; 
import org.jfree.util.Rotation; 

@WebServlet(name = "usagePieChart", urlPatterns = { "/reportImage" }) 
public class PieChartServlet extends HttpServlet { 

    private static final long serialVersionUID = 1L; 

    @Override 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
     resp.setContentType("image/png"); 
     ServletOutputStream os = resp.getOutputStream(); 

     PieDataset dataset = createDataset(); 
     JFreeChart chart = createChart(dataset, "OS Usage"); 

     RenderedImage chartImage = chart.createBufferedImage(400, 300); 
     ImageIO.write(chartImage, "png", os); 
     os.flush(); 
     os.close(); 
    } 

當我在我的碼頭服務器上運行它,這就是我得到: enter image description here

你有什麼想法,爲什麼它不會顯示圖片?

+0

嘗試調試。日誌顯示了什麼?當您在瀏覽器中直接請求圖片時會發生什麼? – Taylor

+0

確實得到調用嗎? –

+0

當我直接在瀏覽器中請求圖像時,它會按照預期正常顯示。 –

回答

2

img標籤的src屬性需要指向一個有效的URL

例如

<img src="/mywebbApp/reportImage" />