Диаграмма JFree с использованием сервлета в jsp

Как я могу нарисовать линейную диаграмму с помощью сервлетов и визуализированного изображения? Я написал сервлет и создал диаграмму. Но я не знаю, как отобразить ее на моей странице jsp.

мой код сервлета:

public class GraphGen extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        genGraph(req, resp);
    }

    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        genGraph(req, resp);
    }

    @SuppressWarnings("deprecation")
    public void genGraph(HttpServletRequest req, HttpServletResponse resp) {

        try {
            OutputStream out = resp.getOutputStream();

            // Create a simple Bar chart
            System.out.println("Setting dataset values");

            DefaultCategoryDataset dataset = new DefaultCategoryDataset();
            dataset.setValue(30, "Girls","SCIENCE CLASS");
            dataset.setValue(30,  "Boys","SCIENCE CLASS");
            dataset.setValue(10,  "Girls","ECONOMICS CLASS");
            dataset.setValue(50, "Boys","ECONOMICS CLASS");
            dataset.setValue(5, "Girls","LANGUAGE CLASS");
            dataset.setValue(55, "Boys","LANGUAGE CLASS");

            JFreeChart chart = ChartFactory.createBarChart3D(
                "Comparison between Girls and Boys in Science," + "Economics and Language classes",
                "Students Comparisons", "No of Students",
                dataset,
                PlotOrientation.VERTICAL,
                true,
                true,
                false);

            chart.setBackgroundPaint(Color.white);

            // Set the background colour of the chart
            chart.getTitle().setPaint(Color.blue);

            // Adjust the colour of the title
            CategoryPlot plot = chart.getCategoryPlot();

            // Get the Plot object for a bar graph
            plot.setBackgroundPaint(Color.white);
            plot.setRangeGridlinePaint(Color.red);

            CategoryItemRenderer renderer = plot.getRenderer();
            renderer.setSeriesPaint(0, Color.red);
            renderer.setSeriesPaint(1, Color.green);
            renderer.setItemURLGenerator(
                new StandardCategoryURLGenerator(
                    "index1.html",
                    "series",
                    "section"));
            renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());

            resp.setContentType("image/png");

            ChartUtilities.writeChartAsPNG(out, chart, 625, 500);

        } catch (Exception e) {
            System.err.println("Problem occurred creating chart." + e.getMessage());
        }
    }

person Bahareh    schedule 24.07.2011    source источник
comment
Вы уже спрашивали доктора Google, например. stackoverflow.com/questions/1255717/?   -  person home    schedule 24.07.2011
comment
Спасибо, с какой проблемой вы столкнулись, что именно не работает?   -  person home    schedule 24.07.2011
comment
Как я могу отобразить это изображение на странице jsp?   -  person Bahareh    schedule 24.07.2011
comment
Вы должны включить ссылку <img src="path_to_your_servlet"/> в свой JSP. Помните, что в вашем случае сервлет является изображением.   -  person home    schedule 24.07.2011
comment
я использовал этот тег. но это не сработало.   -  person Bahareh    schedule 24.07.2011
comment
Если вы укажете свой браузер прямо на сервлет, он покажет изображение?   -  person home    schedule 24.07.2011
comment
Можете ли вы прислать мне пример, который работает правильно?   -  person Bahareh    schedule 24.07.2011
comment
Видите ли вы какие-либо исключения при вызове сервлета?   -  person home    schedule 24.07.2011
comment
Предложение @home верное. Вам необходимо связать сервлет с тегом <img/>. Я бы посоветовал вам предоставить больше полезных отзывов, чем это не сработало.   -  person Steven Benitez    schedule 24.07.2011


Ответы (1)


chart.setBackgroundPaint(Color.white);

            // Set the background colour of the chart
            chart.getTitle().setPaint(Color.blue);

            // Adjust the colour of the title
            CategoryPlot plot = chart.getCategoryPlot();

            // Get the Plot object for a bar graph
            plot.setBackgroundPaint(Color.white);
            plot.setRangeGridlinePaint(Color.red);

            CategoryItemRenderer renderer = plot.getRenderer();
            renderer.setSeriesPaint(0, Color.red);
            renderer.setSeriesPaint(1, Color.green);
            renderer.setItemURLGenerator(
                new StandardCategoryURLGenerator(
                    "index1.html",
                    "series",
                    "section"));
            renderer.setToolTipGenerator(new StandardCategoryToolTipGenerator());

            resp.setContentType("image/png");

            ChartUtilities.writeChartAsPNG(out, chart, 625, 500);

......Вместо приведенного выше кода просто используйте этот код, это проще......

JFreeChart chart = ChartFactory.createBarChart3D(
                "Comparison between Girls and Boys in Science," + "Economics and Language classes",
                "Students Comparisons", "No of Students",
                dataset,
                PlotOrientation.VERTICAL,
                true,
                true,
                false);


            try {

                final ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
                final File file1 = new File(getServletContext().getRealPath(".") + "/images/piechart/lineChart.png");

                ChartUtilities.saveChartAsPNG(file1, chart, 600, 400, info);
            } catch (Exception e) {
                System.out.println(e);

            }  

...............используйте этот код на странице jsp .......

<div>
    <img src="path/images/piechart/lineChart.png"
         width="600" height="400" border="0" usemap="#chart" />
 </div>
person anoop    schedule 07.06.2012