jfreechart和servlet結合使用很簡單,只要把圖片生成了就能經過servlet顯示到畫面上去,jfreechart和struts2的結合使用其實看上去也很簡單,網上大部分方法都是用<img src="*.action">的方法來調用並顯示到畫面上的,可是這中方法只能顯示圖片的頁面,不能顯示jsp原畫面,因此這種方法並不適合經過按鈕來控制圖片的變化的jsp頁面調用jfreechart生成的圖片,爲啥經過按鈕點擊來顯示圖片到原畫面而不是隻有圖片的頁面呢?由於struts2 的返回值 <action name="tbc03Action" class="com.nec.jp.railroadX.tzz.tbc03.Tbc03Action">
<result type="chart">
<param name="width">${width}</param>
<param name="height">${height}</param>
</result>
</action>html
這種方式返回的就是一張圖片,就算你在<result type="chart"> </result>中間加一個返回到頁面上的jsp它返回的仍是一張圖片不是一個jsp頁面的圖片,如今咱們能夠經過servlet和struts2的結合來顯示這張圖片到畫面上去,可是struts2的攔截器會主動攔截servlet的請求,因此還得對struts2 的攔截作些處理,就是在result的時候先返回到頁面在經過servlet請求訪問這張圖片的地址,可是要在result的後面加一句 <interceptor-ref name="defaultStack"/>默認攔截器 ,
<action name="show" method="show" class="LoginAction">
<result>index.jsp</result>
<interceptor-ref name="defaultStack"/>
</action>java
必須在web.xml中加上servlet的配置:web
<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>DisplayChart</servlet-name>
<servlet-class>org.jfree.chart.servlet.DisplayChart</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplayChart</servlet-name>
<url-pattern>/servletDisplayChart</url-pattern>
</servlet-mapping>spring
最後是jsp:apache
添加<img src="<%=request.getContextPath() %>/servletDisplayChart?filename=<s:property value='hy_filename'/>" border="0"> 就能夠經過點按鈕來控制圖片的顯示了windows
其中java代碼:tomcat
import java.awt.Rectangle;
import java.awt.Shape;
import java.io.IOException;
import java.io.PrintWriter;session
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;app
import org.apache.struts2.ServletActionContext;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.entity.ChartEntity;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.category.DefaultCategoryDataset;dom
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
//頁面鼠標事件時須要的參數
private String hy_filename;
/**
* 顯示圖片
* @return
*/
public String show(){
HttpServletRequest req = ServletActionContext.getRequest();
HttpServletResponse res = ServletActionContext.getResponse();
hy_filename = createChartImage(req, res);
return SUCCESS;
}
private String createChartImage(HttpServletRequest req, HttpServletResponse res){
JFreeChart chart = createChart(createData());
String filename = createUseMap(chart, 510, 300, req, res);
return filename;
}
private JFreeChart createChart(DefaultCategoryDataset defaultcategorydataset){
JFreeChart chart = ChartFactory.createLineChart(null, //圖形標題名稱
null, //domain軸 Lable,橫座標Lable
null, //range 軸 Lable,縱座標Lable
defaultcategorydataset, // dataset
PlotOrientation.VERTICAL, //垂直顯示
true, // legend?
true, // tooltips?
false); //URLs?
return chart;
}
private String createUseMap(JFreeChart chart, int width, int height, HttpServletRequest req, HttpServletResponse res){
//在矩形框中顯示信息
Shape shape = new Rectangle(20, 10);
ChartEntity entity = new ChartEntity(shape);
StandardEntityCollection coll = new StandardEntityCollection();
coll.add(entity);
//該工具類上面沒有介紹,在鼠標移動到圖片時顯示提示信息是用Map實現的,這些Map是用該類生成的。
ChartRenderingInfo info = new ChartRenderingInfo(coll);
PrintWriter pw;
String filename = null;
try {
res.setContentType("text/html;charset=utf-8");
res.setCharacterEncoding("utf-8");
pw = res.getWriter();//輸出MAP信息
//寫入到輸出流生成圖像文件,同時把圖片的具體信息放入ChartRenderingInfo的一個實例爲之後生成Map提供信息
//ChartUtilities.writeChartAsPNG(out, chart, width, height, info);
filename = ServletUtilities.saveChartAsPNG(chart, width , height, info, req.getSession());//保存圖表爲文件
//讀取info對象,生成Map信息。這些信息寫在pw的輸出流中,這裏的輸出流就是Response.out,也就是直接輸出到頁面了
ChartUtilities.writeImageMap(pw, filename, info, false);
pw.flush();
} catch (IOException e) {
e.printStackTrace();
}
return filename;
}
private DefaultCategoryDataset createData(){
String series1 = "血糖";
String series2 = "舒張壓";
String series3 = "收縮壓";
String type1 = "2009-01-01";
String type2 = "2009-02-01";
String type3 = "2009-03-01";
String type4 = "2009-04-01";
String type5 = "2009-05-01";
String type6 = "2009-06-01";
String type7 = "2009-07-01";
String type8 = "2009-08-01";
DefaultCategoryDataset defaultcategorydataset = new DefaultCategoryDataset();
defaultcategorydataset.addValue(1.0D, series1, type1);
defaultcategorydataset.addValue(2D, series1, type2);
defaultcategorydataset.addValue(3D, series1, type3);
defaultcategorydataset.addValue(5D, series1, type4);
defaultcategorydataset.addValue(5D, series1, type5);
defaultcategorydataset.addValue(7D, series1, type6);
defaultcategorydataset.addValue(7D, series1, type7);
defaultcategorydataset.addValue(8D, series1, type8);
defaultcategorydataset.addValue(5D, series2, type1);
defaultcategorydataset.addValue(7D, series2, type2);
defaultcategorydataset.addValue(6D, series2, type3);
defaultcategorydataset.addValue(8D, series2, type4);
defaultcategorydataset.addValue(4D, series2, type5);
defaultcategorydataset.addValue(4D, series2, type6);
defaultcategorydataset.addValue(2D, series2, type7);
defaultcategorydataset.addValue(1.0D, series2, type8);
return defaultcategorydataset;
}
public String getHy_filename() {
return hy_filename;
}
public void setHy_filename(String hy_filename) {
this.hy_filename = hy_filename;
}
}
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="jfreeChart" extends="struts-default" >
<action name="show" method="show" class="LoginAction">
<result>index.jsp</result>
<interceptor-ref name="defaultStack"/>
</action>
</package>
</struts>
如今在加上spring的東西的話上面的方法也是無論用的,也不能顯示圖片,由於struts2和spring的攔截器會將servlet攔截掉,因此下面的方法把servlet去掉。
這個問題我糾結了好久才找到方法來解決,其實jfreechart的ServletUtilities提供了圖片的生成保存的方法saveChartAsPNG,他會臨時的保存默認保存路徑是保存在tomcat的temp文件下面,因此能夠把它的路徑改下,取到這個圖片,經過流 的方式輸出到頁面上去,就能實現點按鈕來控制圖片的顯示了。
把生成好的圖片自定義一個jsp:
img。jsp
<%@ page language="java" contentType="text/html; charset=windows-31j"
pageEncoding="windows-31j"%>
<%@ page import="java.io.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-31j">
<title>Insert title here</title>
</head>
<body>
<div style="margin-left: 0px;">
<%
response.setContentType("image/PENG");
OutputStream outt = response.getOutputStream();
String path = (String)application.getAttribute("hy_filename");
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
byte[] b = new byte[1024];
int len = -1;
while ((len = fis.read(b, 0, 1024)) != -1) {
outt.write(b, 0, len);
}
outt.flush();
outt.close();
out.clear();
out = pageContext.pushBody();
%>
</div>
</body>
</html>
而後在原來的頁面把<img src="img.jsp">調用
具體的java代碼:
package com.nec.jp.railroadX.tzz.tbc03;
import java.awt.Color;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.struts2.ServletActionContext;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.xy.XYItemRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.chart.renderer.xy.XYStepRenderer;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.data.time.Second;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import org.jfree.data.xy.XYDataset;
import com.opensymphony.xwork2.ActionSupport;
/**
* create image
* @see createDateSet
* @see getLineXYChart
*/
@SuppressWarnings("serial")
public class Tbc03Action extends ActionSupport{
private String startTime="22:00:00";
private String time="10:00:00";
private String kikann="5";
private JFreeChart chart;
private int width;
private String hy_filename;
private int height;
/**
* @return the startTime
*/
public String getStartTime() {
return startTime;
}
/**
* @param startTime the startTime to set
*/
public void setStartTime(String startTime) {
this.startTime = startTime;
}
/**
* @return the kikann
*/
public String getKikann() {
return kikann;
}
/**
* @param kikann the kikann to set
*/
public void setKikann(String kikann) {
this.kikann = kikann;
}
/**
* @return the width
*/
public int getWidth() {
return width;
}
/**
* @param width the width to set
*/
public void setWidth(int width) {
this.width = width;
}
/**
* @return the height
*/
public int getHeight() {
return height;
}
/**
* @param height the height to set
*/
public void setHeight(int height) {
this.height = height;
}
public JFreeChart getChart() {
return chart;
}
public void setChart(JFreeChart chart) {
this.chart = chart;
}
public String getTime() {
return time;
}
public void setTime(String time) {
this.time = time;
}
public String getHy_filename() {
return hy_filename;
}
public void setHy_filename(String hyFilename) {
hy_filename = hyFilename;
}
public String execute(){
if (kikann!=null) {
if (Integer.parseInt(this.getKikann()) == 5) {
width = 600;
height = 300;
try {
chart = getLineXYChart(0,this.getStartTime(),this.getKikann(),this.time);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (Integer.parseInt(this.getKikann()) > 5) {
try {
width = (int) (Float.parseFloat(this.getKikann())*60/0.5);
height = 300;
chart = getLineXYChart(1,this.getStartTime(),this.getKikann(),this.time);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (Integer.parseInt(this.getKikann()) < 5 && Integer.parseInt(this.getKikann()) > 0) {
try {
width = (int) (Float.parseFloat(this.getKikann())*60/0.5);
height = 300;
chart = getLineXYChart(2,this.getStartTime(),this.getKikann(),this.time);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
ChartRenderingInfo info = new ChartRenderingInfo(new StandardEntityCollection());
try {
hy_filename = Utilities.saveChartAsPNG(chart, width, height, info, ServletActionContext.getRequest().getSession());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ServletActionContext.getServletContext().setAttribute("hy_filename", hy_filename);
//hy_filename = hy_filename.substring(hy_filename.indexOf("/"));
// File file = new File(hy_filename);
// try {
// ChartUtilities.saveChartAsPNG(file, chart, width, height);
// } catch (IOException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
// try {
// ServletUtilities.sendTempFile(file, ServletActionContext.getResponse(),"peng");
// } catch (IOException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
// try {
// ServletUtilities.sendTempFile(file,ServletActionContext.getResponse(),"peng");
// } catch (IOException e1) {
// // TODO Auto-generated catch block
// e1.printStackTrace();
// }
// String strimg = ChartUtilities.getImageMap(hy_filename, info);
// ServletActionContext.getRequest().setAttribute("strimg", strimg);
//
// String path = ServletActionContext.getRequest().getContextPath();
// String basePath = ServletActionContext.getRequest().getScheme() + "://"
// + ServletActionContext.getRequest().getServerName() + ":" + ServletActionContext.getRequest().getServerPort()+ path + "/";
//
// String chartViewer = basePath + "tbc03Action.action";
// ServletActionContext.getRequest().setAttribute("chartViewer", chartViewer);
return SUCCESS;
}
/**
* create image
* @param x date, y value
* @return image name and image url
*/
private XYDataset createDateSet()
{
TimeSeriesCollection dataset = new TimeSeriesCollection();
// AFO Line is generate
TimeSeries s1 = new TimeSeries("line1", org.jfree.data.time.Second.class);
TimeSeries s2 = new TimeSeries("line2", org.jfree.data.time.Second.class);
TimeSeries s3 = new TimeSeries("line3", org.jfree.data.time.Second.class);
TimeSeries s4 = new TimeSeries("line4", org.jfree.data.time.Second.class);
TimeSeries s5 = new TimeSeries("line5", org.jfree.data.time.Second.class);
TimeSeries s6 = new TimeSeries("line6", org.jfree.data.time.Second.class);
// TimeSeries s7 = new TimeSeries("line7", org.jfree.data.time.Second.class);
// TimeSeries s8 = new TimeSeries("line8", org.jfree.data.time.Second.class);
// TimeSeries s9 = new TimeSeries("line9", org.jfree.data.time.Second.class);
// TimeSeries s10 = new TimeSeries("line10", org.jfree.data.time.Second.class);
s1.add(new Second(00, 00, 22, 01, 01, 1970), 1);
s1.add(new Second(00, 01, 22, 01, 01, 1970), 1);
s1.add(new Second(20, 01, 22, 01, 01, 1970), 1.8);
s1.add(new Second(15, 01, 22, 01, 01, 1970), 1.8);
s1.add(new Second(45, 02, 22, 01, 01, 1970), 1);
s1.add(new Second(15, 02, 22, 01, 01, 1970), 1);
s1.add(new Second(45, 03, 22, 01, 01, 1970), 1.8);
s1.add(new Second(15, 03, 22, 01, 01, 1970), 1.8);
s1.add(new Second(15, 04, 22, 01, 01, 1970), 1);
s1.add(new Second(45, 04, 22, 01, 01, 1970), 1);
dataset.addSeries(s1);
s2.add(new Second(00, 00, 22, 01, 01, 1970), 2);
s2.add(new Second(00, 01, 22, 01, 01, 1970), 2);
s2.add(new Second(20, 01, 22, 1, 01, 1970), 2.8);
s2.add(new Second(15, 01, 22, 01, 01, 1970), 2.8);
s2.add(new Second(45, 02, 22, 01, 01, 1970), 2);
s2.add(new Second(15, 02, 22, 01, 01, 1970), 2);
s2.add(new Second(45, 03, 22, 01, 01, 1970), 2.8);
s2.add(new Second(15, 03, 22, 01, 01, 1970), 2.8);
s2.add(new Second(15, 04, 22, 01, 01, 1970), 2);
s2.add(new Second(45, 04, 22, 01, 01, 1970), 2);
dataset.addSeries(s2);
s3.add(new Second(00, 00, 22, 01, 01, 1970), 3);
s3.add(new Second(00, 01, 22, 01, 01, 1970), 3);
s3.add(new Second(20, 01, 22, 1, 01, 1970), 3.8);
s3.add(new Second(15, 01, 22, 01, 01, 1970), 3.8);
s3.add(new Second(45, 02, 22, 01, 01, 1970), 3);
s3.add(new Second(15, 02, 22, 01, 01, 1970), 3);
s3.add(new Second(45, 03, 22, 01, 01, 1970), 3.8);
s3.add(new Second(15, 03, 22, 01, 01, 1970), 3.8);
s3.add(new Second(15, 04, 22, 01, 01, 1970), 3);
s3.add(new Second(45, 04, 22, 01, 01, 1970), 3);
dataset.addSeries(s3);
s4.add(new Second(00, 00, 22, 01, 01, 1970), 4);
s4.add(new Second(00, 01, 22, 01, 01, 1970), 4);
s4.add(new Second(20, 01, 22, 1, 01, 1970), 4.8);
s4.add(new Second(15, 01, 22, 01, 01, 1970), 4.8);
s4.add(new Second(45, 02, 22, 01, 01, 1970), 4);
s4.add(new Second(15, 02, 22, 01, 01, 1970), 4);
s4.add(new Second(45, 03, 22, 01, 01, 1970), 4.8);
s4.add(new Second(15, 03, 22, 01, 01, 1970), 4.8);
s4.add(new Second(15, 04, 22, 01, 01, 1970), 4);
s4.add(new Second(45, 04, 22, 01, 01, 1970), 4);
dataset.addSeries(s4);
s5.add(new Second(00, 00, 22, 01, 01, 1970), 5);
s5.add(new Second(00, 01, 22, 01, 01, 1970), 5);
s5.add(new Second(20, 01, 22, 1, 01, 1970), 5.8);
s5.add(new Second(15, 01, 22, 01, 01, 1970), 5.8);
s5.add(new Second(45, 02, 22, 01, 01, 1970), 5);
s5.add(new Second(15, 02, 22, 01, 01, 1970), 5);
s5.add(new Second(45, 03, 22, 01, 01, 1970), 5.8);
s5.add(new Second(15, 03, 22, 01, 01, 1970), 5.8);
s5.add(new Second(15, 04, 22, 01, 01, 1970), 5);
s5.add(new Second(45, 04, 22, 01, 01, 1970), 5);
dataset.addSeries(s5);
s6.add(new Second(00, 00, 22, 01, 01, 1970), 6);
s6.add(new Second(00, 01, 22, 01, 01, 1970), 6);
s6.add(new Second(20, 01, 22, 1, 01, 1970), 6.8);
s6.add(new Second(15, 01, 22, 01, 01, 1970), 6.8);
s6.add(new Second(45, 02, 22, 01, 01, 1970), 6);
s6.add(new Second(15, 02, 22, 01, 01, 1970), 6);
s6.add(new Second(45, 03, 22, 01, 01, 1970), 6.8);
s6.add(new Second(15, 03, 22, 01, 01, 1970), 6.8);
s6.add(new Second(15, 04, 22, 01, 01, 1970), 6);
s6.add(new Second(45, 04, 22, 01, 01, 1970), 6);
dataset.addSeries(s6);
dataset.setDomainIsPointsInTime(true);
return dataset;
}
/**
* produce pic
*
* @param session
* image save in session
* @param pw
* write image url
* @param s
* image is big or small
* @exception IOException
* dateTime I/O exception
* @throws ParseException
*/
public JFreeChart getLineXYChart(int s,String starttime,String kikan,String nyr) throws IOException, ParseException
{
XYDataset dataset = this.createDateSet();
// draw jFreeChart page
chart = ChartFactory.createTimeSeriesChart(" ", " ", " ", dataset, false, false, false);
// x ,y draw style
XYPlot xyplot = (XYPlot)chart.getPlot();
xyplot.setBackgroundPaint(Color.black);
xyplot.setDomainGridlinePaint(Color.black);
xyplot.setRangeGridlinePaint(Color.white);
xyplot.setDomainMinorGridlinePaint(Color.white);
xyplot.setDomainAxisLocation(AxisLocation.TOP_OR_RIGHT);
XYStepRenderer xysteprenderer = new XYStepRenderer();
xysteprenderer.setBaseShapesVisible(true);
xysteprenderer.setBaseToolTipGenerator(new StandardXYToolTipGenerator());
xysteprenderer.setDefaultEntityRadius(2);
xyplot.setRenderer(xysteprenderer);
//*
DateAxis dateaxis = (DateAxis)xyplot.getDomainAxis();
// time(x) axis
//DateAxis dateaxis = (DateAxis)xyplot.getDomainAxis();
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
dateaxis.setDateFormatOverride(format);
// dateaxis.setVerticalTickLabels(true);
Date end_time;
String endtime;
int sec;
int min;
sec = Integer.parseInt(starttime.substring(6,8))+1;
min = Integer.parseInt(kikan)+Integer.parseInt(starttime.substring(3,5));
System.out.print(sec);
if (sec < 0) {
sec = 00;
}
String secend = null;
if (sec < 10) {
secend = "0"+sec;
}
String minute = "";
if (min <10) {
minute = "0" + String.valueOf(min);
} else {
minute = String.valueOf(min);
}
endtime = starttime.substring(0,2)+":"+ minute +":"+ secend;
end_time = format.parse(endtime);
int starttime_sec = Integer.parseInt(starttime.substring(6, 8))+1;
System.out.print(end_time.getDate());
String starttime_secend = "";
if (starttime_sec < 10) {
starttime_secend = "0" + String.valueOf(starttime_sec);
}
starttime = starttime.substring(0, 6) + starttime_secend;
starttime = starttime;
Date startDate = format.parse(starttime);
dateaxis.setRange(startDate, end_time);
dateaxis.setVisible(true);
XYItemRenderer r = xyplot.getRenderer();
if (r instanceof XYLineAndShapeRenderer)
{
XYLineAndShapeRenderer renderer = (XYLineAndShapeRenderer) r;
// line color
renderer.setSeriesPaint(0, Color.GREEN);
renderer.setSeriesPaint(1, Color.green);
renderer.setSeriesPaint(2, Color.green);
renderer.setSeriesPaint(3, Color.GREEN);
renderer.setSeriesPaint(4, Color.green);
renderer.setSeriesPaint(5, Color.green);
renderer.setSeriesPaint(6, Color.GREEN);
renderer.setSeriesPaint(7, Color.green);
renderer.setSeriesPaint(8, Color.green);
renderer.setSeriesPaint(9, Color.GREEN);
renderer.setSeriesPaint(10, Color.GREEN);
}
// dispose dateTime I/O exception
if (s == 1) {
// big
dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.SECOND, 60, format));
} else if (s == 0) {
// normal
dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.SECOND, (int) (Float.parseFloat(kikan)*60/0.5/20), format));
} else if (s == 2) {
// small
dateaxis.setTickUnit(new DateTickUnit(DateTickUnit.SECOND, 30, format));
}
return chart;
}
}
Utilities.java//修改了jfreechart的生成臨時圖片的路徑
public static String saveChartAsPNG(JFreeChart chart, int width, int height,
ChartRenderingInfo info, HttpSession session) throws IOException {
if (chart == null) {
throw new IllegalArgumentException("Null 'chart' argument.");
}
Utilities.createTempDir();
String prefix = Utilities.tempFilePrefix;
if (session == null) {
prefix = Utilities.tempOneTimeFilePrefix;
}
System.out.print(ServletActionContext.getServletContext().getRealPath(ServletActionContext.getRequest().getRequestURI()));
String path = ServletActionContext.getRequest().getRealPath("/") + "TBC03";
String path1 = ServletActionContext.getRequest().getContextPath();
String basePath = ServletActionContext.getRequest().getScheme() + "://"
+ ServletActionContext.getRequest().getServerName() + ":" + ServletActionContext.getRequest().getServerPort()
+ path1 + "/";
File tempFile = File.createTempFile(prefix, ".png",
new File(path));
ChartUtilities.saveChartAsPNG(tempFile, chart, width, height, info);
if (session != null) {
Utilities.registerChartForDeletion(tempFile, session);
}
return path+"/"+tempFile.getName();
}
protected static void registerChartForDeletion(File tempFile,
HttpSession session) {
// Add chart to deletion list in session
if (session != null) {
ChartDeleter chartDeleter
= (ChartDeleter) session.getAttribute("JFreeChart_Deleter");
if (chartDeleter == null) {
chartDeleter = new ChartDeleter();
session.setAttribute("JFreeChart_Deleter", chartDeleter);
}
chartDeleter.addChart(tempFile.getName());
}
else {
System.out.println("Session is null - chart will not be deleted");
}
}
ChartResult.java //重新定義了返回圖片的width和height的屬性不然出錯。
package com.nec.jp.railroadX.tzz.tbc03;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.StrutsResultSupport;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.util.ValueStack;
public class ChartResult extends StrutsResultSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private String width;
private String height;
private String imageType;
public String getWidth() {
return width;
}
public void setWidth(String width) {
this.width = width;
}
public String getHeight() {
return height;
}
public void setHeight(String height) {
this.height = height;
}
public String getImageType() {
return imageType;
}
public void setImageType(String imageType) {
this.imageType = imageType;
}
@Override
protected void doExecute(String arg0, ActionInvocation invocation)
throws Exception {
JFreeChart chart =(JFreeChart) invocation.getStack().findValue("chart"); //add by _zZ begin
ValueStack stack = invocation.getStack();
height = conditionalParse(height, invocation);
width = conditionalParse(width, invocation);
imageType = conditionalParse(imageType, invocation); //add by _zZ end
HttpServletResponse response = ServletActionContext.getResponse();
OutputStream os = response.getOutputStream(); //add by _zZ begin
int h = Integer.parseInt(height);
int w = Integer.parseInt(width); //add by _zZ end
if("jpeg".equalsIgnoreCase(imageType) || "jpg".equalsIgnoreCase(imageType))
ChartUtilities.writeChartAsJPEG(os, chart, w, h);
else if("png".equalsIgnoreCase(imageType)) ChartUtilities.writeChartAsPNG(os, chart, w, h);
else ChartUtilities.writeChartAsJPEG(os, chart, w, h);
os.flush();
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="jfreeChart" extends="jfreechart-default" >
<result-types>
<result-type name="chart" class="org.apache.struts2.dispatcher.ChartResult" >
<param name="width">${width}</param>
<param name="height">${height}</param>
</result-type>
<result-type name="chart" class="com.nec.jp.railroadX.tzz.tbc03.ChartResult"></result-type>
</result-types>
<action name="updatetbc03Action" class="com.nec.jp.railroadX.tzz.tbc03.Tbc03Action" >
<result name="success" >
/TBC03/STBC0301.jsp
</result>
</action>
</package>
</struts>
STBC0301.jsp
<s:form action="updatetbc03Action" method="get">
<s:submit value="更新" ></s:submit>
<img id="imgShow" src="img.jsp" usemap="<s:property value='hy_filename'/>" >