在 Java Web 開發中,數據可視化是常見需求。JFreeChart 作為開源圖表庫的佼佼者,功能強大但直接在 JSP 中編寫繁瑣的 Java 代碼不利於維護。本文示範如何將 JFreeChart 封裝為自定義 JSP 標籤,實現圖表組件的複用與參數化配置。
繼承 TagSupport 類,封裝圖表寬高、類型、數據源、渲染模式(2D/3D)等屬性。通過 doStartTag() 方法在頁面加載時動態生成圖表圖片並輸出 HTML 標籤。
public class ChartTag extends TagSupport {
private static final long serialVersionUID = 1L;
private int width = 790; // 圖表寬度
private int height = 460; // 圖表高度
private String type; // 圖表類型(如:pie, bar, line)
private DataVO dataVO; // 圖表數據傳輸對象
private String attributeName = "chartData"; // Request 屬性名
private String chartType = "2D"; // 渲染模式:2D 或 3D
public int doStartTag() throws JspException {
HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
HttpSession session = request.getSession(true);
// 從 Request 獲取數據對象
dataVO = (DataVO) request.getAttribute(attributeName);
// 初始化圖表工廠
ChartFactory factory = new ChartFactory(dataVO, session);
factory.setPicWidth(width);
factory.setPicHeight(height);
factory.setChartStyle(chartType);
try {
factory.createChart(type); // 根據類型生成圖表
} catch (Exception e) {
e.printStackTrace();
}
// 輸出圖片及映射區域
String fileName = factory.getFileName();
String picUrl = factory.getPicURL();
StringBuilder html = new StringBuilder();
html.append(factory.getChartMapHtml());
html.append(String.format(
"<img border='0' width='%d' height='%d' src='%s%s' useMap='#%s'/>",
width, height, request.getContextPath(), picUrl, fileName
));
try {
pageContext.getOut().println(html.toString());
} catch (IOException e) {
throw new JspException("圖表輸出失敗", e);
}
return EVAL_PAGE;
}
// Getter/Setter 方法省略...
}
通過 DataVO 封裝圖表數據,標籤不關心具體業務邏輯,僅負責渲染,符合「關注點分離」原則。
ChartFactory 負責調用 JFreeChart API 生成圖片文件,並返回 <map> 區域座標,實現圖表熱點點擊功能(如點擊餅圖區塊跳轉詳情頁)。
JSP 頁面僅需聲明:
<%@ taglib prefix="chart" uri="/WEB-INF/chart.tld" %>
<chart:chartTag width="800" height="500" type="pie3D" attributeName="salesData" chartType="3D" />
即可輕鬆嵌入專業級圖表,參數可動態傳遞,適應不同業務場景。
將 JFreeChart 封裝為 JSP 標籤,不僅簡化了頁面代碼,更統一了圖表風格與交互行為。此模式可擴展至 ECharts、Highcharts 等前端圖表庫的服務端渲染場景,是 Java Web 圖表開發的經典範式。