注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

Search的博客

不断学习中!

 
 
 

日志

 
 

JFreeChart与Servlet的结合使用  

2012-12-24 23:04:56|  分类: 默认分类 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
package code.lxy.Util;

import java.util.Map;

public class Data {
    private String pageName;
    private  Map<String, Double> browserPageSum;
    public String getPageName() {
        return pageName;
    }
    public void setPageName(String pageName) {
        this.pageName = pageName;
    }
    public Map<String, Double> getBrowserPageSum() {
        return browserPageSum;
    }
    public void setBrowserPageSum(Map<String, Double> browserPageSum) {
        this.browserPageSum = browserPageSum;
    }
    
}

package code.lxy.Util;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
public class SqlOperation {
    private Connection conn;
    private Statement sta;
    private PreparedStatement pres;
    private ResultSet result;
    public SqlOperation() throws ClassNotFoundException, SQLException
    {
        Class.forName("com.mysql.jdbc.Driver");
        conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/browserdata", "root", "wojiushiwo");
    }
    public Map<String,Double> getBrowserData(String pageName)
    {
        Map<String, Double> map=new HashMap<String, Double>();
        String sql="select date,browserData from browser where pageName=?";
        try {
            pres=conn.prepareStatement(sql);
            pres.setString(1, pageName);
            result=pres.executeQuery();
            while(result.next())
            {
                map.put(result.getString("date"), (double) result.getShort("browserData"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return map;
    }
}

package code.lxy.Util;

import java.awt.Color;
import java.awt.Font;
import java.awt.GradientPaint;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.time.Month;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.ui.RectangleInsets;
import org.jfree.ui.TextAnchor;

/**
 * @description 使用JFreeChart组建,生成一个价格随日期的走势图表
 *
 */
public class TimeSeriesChartUtil {
   
    private String type;//month,year
    private int width ;//后台计算
    private int height;//后台计算
    private String title;//图表的主标题
    private String subTitle;//图表的子标题
    private String xName;//可默认值:月份
    private String yName;//可默认值:价格指数
   
    /***
     * constructor function
     * @param type
     * @param title
     * @param subTitle
     * @param xName
     * @param yName
     */
    public TimeSeriesChartUtil(String type,String title,String subTitle,String xName,String yName){
        this.type = type;
        this.title = title;
        this.subTitle = subTitle;
        this.xName = xName;
        this.yName = yName;
        if("month".equals(type)){
            this.width = 800;
            this.height = 600;
        }else if("year".equals(type)){
            this.width = 600;
            this.height = 400;
        }
    }
   
    /** 根据TimeSeriesCollection创建JFreeChart对象*/  
    public JFreeChart createChart(TimeSeriesCollection dataset) {  
       
        JFreeChart chart = ChartFactory.createTimeSeriesChart(this.title, this.xName,this.yName, dataset, true, true, true);
       
        XYPlot plot = (XYPlot) chart.getPlot();
        XYLineAndShapeRenderer xylineandshaperenderer = (XYLineAndShapeRenderer)plot.getRenderer();
        //设置网格背景颜色
        plot.setBackgroundPaint(Color.white);
        //设置网格竖线颜色
        plot.setDomainGridlinePaint(Color.pink);
        //设置网格横线颜色
        plot.setRangeGridlinePaint(Color.pink);
        //设置曲线图与xy轴的距离
        plot.setAxisOffset(new RectangleInsets(0D, 0D, 0D, 10D));
        //设置曲线是否显示数据点
        xylineandshaperenderer.setBaseShapesVisible(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);
       
        //设置子标题
        TextTitle subtitle = new TextTitle(this.subTitle, new Font("黑体", Font.BOLD, 12));
        chart.addSubtitle(subtitle);
        //设置主标题
        chart.setTitle(new TextTitle(this.title, new Font("隶书", Font.ITALIC, 15)));
        //设置背景颜色
        chart.setBackgroundPaint(new GradientPaint(0, 0, Color.white, 0, 1000,Color.blue));
        chart.setAntiAlias(true);
 
        return chart;  
    }  
    /**创建TimeSeriesCollection对象  */
    public TimeSeriesCollection createDataset(List<Data> datalist){
       
        //时间曲线数据集合
        TimeSeriesCollection lineDataset = new TimeSeriesCollection();
        for(int i=0;i<datalist.size();i++){
            Data data = datalist.get(i);
            TimeSeries series = new TimeSeries(data.getPageName(),Month.class);
            Map<String,Double> pimap = data.getBrowserPageSum();
            Set piset = pimap.entrySet();  
            Iterator piIterator = piset.iterator();  
            while(piIterator.hasNext()){  
                Map.Entry<String,Double> hiddenMapEntry = (Map.Entry<String,Double>)piIterator.next(); 
                String key = hiddenMapEntry.getKey();  
                int year = Integer.parseInt(key.substring(0,4));
                int month = Integer.parseInt(key.substring(4, 6));
                series.add(new Month(month,year),hiddenMapEntry.getValue());
            } 
            lineDataset.addSeries(series);
        }
        return lineDataset;
    }
       /*
        * 显示在网页
        */
    public void displayInJsp(HttpServletResponse response,JFreeChart chart)
    {
        try {
            ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, width, height);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**保存为文件*/  
    public void saveAsFile(JFreeChart chart, String outputPath) {  
        FileOutputStream out = null;  
        try {  
            File outFile = new File(outputPath);  
            if (!outFile.getParentFile().exists()) {  
                outFile.getParentFile().mkdirs();  
            }  
            out = new FileOutputStream(outputPath);  
            // 保存为PNG  
            ChartUtilities.writeChartAsPNG(out, chart, width, height);  
            // 保存为JPEG  
            // ChartUtilities.writeChartAsJPEG(out, chart, width, height);  
            out.flush();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (out != null) {  
                try {  
                    out.close();  
                } catch (IOException e) {  
                    // do nothing  
                }  
            }  
        }  
    }  
 
    public int getWidth() {
        return width;
    }

    public void setWidth(int width) {
        this.width = width;
    }

    public int getHeight() {
        return height;
    }

    public void setHeight(int height) {
        this.height = height;
    }  
   
    public String getXName() {
        return xName;
    }

    public void setXName(String name) {
        xName = name;
    }

    public String getYName() {
        return yName;
    }

    public void setYName(String name) {
        yName = name;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }


    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getSubTitle() {
        return subTitle;
    }

    public void setSubTitle(String subTitle) {
        this.subTitle = subTitle;
    }

}

package code.lxy.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jfree.chart.JFreeChart;
import org.jfree.data.time.TimeSeriesCollection;

import code.lxy.Util.Data;
import code.lxy.Util.SqlOperation;
import code.lxy.Util.TimeSeriesChartUtil;

/**
 * Servlet implementation class DisplayFreeChart
 */
@WebServlet("/DisplayFreeChart")
public class DisplayFreeChart extends HttpServlet {
    private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DisplayFreeChart() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        TimeSeriesChartUtil util = new TimeSeriesChartUtil("year", "网络流量访问数据", "2012年上半年访问量走势图", "网页", "访问量"); 
        SqlOperation sql=null;
        try {
            sql = new SqlOperation();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        Map<String, Double> map=sql.getBrowserData("index.jsp");
        Map<String, Double> map1=sql.getBrowserData("service.jsp");
        List<Data> datalist=new ArrayList<Data>();
        Data data1=new Data();
        data1.setPageName("index.jsp");
        data1.setBrowserPageSum(map);
        Data data2=new Data();
        data2.setPageName("service.jsp");
        data2.setBrowserPageSum(map1);

        datalist.add(data1);
        datalist.add(data2);
        TimeSeriesCollection datalist2=util.createDataset(datalist);
        JFreeChart freeChart=util.createChart(datalist2);
        util.displayInJsp(response, freeChart);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}
  评论这张
 
阅读(309)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017