Use JFreechart to generate various charts in JSP

  A Java novice encountered a problem when writing a web page, that is, to take out the content of a table in the database and generate a bar chart or a line chart, which suddenly became confusing, and I don't know how to complete it, but I stopped and thought about it. Thought, first of all, I should know the ways to generate charts. I found the experience summarized by the great God through the Internet as follows (original):

https://blog.csdn.net/happylee6688/article/details/26960729

  • ChartDirector
  ChartDirector is a commercial charting library, available in multiple languages, supported versions include .NET, ASP/COM/VB, JSP/Java, CodeFusion, PHP, Perl, Ruby, C++, etc. ChartDirector charting tool is especially suitable for web and embedded application development. The charts made with it are very fine and beautiful. Although they are business charts, they are not expensive. Of course, if you don’t want to spend money to buy them, it also provides a free version, but the logo information will appear on the generated charts. However, there are still a lot of cracking methods on the Internet, which are very simple.
  ChartDirector plug-in is easy to use, fast, flexible, powerful and interactive. It is an ideal tool for web server and embedded application development, with a rich library of chart graphics components. Support a variety of chart styles, such as circle chart (pie chart), doughnut chart, column chart (bar chart), line chart, curve chart, trapezoidal line chart, trend line chart, curve fitting chart, line-to-line chart Color maps, area maps, foam maps and more. Using multi-threading structure, it is especially used in server-side application development with high performance requirements. It has API (application programming interface)-based objects, allowing users to control and customize chart details, so as to design user-satisfied charts.
  ChartDirector's support for Chinese is also very good, the problems that arise are easy to solve, and there are solutions on the Internet. In addition, in the source code provided by ChartDirector, the demo of jsp is relatively simple, you only need to change the data, and you can immediately show the effect you want. It also has English documents, and the source code description is provided in the document, which is very convenient for developers. Personally, I still like this plugin very much, with a wide variety of graphics, beautiful styles, and easy to use.
  • JScharts 
  JScharts is a JavaScript toolkit for drawing charts directly on the browser. Supports bar charts, pie charts and simple curve charts. Insert this library directly into a web page, then call the data from an XML file or JavaScript array variable.
The feature of JSCharts is that it does not require any server-side plug-ins and modules, it is a pure JavaScript component, it is a commercial software, but provides a free version (with watermark). To remove the watermark, a domain key is required. Under normal circumstances, JScharts does not support Chinese, but find a solution on the Internet, you can try it, click here  .
  • JFreeChart
  JFreeChart is an open source Java project, which is mainly used to develop a variety of charts, including pie charts, bar charts (normal column charts and stacked column charts), line charts, area charts, distribution charts, mixed charts Charts, Gantt charts, some dashboards, and more. The requirements of current business systems can be met on these different styles of charts.
  JFreeChart is a chart development technology based on Java language, which can be used in Servlet, JSP, Applet, Java Application environment, any database data can be dynamically displayed through JDBC, and can be output to PDF file in combination with ltext. The graph drawn by JFreeChart is not fine enough and looks a bit blurry, and the borders of text, color and color of the chart are also blurred. JFreeChart's support for Chinese is not very good, although there are font solutions, there are still problems. The default font it uses will display blurry Chinese, you may need to modify the source code.
 
  Comparing these three Java chart plug-ins, ChartDirector provides the most graphic styles and the most beautiful. After all, it is a commercial software, and it has some advantages over the other two. Although the free version of the chart will have logo information, there is a solution for this online that removes the logo. For developers, ChartDirector provides a lot of Demos and documents, enough for developers to learn and use.
  JScharts also provides some commonly used graphic styles, including column charts, pie charts, and more. And the styles it offers are pretty good too. Although JScharts does not require any server-side plug-ins and modules, it has certain requirements for JavaScript on the web front end, and developers who do not understand JavaScript cannot use it. Of course, developing charts with JScharts is fairly straightforward if you know JavaScript.
  JFreeChart also provides some commonly used graphic styles, but it only supports the java language, which is very simple in terms of ease of use. It's still possible in terms of style. Although the documentation of JFreeChart is charged, fortunately, there are still many people using JFreeChart in China, and many related tutorials can be found on the Internet. The disadvantage of JFreeChart is that it is only suitable for generating pictures, and the text and pictures are not particularly clear, and some adjustments are needed. ////////
  Because it is a java development web, I decided to learn JFreeChart, steps:
One: Jfreechart download, download address: http://sourceforge.net/projects/jfreechart/files/  Download jfreechart-1.0.19.zip, after decompression, find jfreechart.jar and jcommon.jar from the lib file Copy (I don't know what else to do) and paste it into WEB-INF\lib
Two: write code

<%@ page pageEncoding="UTF-8"
contentType="text/html; charset=UTF-8"%>
<%@ page import="java.awt.Color,
org.jfree.chart.ChartFactory,
org.jfree.chart.JFreeChart,
org.jfree.chart.plot.PlotOrientation,
org.jfree.chart.servlet.ServletUtilities,
org.jfree.data.category.CategoryDataset,
org.jfree.data.general.*,
org.jfree.chart.plot.CategoryPlot,
org.jfree.chart.axis.CategoryAxis,
org.jfree.chart.axis.ValueAxis,
org.jfree.chart.renderer.category.BarRenderer3D,
org.jfree.chart.urls.StandardCategoryURLGenerator,
org.jfree.chart.*,
org.jfree.chart.entity.*,
org.jfree.chart.labels.*,
org.jfree.chart.axis.CategoryLabelPositions,
java.awt.Font,
java.awt.GradientPaint,
org.jfree.ui.TextAnchor,
org.jfree.chart.axis.NumberAxis,
org.jfree.chart.axis.NumberTickUnit
"%>
<%@ page import="org.jfree.data.general.DefaultPieDataset"%>
<%@ page import="org.jfree.data.category.CategoryDataset" %>
<%@ page import="org.jfree.data.category.DefaultCategoryDataset" %>
<%@ page import="org.jfree.chart.JFreeChart"%>
<%@ page import="org.jfree.chart.plot.PiePlot"%>
<%@ page import="org.jfree.chart.ChartRenderingInfo"%>
<%@ page import="org.jfree.chart.servlet.ServletUtilities"%>
<%@ page import="org.jfree.chart.urls.StandardPieURLGenerator"%>
<%@ page import="org.jfree.chart.entity.StandardEntityCollection"%>
<%@ page import="org.jfree.chart.encoders.SunPNGEncoderAdapter"%>
<%@ page import="org.jfree.chart.StandardChartTheme"%>
<%@ page import="org.jfree.chart.ChartFactory"%>
<%@ page import="org.jfree.chart.plot.CategoryPlot"%>
<%@ page import="org.jfree.chart.plot.PlotOrientation"%>
<%@ page import="org.jfree.chart.axis.CategoryAxis"%>
<%@ page import="org.jfree.chart.renderer.category.BarRenderer"%>
<%@ page import="org.jfree.chart.labels.StandardCategoryItemLabelGenerator"%>
<%@ page import="java.awt.Font"%>
<%@ page import="java.awt.Color"%>
<%@ page import="java.sql.*"%>
<%@ page import="java.util.*"%>
<%@ page import="java.awt.*"%>
<%@ page import="java.io.*"%>
<%@ page import="org.jfree.chart.axis.CategoryAxis3D"%>
<%@ page import="org.jfree.chart.axis.CategoryLabelPositions"%>
<%@ page import="org.jfree.chart.axis.CategoryAxis3D"%>
<%@ page import="org.jfree.chart.axis.NumberAxis3D"%>
<%@ page import="org.jfree.chart.axis.NumberTickUnit"%>
<%@ page import="org.jfree.chart.renderer.category.BarRenderer3D"%>
<%@ page import="org.jfree.chart.renderer.category.BarRenderer3D" %>
<%@ page import="org.jfree.chart.renderer.category.LineAndShapeRenderer" %>
<%@ page import="org.jfree.data.category.DefaultCategoryDataset" %>
<%@ page import="org.jfree.chart.plot.DatasetRenderingOrder" %>

//PS: A novice should import classes as much as possible to prevent mistakes...

//The pie chart code is as follows:

<html>
<body>
<%
//Instantiate the core class object
DefaultPieDataset dataset=new DefaultPieDataset();
//Set the chart value, it can be multiple
dataset.setValue("paid",45);
dataset.setValue("Unpaid ",25);
//Create a pie chart based on the factory class org.jfree.chart.ChartFactory provided by
JFreeChart JFreeChart chart=ChartFactory.createPieChart3D("Student payment form",dataset,true,false,false);

//Generate the graph and save it into the session, get the name of the graph saved in the session

String filename=ServletUtilities.saveChartAsPNG(chart,500,400,session);

//Display the generated graph through img on the page, and output the graph through jfreechart's servlet
String graphURL=request.getContextPath()+"/DisplayChart?filename="+filename;
%>
<img src="<%=graphURL %> " >
</body>
</html>

 

The above method of outputting the chart is to use the serverlet of JFreeChart for output, so the web.xml file should be configured as follows: (If the chart is not displayed, most of the web.xml is not configured)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ceshi</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>

<servlet>
<servlet-name>DisplayChart</servlet-name>
<servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>DisplayChart</servlet-name>
<url-pattern>/DisplayChart</url-pattern>
</servlet-mapping>
</web-app>

 

In fact, there are two ways to output the chart, the other is through a function output: (for example, the histogram)

//The first step, construct a Dataset: fill in the data to be counted
DefaultCategoryDataset mDataset = new DefaultCategoryDataset();
mDataset.addValue(2000, "Tsinghua University", "Undergraduate"); //The data is generally obtained from the database, using mDataset.addValue
(1500, "Tsinghua University", "Graduate student");
mDataset.addValue(1000, "Tsinghua University", "PhD student");
mDataset.addValue(900, "Tsinghua University", " Lecturer");
mDataset.addValue(800, "Tsinghua University", "Associate Professor");
mDataset.addValue(300, "Tsinghua University", "Professor");
mDataset.addValue(600, "Tsinghua University", "Administrative Staff" ");
mDataset.addValue(400, "Tsinghua University", "Managers");
//The second step, generate graphics, ChartFactory.createBarChart3D to generate a bar chart
JFreeChart mChart = ChartFactory.createBarChart3D(
"School personnel distribution map",// graphic name
"type", // category name, the abscissa name
"quantity", // value name, the ordinate name
mDataset, // data set
PlotOrientation.VERTICAL, // vertical display
true, // whether to display legend
true, // whether to use tooltip
false);// whether to use url

// third, display, there are two methods: streaming output and URL (above Already said) output
response.setContentType("image/png");
//Streaming output
ChartUtilities.writeChartAsPNG(response.getOutputStream(),mChart,800,500);

//////////////////////////////////////////////////////

It stands to reason that the core output of the chart has been learned, but from the above, we know that JFreeChart does not support Chinese, and there will be garbled characters. If the parameters in the chart are in English, the above code is enough to deal with

If you want to output Chinese without displaying garbled characters, you must configure it yourself, as follows:

// Configure font
Font xfont = new Font("宋体", Font.PLAIN, 12);// X-axis
Font yfont = new Font("宋体", Font.PLAIN, 12);// Y-axis
Font kfont = new Font("Arial", Font.PLAIN, 12);// Bottom
Font titleFont = new Font("Arial", Font.BOLD, 25); // Picture title
//Graphic drawing structure object, not applicable to pie chart
CategoryPlot plot = mChart.getCategoryPlot();

// X-axis
CategoryAxis domainAxis = plot.getDomainAxis(); domainAxis.setLabelFont
(xfont);// Axis title
domainAxis.setTickLabelFont(xfont);// Axis value
domainAxis.setTickLabelPaint(Color. BLACK); // font color

// Y-axis
ValueAxis rangeAxis = plot.getRangeAxis();
rangeAxis.setLabelFont(yfont);
rangeAxis.setLabelPaint(Color.BLACK); // font color
rangeAxis.setTickLabelFont(yfont);

This solves the garbled code. The above code is suitable for bar charts and font settings. The code for setting fonts 
for line charts and pie charts is not the same. It is necessary to set fonts for different types of graphics separately, but they are very similar.

 

Some of the ideas above are enough for the general needs of users, but sometimes you want to output some comprehensive charts, such as histograms and line charts, or even histograms and many line charts.

There are also many examples on the Internet, and you can also learn line charts along with the above ideas.

Comprehensive reference link:

http://blog.sina.com.cn/s/blog_906e353d0101241e.html

https://blog.csdn.net/sb_jb/article/details/77867614?fps=1&locationNum=2

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324782815&siteId=291194637