1.action
@Controller(value = "pieAction")@Scope("prototype")public class PieAction extends ActionSupport { @Autowired private PieService pieService; // 图表 private JFreeChart jFreeChart; @Override public String execute() throws Exception { // 1准备数据集 DefaultPieDataset pieDate = new DefaultPieDataset(); // 2查询数据 Listlist = pieService.find(); // 3循环放入数据集 for (Pie pie : list) { pieDate.setValue(pie.getName(), pie.getNum()); } // 设置主题及编码(省略主题设置) StandardChartTheme sct = new StandardChartTheme("CN"); ChartFactory.setChartTheme(sct); // 生成char this.jFreeChart = ChartFactory.createPieChart3D("标题-测试", pieDate); // 乱码解决 TextTitle textTitle = jFreeChart.getTitle(); textTitle.setFont(new Font("微软雅黑", Font.BOLD, 12)); PiePlot plot = (PiePlot) jFreeChart.getPlot(); // 设置饼状图体里的的各个标签字体 plot.setLabelFont(new Font("微软雅黑", Font.BOLD, 12)); // 设置图表下方的图例说明字体 jFreeChart.getLegend().setItemFont(new Font("微软雅黑", Font.BOLD, 12)); // 获取到要保存的路径 String realPath = ServletActionContext.getRequest().getRealPath("img"); // 保存图片到路径 FileOutputStream fos = new FileOutputStream(realPath + "/test.jpg"); ChartUtilities.writeChartAsJPEG(fos, 1, jFreeChart, 400, 300, null); fos.close(); return SUCCESS; } public PieService getPieService() { return pieService; } public void setPieService(PieService pieService) { this.pieService = pieService; } public JFreeChart getjFreeChart() { return jFreeChart; } public void setjFreeChart(JFreeChart jFreeChart) { this.jFreeChart = jFreeChart; }}
2.jsp页面