Today you are going to know how to create dynamic chart from an jsp page.
First create the database and tables like below if you are using mysql otherwise use your own database you need to change only connection drivers only
mysql>create database s2sgateway;
mysql>use s2sgateway;
mysql> create table chart(name varchar(20),LeavePercentage integer);
insert into chart values('amar',10),('jani',20);
insert into chart values('safiq',10),('s2s',20);
Now write the below code in the jsp page after executing the code chart is saved in the location given by you for the saveChartAsJPEG location
ChartUtilities.saveChartAsJPEG(new File("c:\\s2s worksspace\\s2sgateway\\WebContent\\chart.jpg"), chart, 500, 450);
then use img src to define the exact location to show the chart in jsp page copy the code below
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="org.jfree.chart.ChartFactory" %>
<%@ page import="org.jfree.chart.ChartUtilities"%>
<%@ page import="org.jfree.chart.JFreeChart" %>
<%@ page import="org.jfree.chart.plot.PlotOrientation"%>
<%@ page import="org.jfree.data.*" %>
<%@ page import="org.jfree.data.jdbc.JDBCCategoryDataset"%>
<%@ page import="org.jfree.chart.renderer.category.CategoryItemRenderer"%>
<%@ page import="org.jfree.chart.plot.CategoryPlot"%>
<%@ page import="org.jfree.chart.plot.PlotOrientation"%>
<%@ page import="java.awt.Color"%>
<%
String query="SELECT * from chart";
JDBCCategoryDataset dataset=new JDBCCategoryDataset("jdbc:mysql://localhost:3306/s2sgateway",
"com.mysql.jdbc.Driver","root","root");
dataset.executeQuery( query);
JFreeChart chart = ChartFactory .createBarChart3D(
"Chart Creation",
"Student Names",
"Days Present",
dataset,
PlotOrientation.VERTICAL,true, true, false);
CategoryPlot plot = chart.getCategoryPlot();
CategoryItemRenderer renderer = plot.getRenderer();
renderer.setSeriesPaint(0, Color.green);
try
{
ChartUtilities.saveChartAsJPEG(new File("c:\\s2s worksspace\\s2sgateway\\WebContent\\chart.jpg"), chart, 500, 450);
}
catch (IOException e)
{
System.out.println("Problem in creating chart.");
}
%>
<img src="c:\\s2s worksspace\\s2sgateway\\WebContent\\chart.jpg" width=500 height=450>
You can change your own color at
renderer.setSeriesPaint(0, Color.green); and change the
database table and values to your own Any doubt ask us.
Happy Coding