public class ChartView extends AbstractView { @Override protected void renderMergedOutputModel(Map<String, Object> map, HttpServletRequest request, HttpServletResponse response) throws Exception { JFreeChart chart=null; //IChart为自定义的接口规范。根据输出类型的不同调用相应的方法 switch (((Integer)map.get(IChart.CHARTTYPE)).intValue()) { case IChart.BAR:chart=getChartBar(map);break; case IChart.PIE:break; default:break; } //图片的输出 ChartUtilities.writeChartAsJPEG(response.getOutputStream(), chart, 200,200); } private JFreeChart getChartBar(Map<String, Object> map){ JFreeChart chart = ChartFactory.createBarChart3D("产品销量图", "产品名称", "销量", (CategoryDataset)map.get(IChart.CHARDATASET), PlotOrientation.VERTICAL, true, true, false); chart.getTitle().setFont(new Font("宋体", Font.BOLD, 20)); chart.getCategoryPlot().getDomainAxis().setTickLabelFont(new Font("宋体", Font.BOLD, 11)); chart.getCategoryPlot().getDomainAxis().setLabelFont(new Font("黑体", Font.BOLD, 12)); chart.getCategoryPlot().getRangeAxis().setTickLabelFont(new Font("宋体", Font.BOLD, 11)); chart.getCategoryPlot().getRangeAxis().setLabelFont(new Font("黑体", Font.BOLD, 12)); chart.getLegend().setItemFont(new Font("宋体", Font.BOLD, 11)); return chart; } }
public class ChartViewResolver extends AbstractCachingViewResolver { private String chartSuffix;//后缀 private View chartView; @Override protected View loadView(String viewName, Locale locale) throws Exception { View view = null; if (viewName.endsWith(this.getChartSuffix())){ view =this.getChartView(); } return view; } public String getChartSuffix() { return chartSuffix; } public void setChartSuffix(String chartSuffix) { this.chartSuffix = chartSuffix; } public View getChartView() { return chartView; } public void setChartView(View chartView) { this.chartView = chartView; } }
<bean id="chartViewResolver" class="com.zhang.webapp.util.ChartViewResolver"> <property name="chartSuffix" value=".chart"/> <property name="chartView"> <bean class="com.zhang.webapp.util.ChartView"/> </property> </bean> <!--注意viewResolver应放在最后,让自定义的优先执行 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/pages/"/> <property name="suffix" value=".jsp"/> </bean>
@RequestMapping(value="/getchart.chart",method=RequestMethod.GET) public String getChart(ModelMap modelMap){ DefaultCategoryDataset dataset = new DefaultCategoryDataset(); dataset.addValue(510, "深圳", "苹果"); dataset.addValue(320, "深圳", "香蕉"); dataset.addValue(580, "深圳", "橘子"); dataset.addValue(390, "济南", "梨子"); modelMap.addAttribute(IChart.CHARTTYPE,IChart.BAR); modelMap.addAttribute(IChart.CHARDATASET,dataset); return "webanalytics.chart"; }页面的代码:
<div id="tab_barChart" style="padding:0;display:block;"> <img id="chart_BAR" src="<c:url value='/user/getchart.chart'/>"> </div>
结果如下图所示: