JFreeChart Dynamic Pie Chart Example Java Servlet Tutorial

We have been discussing how to invoke JFreeChart using a Java Servlet and paint the resulting chart on the browser for sometime now. In the examples discussed so far, the charts created were static in nature; i.e. the servlet was not able to accept user inputs and generate dynamic chart as an output. In this post, we will provide dynamic inputs to our chart servlet using a HTML form and use the user provided inputs to return a chart object back to the browser. In order to do this, we will first create a simple HTML form as shown below, that accepts the marks obtained by a student in five different subjects. Refer to the code below, that shows how to create the HTML form;

<html>
<head>
  <Title>Generate Dynamic Pie Chart with JFreeChart and HTTP Servlet</Title>
</head>
<body BGCOLOR="#CCFFCC">
<H2>Enter your marks to get a Pie Chart Generated with JFreechart API</H2>
<!-- We create a simple form to accept user inputs -->
<!-- The action for this form points to the servlet URL created in earlier posts -->
<FORM ACTION="servlets/servlet/PieChartServlet" METHOD="POST">
Maths:<INPUT TYPE="TEXT" NAME="Maths"><BR>
Physics:<INPUT TYPE="TEXT" NAME="Physics"><BR>
Chemistry:<INPUT TYPE="TEXT" NAME="Chemistry"><BR>
Biology:<INPUT TYPE="TEXT" NAME="Biology"><BR>
English:<INPUT TYPE="TEXT" NAME="English"><BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">  
</FORM>
</body>
</html>
You will have to copy this html to a convenient place in your tomcat webserver.A screenshot of this HTML form is provided below.
Dynamic Pie Chart with JFreeChart
HTML Form Used to Create Dynamic Pie Chart Using JFreeChart
Now, when you click on Submit Order (i.e. request, renamed in the HTML code), the Servlet written in our servlet tutorial will accept the values entered in the page and send a dynamic pie chart back to the browser , after generating it in JFreeChart. Since we are posting data in the form to the servlet we have to modify the servlet code slightly to have a doPost method. The servlet should accept the form elements and use them to create a chart now. A modified servlet code to meet this requirement is provided below;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import java.awt.Color;
import org.jfree.chart.plot.PiePlot;
/* Code for the HTTP Servlet that will return the Pie Chart as a PNG image
back to the browser after generating it using JFreeChart API */
public class PieChartServlet extends HttpServlet {
public PieChartServlet() {
/* No code in the constructor for this demonstration */
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
        OutputStream out = response.getOutputStream(); /* Get the output stream from the response object */
        try {
                DefaultPieDataset myServletPieChart = new DefaultPieDataset();
                /* We will now get the values posted to us from the HTML form, to generate a dynamic pie chart */
                /* to get the form values we use request.getParameter method. We have to convert this to Double format to 
                pass this as an input to our pie chart*/
                /* The NAME used in HTML form will serve as input to getParameter */
                myServletPieChart.setValue("Maths",Double.parseDouble(request.getParameter("Maths")));
                myServletPieChart.setValue("Physics", Double.parseDouble(request.getParameter("Physics")));
                myServletPieChart.setValue("Chemistry", Double.parseDouble(request.getParameter("Chemistry")));
                myServletPieChart.setValue("Biology", Double.parseDouble(request.getParameter("Biology")));
                myServletPieChart.setValue("English",Double.parseDouble(request.getParameter("English")));        
                JFreeChart mychart = ChartFactory.createPieChart("HTTP Servlet - Dynamic Pie Chart Example",myServletPieChart,true,true,false);
                /* We use the configurator to define labels for the chart, which can be shown on image also */
                PiePlot ColorConfigurator = (PiePlot) mychart.getPlot();
                ColorConfigurator.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}:{1}"));
                ColorConfigurator.setLabelBackgroundPaint(new Color(220, 220, 220));  
                response.setContentType("image/png"); /* Set the HTTP Response Type */
                /* Send a big chart back to the browser */
                ChartUtilities.writeChartAsPNG(out, mychart, 640, 480);/* Write the data to the output stream */
        }
        catch (Exception e) {
                System.err.println(e.toString()); /* Throw exceptions to log files */
        }
        finally {
                out.close();/* Close the output stream */
        }
        }
/* We write a doPost method which will be invoked when you post data to the servlet */
/* Inside doPost we invoke doGet to return a chart back to us depending on the input parameters*/
public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
      throws ServletException, IOException {
    doGet(request, response);
  }     
}
You will have to compile and deploy this new servlet. You can refer to the JFreeChart Servlet Tutorial to know how to do this, if you are using Tomcat server. After you deploy the new version of servlet code, when you send values from this form, each time you will get a different chart displayed on the browser..Wow! we have created dynamic charts using JFreeChart Servlets. A sample chart produced for some random inputs is provided below;
JFreeChart Dynamic Pie Chart Using HTTP Servlets
JFreeChart Dynamic Pie Chart Using HTTP Servlets

1 comment:

  1. Thankuuuuuu !!! soo much was very useful for showing my results for my college project this is awesome blog clearly dealt with what to do with necessary generation of the graph.worked well without any errors keep on blogging like these new things to help the new jfreechart developers

    ReplyDelete