グラフをただ出すだけなら,JFreeChartとServletそれぞれに関して若干の知識があればどうってことなくできる気がするが,確認のためにグラフをただ出してみた.
サンプル
その他の注意点
サンプル
本頁のサンプルは本当にグラフをただ出すだけである.JFreeChartオブジェクトは以前作成した棒グラフを出力するサンプルを流用する.
package matsu.sample;
import java.io.*;
import javax.servlet.http.*;
import org.jfree.chart.*;
import org.jfree.chart.plot.*;
import org.jfree.chart.axis.*;
import org.jfree.ui.*;
import org.jfree.data.*;
public class SimpleChartServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res) {
int width = 640;
int height = 640;
try {
// 縦横サイズの指定
width = Integer.parseInt(req.getParameterValues ("width")[0]);
height = Integer.parseInt(req.getParameterValues ("height")[0]);
} catch (Exception e) {
e.printStackTrace();
}
// 棒グラフのJFreeChartを作成
JFreeChart chart = createChart();
// コンテンツタイプをpngにする.
res.setContentType("image/png");
OutputStream outputStream;
System.err.println("write png width = " + width + " / height = " + height);
try {
outputStream = new BufferedOutputStream(res.getOutputStream());
// JFreeChartをPNGとして出力
ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 棒グラフのJFreeChartを作成する.
*/
private JFreeChart createChart () {
// 棒グラフのデータ
double[][] data = new double[][]
{{1.0, 2.0, 3.0, 4.0},
{5.0, 6.0, 7.0, 8.0},
{9.0, 10.0, 11.0, 12.0},
{13.0, 14.0, 15.0, 16.0}};
// CategoryDatasetオブジェクトの作成
CategoryDataset cData = DatasetUtilities.createCategoryDataset("RowKey ", "ColKey ", data);
// CategoryDatasetをデータにしてJFreeChartを作成
JFreeChart barChart = ChartFactory.createBarChart ("SampleBarChart",
"categoryAxisLabel",
"valueAxisLabel",
cData, PlotOrientation.VERTICAL,
false, false, false);
return barChart;
}
}
クエリにwidth,heightを使用して出力するグラフの縦横サイズを指定できる(デフォルトはそれぞれ640).で,このServletにアクセスすると,いつも決まったグラフが指定したサイズで出力される.注意点は
res.setContentType("image/png");
等としてコンテンツタイプを指定し,それに合わせて
ChartUtilities.writeChartAsPNG(outputStream, chart, width, height);
とグラフを出力する点である.
その他の注意点
JFreeChartでJFreeChartを生成する際には,おそらく必ずSwingやAWTを使用する.ウィンドウを出す/出さないにかかわらずである.で,Xが動いていないマシンで上のサンプルを起動すると,以下のような例外が発生してうまく動かなかった.
2004-06-23 21:09:51 simple_chart_servlet: init
2004-06-23 21:09:58 StandardWrapperValve[simple_chart_servlet]:
Servlet.service() for servlet simple_chart_servlet threw exception
javax.servlet.ServletException: Servlet execution threw an exception
....
----- Root Cause -----
java.lang.InternalError: Can't connect to X11 window server using 'xserver:0.0'
as the value of the DISPLAY variable.
at sun.awt.X11GraphicsEnvironment.initDisplay(Native Method)
at sun.awt.X11GraphicsEnvironment.<clinit>(X11GraphicsEnvironment.java:125)
上は環境変数DISPLAYをxserver:0.0と設定してTomcatを起動した場合の例である.Tomcatを起動する環境がXサーバと通信できるようにすれば,うまく起動しグラフも出力された.