将图片从servlet加载到JSP

时间:2017-05-31 02:17:20

标签: java jsp servlets

您好我不知道为什么当我尝试从servlet加载图片时会发生这种情况。

这是我的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

你有什么想法,为什么它不会显示图片?

1 个答案:

答案 0 :(得分:2)

src代码的img属性需要指向有效的网址

e.g。

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