First, I will create a pie chart method independently written as a Piechar.java class, the detailed code is as follows: (the database needs to build itself, if necessary)
1 Importjava.io.IOException;2 Importjava.sql.SQLException;3 Importorg.jfree.chart.ChartFactory;4 ImportOrg.jfree.chart.JFreeChart;5 ImportOrg.jfree.data.general.DefaultPieDataset;6 7 Public classPiechart {8 PublicJfreechart chart=NULL;9 PublicPiechart ()throwsIOException, sqlexception{TenDefaultpiedataset data =GetDataSet (); OneChart = Chartfactory.createpiechart3d ("pie chart of various commodity quantities", data,true,false,false);//Draw a pie chart A } - //custom methods to generate a pie chart dataset - Private StaticDefaultpiedataset GetDataSet ()throwssqlexception{ theDefaultpiedataset Dabaset =NewDefaultpiedataset (); -Conndb conn =Newconndb (); -String sql = "Select P_type,count (P_type) as P_type_count from Product GROUP by (P_type)"; -Conn.rs =conn.doquery (SQL); + //reading database data, generating datasets - while(Conn.rs.next ()) { +Dabaset.setvalue (conn.rs.getString ("P_type"), Conn.rs.getInt ("P_type_count")); A } at returnDabaset; - } -}
Then call this Java class in the JSP file, with the detailed code as follows:
1<jsp:usebean id= "Pies"class= "Bean. Piechart "></jsp:useBean>2<body>3 4<%5String filename = servletutilities.savechartaspng (pies.chart,500, 300,NULL, session);//Generate picture Path6String Graphurl = Request.getcontextpath () + "/servlet/displaychart?filename=" + filename;//The full path of the resulting picture in the project7 System.out.println (graphurl);8%>9<div align= "center" >Ten One</div> A</body>
This is not enough to finish, also need to do in the Web. xml file configuration in order to display the picture, detailed configuration as follows:
1 <servlet>2 <Servlet-name>Displaychart</Servlet-name>3 <Servlet-class>Org.jfree.chart.servlet.DisplayChart</Servlet-class>4 </servlet>5 <servlet-mapping>6 <Servlet-name>Displaychart</Servlet-name>7 <Url-pattern>/servlet/displaychart</Url-pattern>8 </servlet-mapping>
Complete the servlet mapping.
The final effect is as follows:
Reads the database data and consolidates the data into a pie chart displayed in the JSP