struts2+JfreeChart实现饼状图,柱状图,线形图

1.基本原理:Jfreechart类生成图片(在tomcat-->temp目录下),再在页面中用<img src="路径"/>输出

2.导入jar包

commons-logging-1.0.4.jar,freemarker-2.3.8.jar,ognl-2.6.11.jar,struts2-core-2.0.12.jar,xwork-2.0.6.jar

jcommon-1.0.16.jar,jfreechart-1.0.13.jar

3.定义web.xml

<filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
   
   
    <servlet>
     <servlet-name>display</servlet-name>
     <servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
     
    </servlet>
    <servlet-mapping>
     <servlet-name>display</servlet-name>
     <url-pattern>/servlet/displaychart</url-pattern>
    </servlet-mapping>
   
    <!-- 指定Session过期后,自动删除tomcat目录下的temp文件夹内的图片 -->
    <listener>
     <listener-class>org.jfree.chart.servlet.ChartDeleter</listener-class>
     
    </listener>

4.定义JFreechartFactory类,用来生成饼状,柱状,线性JreeChart对象

package com.jfreechart;

import java.awt.Color;
import java.awt.Font;

import org.jfree.chart.*;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.title.LegendTitle;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleInsets;
import org.jfree.ui.TextAnchor;
import org.jfree.util.Rotation;

import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.renderer.category.BarRenderer3D;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.labels.*;
import org.jfree.chart.plot.*;
import org.jfree.data.time.*;

public class JFreeChartFactory {

 
 public static JFreeChart CreateBarChart()
 {
  // 生成普通饼图
   JFreeChart chart = ChartFactory.createBarChart3D
("", "肉类", "销量",
     getBarDateSet(),
     PlotOrientation.VERTICAL, true, false, false);
   // 重新设置图表标题,改变字体
   chart.setTitle(new TextTitle("肉量销售图"
    , new Font("黑体", Font.ITALIC , 22)));
   // 取得统计图表的第一个图例
   LegendTitle legend = chart.getLegend(0);
   // 修改图例的字体(解决乱码)
   legend.setItemFont(new Font("宋体", Font.BOLD, 14));
   // 获得饼图的 Plot 对象
   CategoryPlot plot = chart.getCategoryPlot();
  
   ValueAxis valueAxis=plot.getRangeAxis();
  
   valueAxis.setLabelFont(new Font("楷体", Font.BOLD, 14));//设置y轴的标题(解决乱码问题)
   valueAxis.setTickLabelFont(new Font("楷体", Font.BOLD, 14));//设置y轴上的文字(解决乱码问题)
  
   //valueAxis.setAutoRange(true);
   //valueAxis.setFixedAutoRange(50);
   valueAxis.setAutoRangeMinimumSize(50);
   valueAxis.setLowerBound(0);
   valueAxis.setUpperBound(700);
  
   plot.getDomainAxis().setLabelFont(new Font("楷体", Font.BOLD, 14));//设置x轴的标题(解决乱码问题)
   plot.getDomainAxis().setTickLabelFont(new Font("楷体", Font.BOLD, 14));//设置x轴上的文字(解决乱码问题)
  
   //设置背景色
   plot.setBackgroundPaint(Color.white);
  
   //设置y轴的线条颜色
   plot.setDomainGridlinePaint(Color.PINK);
  //设置x轴的线条颜色
   plot.setRangeGridlinePaint(Color.PINK);
  
  
   BarRenderer3D renderer=new BarRenderer3D();
   renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
   renderer.setBaseItemLabelsVisible(true);
  
   //注意:此句很关键,若无此句,那数字的显示会被覆盖,给人数字没有显示出来的问题
   renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,TextAnchor.BASELINE_LEFT));
   renderer.setItemLabelAnchorOffset(10D);
  
   plot.setRenderer(renderer);
  
   //将下方的“肉类”放到上方
  // plot.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);
   //将默认放在左边的“销量”放到右方
   plot.setRangeAxisLocation(AxisLocation.BOTTOM_OR_RIGHT);
  
  
   // 设定背景透明度(0-1.0 之间)
   plot.setBackgroundAlpha(0.9f);
  
   return chart;
 }
 
 private static CategoryDataset getBarDateSet()
 {
  double da[][]=new double[][]{{200,340,400},
    {300,640,200},
    {400,340,100}};
  String row[]={"猪肉","狗肉","羊肉"};
  String colu[]={"广州","深圳","上海"};
  
  return DatasetUtilities.createCategoryDataset(row, colu, da);
  
 }
 
 public static JFreeChart CreateLineChart()
 {
  
  
  JFreeChart chart = ChartFactory.createTimeSeriesChart("访问量统计时间线","月份",
    "访问量",getLineDateSet(),true,true,true);
  
  
  
  
  
  //设置子标题
  TextTitle subtitle=new TextTitle("2007年度",new Font("黑体",Font.BOLD,12));
  chart.addSubtitle(subtitle);
  //设置主标题
  chart.setTitle(new TextTitle("阿蜜果blog访问量统计",new Font("隶书",Font.ITALIC,15)));
  
  
  // 取得统计图表的第一个图例
   LegendTitle legend = chart.getLegend(0);
   // 修改图例的字体(解决乱码)
   legend.setItemFont(new Font("宋体", Font.BOLD, 14));
  
   XYPlot plot = chart.getXYPlot();
  
   ValueAxis valueAxis=plot.getRangeAxis();
  
   valueAxis.setLabelFont(new Font("楷体", Font.BOLD, 14));//设置y轴的标题(解决乱码问题)
   valueAxis.setTickLabelFont(new Font("楷体", Font.BOLD, 14));//设置y轴上的文字(解决乱码问题)
  
   plot.getDomainAxis().setLabelFont(new Font("楷体", Font.BOLD, 14));//设置x轴的标题(解决乱码问题)
   plot.getDomainAxis().setTickLabelFont(new Font("楷体", Font.BOLD, 14));//设置x轴上的文字(解决乱码问题)
  
  
  
  //设置网格背景颜色
   plot.setBackgroundPaint(Color.white);
   //设置网格竖线颜色
   plot.setDomainGridlinePaint(Color.BLUE);
   //设置网格横线颜色
   plot.setRangeGridlinePaint(Color.pink);
   //设置曲线图与xy轴的距离
   plot.setAxisOffset(new RectangleInsets(0D, 0D, 0D, 10D));
  
  // XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer)plot.getRenderer();
   //xylineandshaperenderer.setBaseItemLabelsVisible(true);
  
  //设置曲线显示各数据点的值
   XYItemRenderer xyitem = plot.getRenderer();  
   xyitem.setBaseItemLabelsVisible(true); 
    xyitem.setBasePositiveItemLabelPosition(
     new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12,
       TextAnchor.BASELINE_LEFT));
   xyitem.setBaseItemLabelGenerator(new
     StandardXYItemLabelGenerator());
   xyitem.setBaseItemLabelFont(new Font("Dialog", 1, 14));
   plot.setRenderer(xyitem);
  
  chart.setAntiAlias(true);
  return chart;
 }
 
 private static TimeSeriesCollection getLineDateSet()
 {
  //访问量统计时间线
  TimeSeries timeSeries1=new TimeSeries("2010",Month.class);
  TimeSeries timeSeries2=new TimeSeries("2011",Month.class);
  //时间曲线数据集合
  TimeSeriesCollection lineDataset=new TimeSeriesCollection();
  //构造数据集合
  timeSeries1.add(new Month(1,2011), 11200);
  timeSeries1.add(new Month(2, 2011), 9000);
  timeSeries1.add(new Month(3, 2011), 6200);
  timeSeries1.add(new Month(4, 2011), 8200);
  timeSeries1.add(new Month(5, 2011), 8200);
  timeSeries1.add(new Month(6, 2011), 12200);
  timeSeries1.add(new Month(7, 2011), 13200);
  
  timeSeries2.add(new Month(1,2011), 1120);
  timeSeries2.add(new Month(2, 2011), 800);
  timeSeries2.add(new Month(3, 2011), 3200);
  timeSeries2.add(new Month(4, 2011), 2200);
  timeSeries2.add(new Month(5, 2011), 1200);
  timeSeries2.add(new Month(6, 2011), 62200);
  timeSeries2.add(new Month(7, 2011), 3200);
  
  lineDataset.addSeries(timeSeries1);
  lineDataset.addSeries(timeSeries2);
  return lineDataset;
 }
 
 
 public static JFreeChart CreatePieChart()
 {
  // 生成普通饼图
   JFreeChart chart = ChartFactory.createPieChart3D(
   "",  // 图表标题
   getPieDataSet(), // 数据
    true, // 是否显示图例
    true, // 是否显示工具提示
    false // 是否生成 URL
   );
   // 重新设置图表标题,改变字体
   chart.setTitle(new TextTitle("图书销量统计图"
    , new Font("黑体", Font.ITALIC , 14)));
   // 取得统计图表的第一个图例
   LegendTitle legend = chart.getLegend(0);
   // 修改图例的字体
   legend.setItemFont(new Font("宋体", Font.BOLD, 12));
   // 获得饼图的 Plot 对象
   PiePlot plot = (PiePlot)chart.getPlot();
   // 设置饼图各部分的标签字体
   plot.setLabelFont(new Font("楷体", Font.BOLD, 12));
  
  
  
  
  //设置开始角度
   plot.setStartAngle(150D);
   //设置方向为”顺时针方向“
   plot.setDirection(Rotation.CLOCKWISE);
   //设置透明度,0.5F为半透明,1为不透明,0为全透明
   plot.setForegroundAlpha(0.5F);
  
   // 设定背景透明度(0-1.0 之间)
   plot.setBackgroundAlpha(0.9f);
  
   return chart;
 }
 
 private static  DefaultPieDataset getPieDataSet()
  {
   // 提供生成饼图的数据
   DefaultPieDataset dataset = new DefaultPieDataset();
   dataset.setValue("疯狂 Java 讲义",47000);
   dataset.setValue("轻量级 Java EE 企业实战",38000);
   dataset.setValue("疯狂 Ajax 讲义",31000);
   dataset.setValue("Struts 2 权威指南",29000);
   dataset.setValue("疯狂 XML 讲义",25000);
   return dataset;
  }
 
}

5.定义Action类(定义3个属性,分别用来存储饼状,柱状,线性图片的输出路径)

package com.test.action;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import com.opensymphony.xwork2.ActionSupport;

import com.jfreechart.*;

import org.apache.struts2.ServletActionContext;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.servlet.DisplayChart;

public class LoginAction extends ActionSupport {

 /**
  *
  */
 
 private String username;
 private String pwd;
 
 private String barchart;
 private String linechart;
 private String piechart;
 public String getUsername() {
  return username;
 }
 public void setUsername(String username) {
  this.username = username;
 }
 public String getPwd() {
  return pwd;
 }
 public void setPwd(String pwd) {
  this.pwd = pwd;
 }
 
 public String ForwardLogin()
 {
  return "input";
 }
 
 public String execute() throws Exception
 {
  CreatePie();
  CreateLine();
  CreateBar();
  //System.out.println("execute");
  return "first";
 }
 
 
 


 
 
 public String getBarchart() {
  return barchart;
 }
 public void setBarchart(String barchart) {
  this.barchart = barchart;
 }
 public String getLinechart() {
  return linechart;
 }
 public void setLinechart(String linechart) {
  this.linechart = linechart;
 }
 public String getPiechart() {
  return piechart;
 }
 public void setPiechart(String piechart) {
  this.piechart = piechart;
 }
 
 /**
  * 创建饼形
  * @throws IOException
  */
 private void CreatePie() throws IOException
 {
  HttpServletRequest request=ServletActionContext.getRequest();
  
  JFreeChart chart=JFreeChartFactory.CreatePieChart();
  String st=ServletUtilities.saveChartAsJPEG(chart,500,400,request.getSession());
  
  piechart=new StringBuffer(request.getContextPath()).append("/servlet/displaychart?filename="+st).toString();
  
 }
 
 /**
  * 创建线性
  * @throws IOException
  */
 private void CreateLine() throws IOException
 {
  HttpServletRequest request=ServletActionContext.getRequest();
  
  JFreeChart chart=JFreeChartFactory.CreateLineChart();
  String st=ServletUtilities.saveChartAsJPEG(chart,500,400,request.getSession());
  
  linechart=new StringBuffer(request.getContextPath()).append("/servlet/displaychart?filename="+st).toString();
  
 }
 
 /**
  * 创建柱形
  * @throws IOException
  */
 private void CreateBar() throws IOException
 {
  HttpServletRequest request=ServletActionContext.getRequest();
  
  JFreeChart chart=JFreeChartFactory.CreateBarChart();
  String st=ServletUtilities.saveChartAsJPEG(chart,500,400,request.getSession());
  
  barchart=new StringBuffer(request.getContextPath()).append("/servlet/displaychart?filename="+st).toString();
  
 }
 
}

6.定义jsp文件,用<img>标签输出图形

 饼状<br/>
    <img src="${requestScope.piechart }">
    <br>线形
    <br>
    <img src="${requestScope.linechart }">
    <br> 柱形
    <br>
    <img src="${requestScope.barchart }">

 

发布了36 篇原创文章 · 获赞 3 · 访问量 3万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章