关键类
1创建一个动态xml文件ChartManager .java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.bcc.service;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import com.bcc.comm.RestUtil;
public class ChartManager {
public void creatLineXml(ServletOutputStream sos, HashMap dateMap,String[] xy, boolean defaultShowData) throws IOException {
defaultShowData = true;
//创建新节点
Document document = DocumentHelper.createDocument();
Element chart = document.addElement("chart");
chart.addAttribute("caption", "");//主标题
chart.addAttribute("rotateYAxisName", "0");
chart.addAttribute("xAxisName", xy[0]);//x轴标注
chart.addAttribute("yAxisName", xy[1]);//y轴标注
chart.addAttribute("yAxisMinValue", "1500");//y轴最大值
chart.addAttribute("numberPrefix", "");//y轴单位
if (defaultShowData == true) {
chart.addAttribute("showValues", "1");
} else {
chart.addAttribute("showValues", "0");
}
chart.addAttribute("alternateHGridColor", "FCB541");
chart.addAttribute("alternateHGridAlpha", "20");
chart.addAttribute("divLineColor", "FCB541");
chart.addAttribute("divLineAlpha", "50");
chart.addAttribute("canvasBorderColor", "666666");
chart.addAttribute("baseFontColor", "666666");
chart.addAttribute("lineColor", "FCB541");
chart.addAttribute("imageSave", "1");
chart.addAttribute("imageSaveURL", "FusionChartsSave.jsp");
chart.addAttribute("imageSaveDialogFontColor", "cfbbfc");
chart.addAttribute("baseFontSize", "12");
Iterator iter = dateMap.entrySet().iterator();
while(iter.hasNext()) {
Element set = chart.addElement("set");
Map.Entry entry = (Map.Entry) iter.next();
set.addAttribute("label", entry.getKey().toString());
set.addAttribute("value", entry.getValue().toString());
}
try {
RestUtil.xmlStream(document, sos);
} catch (Exception e) {
}
}
}
2 创建写入xml的类 RestUtil.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.bcc.comm;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import javax.servlet.ServletOutputStream;
import org.dom4j.Document;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
/**
*
* @author fenglei
*/
public class RestUtil {
/**
* 获得 Document By Url
* @param url
* @return
*/
public static Document getDocumentByUrlXml(String url) throws Exception {
String xmlString = "";
InputStream is = RestUtil.getInputStreamByUrlXml(url);
SAXReader saxReadr = new SAXReader();// 得到SAXReader对象
Document document = null;
try{
document = saxReadr.read(is);
java.io.StringWriter out = new java.io.StringWriter();
XMLWriter xw = new XMLWriter(out, new OutputFormat("", true, "GBK"));
xw.write(document);
xmlString = out.toString();
System.out.println("xmlString: " + xmlString);
}catch (Exception e) {
System.out.println("获取数据异常: " + e.getMessage());
throw e;
}
return document;
}
/**
* 获得URL资源
* @param url
* @return
*/
public static InputStream getInputStreamByUrlXml(String url){
URL urlXml = null;
URLConnection conn = null;
InputStream is = null;
try {
urlXml = new URL(url);
conn = urlXml.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(10000);
conn.setDoOutput(true);
conn.connect();
is = conn.getInputStream();
} catch (UnsupportedEncodingException e) {
System.out.println("UnsupportedEncodingException here");
} catch (IOException e) {
System.out.println("IOException here");
}
return is;
}
/**
* 精美打印
* @param document
* @return
*/
public static String printXml(Document document) {
// 将XML写入浄1�7
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
XMLWriter output = null;
try {
output = new XMLWriter(format);
// System.out.println(document.asXML());
output.write(document);
} catch (IOException e) {
// throw e;
} finally {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String xmlString = document.asXML();
//System.out.println(xmlString);
return xmlString;
}
public static void xmlStream(Document document, ServletOutputStream sos) throws UnsupportedEncodingException, IOException {
String xmlString = document.asXML();
//设置编码
OutputFormat format = OutputFormat.createPrettyPrint();
format.setEncoding("GBK");
XMLWriter xmlout = null;
try {
xmlout = new XMLWriter(sos,format);
xmlout.write(document);
} catch (IOException ex) {
throw ex;
} finally {
if (xmlout != null) {
try {
xmlout.close();
} catch (IOException ex) {
throw ex;
}
}
}
}
}
3 创建jsp用来保存图片FusionChartsSave.jsp
<%@ page import="java.io.OutputStream"%>
<%@ page import="java.awt.Color"%>
<%@ page import="java.awt.Graphics"%>
<%@ page import="java.awt.image.BufferedImage"%>
<%@ page import="javax.imageio.ImageIO"%>
<jsp:directive.page import="java.io.File"/>
<jsp:directive.page import="java.io.FileOutputStream"/>
<%
//Decoded data from charts.
String data="";
//Rows of color values.
String[] rows;
//Width and height of chart.
int width=0;
int height=0;
//Default background color of the chart
String bgcolor="";
Color bgColor;
//Get the width and height from form
try{
width = Integer.parseInt(request.getParameter("width"));
height = Integer.parseInt(request.getParameter("height"));
}
catch(Exception e){
//If the width and height have not been given, we cannot create the image.
out.print("Image width/height not provided.");
out.close();
}
if(width==0 || height==0){
//If the width and height are less than 1, we cannot create the image.
out.print("Image width/height not provided.");
out.close();
}
//Get background color from request and set default
bgcolor =request.getParameter("bgcolor");
if (bgcolor==null || bgcolor=="" || bgcolor==null){
bgcolor = "FFFFFF";
}
//Convert background color to color object
bgColor = new Color(Integer.parseInt(bgcolor,16));
//Get image data from request
data = request.getParameter("data");
if(data==null){
//If image data not provided.
out.print("Image Data not supplied.");
out.close();
}
try{
//Parse data
rows = new String[height+1];
rows = data.split(";");
//Bitmap to store the chart.
//Reference to graphics object - gr
BufferedImage chart = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
Graphics gr = chart.createGraphics();
gr.setColor(bgColor);
gr.fillRect(0,0,width,height);
String c;
int r;
int ri = 0;
for (int i=0; i<rows.length; i++){
//Split individual pixels.
String[] pixels = rows[i].split(",");
//Set horizontal row index to 0
ri = 0;
for (int j=0; j<pixels.length; j++){
//Now, if it's not empty, we process it
//Split the color and repeat factor
String[] clrs = pixels[j].split("_");
//Reference to color
c = clrs[0];
r = Integer.parseInt(clrs[1]);
//If color is not empty (i.e. not background pixel)
if (c!=null && c.length()>0 && c!=""){
if (c.length()<6){
//If the hexadecimal code is less than 6 characters, pad with 0
StringBuffer str = new StringBuffer(c);
int strLength = str.length();
for ( int p = c.length()+1; p <= 6 ; p ++ ) {
str.insert( 0, "0" );
}
//Assing the new padded string
c = str.toString();
}
for (int k=1; k<=r; k++){
//Draw each pixel
gr.setColor(new Color(Integer.parseInt(c,16)));
gr.fillRect(ri, i,1,1);
//Increment horizontal row count
ri++;
}
}else{
//Just increment horizontal index
ri = ri + r;
}
}
}
//Returns the image
response.setContentType("image/jpeg");
response.addHeader("Content-Disposition", "attachment; filename=/"FusionCharts.jpg/"");
OutputStream os = response.getOutputStream();
ImageIO.write(chart, "jpeg", os);
os.close();
}catch(Exception e){
//IF the image data is mal-formatted.
out.print("Image data is not in proper format.");
out.close();
}
%>
4 action里面的代码
/**
* 统计分析,生成数据,FusionCharts
*/
public void figureViewtjfx(HttpServletRequest req, HttpServletResponse res){
try {
HttpSession session = req.getSession();
List<ContentVoBean> contenList=(List)session.getAttribute("sessionVoBeantjfx");
chartManager = new ChartManager();
res.setContentType("text/xml; charset=GBK");
res.setDateHeader("Dxpires", 0);
res.setHeader("Cache-Control", "no-cache");
res.setHeader("Pragma", "no-cache");
ServletOutputStream sos = res.getOutputStream();
HashMap dataMap = new HashMap();
for(int i=0;i<contenList.size();i++){
dataMap.put(contenList.get(i).getUserNumber(), contenList.get(i).getRealityTemperature());
}
String[] xy=new String[]{"当前时间段用户平均温度","温度值"};;
chartManager.creatLineXml(sos, dataMap,xy, true);
} catch (IOException e) {
e.printStackTrace();
}
}
5 jsp页面中的代码
<div id="chartdiv3" align="center"></div>
<tr><td align="center"><input type="button" onclick="javascript:formSubmit();" value="生成报表" class="buttoncss"> <input type="button" onclick="javascript:formSubmit();" value="打印图表" class="buttoncss"></td></tr>
</table>
<script type="text/javascript">
var chart = new FusionCharts("<%=request.getContextPath()%>/style/FusionCharts/Charts/Pie2D.swf", "ChartId", "950", "380", "0", "0");
chart.setDataURL("<%=request.getContextPath()%>/contentAction?action=figureViewtjfx");
chart.render("chartdiv3");
</script>