您的位置:首页 > 编程语言 > Java开发

jfreechart和struts2,spring结合使用

2011-05-31 15:50 696 查看
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>

这种方式返回的就是一张图片,就算你在<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>

必须在web.xml中加上servlet的配置:

<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>

最后是jsp:

添加<img src="<%=request.getContextPath() %>/servletDisplayChart?filename=<s:property value='hy_filename'/>" border="0"> 就可以通过点按钮来控制图片的显示了

其中java代码:

import java.awt.Rectangle;

import java.awt.Shape;

import java.io.IOException;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

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;

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'/>" >

ok,问题解决,暂时没找到更好的办法

参考http://developer.51cto.com/art/201112/308498.htm
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: