1. 程式人生 > >ECharts動態載入JavaWeb後臺資料,圖表展現

ECharts動態載入JavaWeb後臺資料,圖表展現

jsp程式碼:(根據官方demo及自己需求,適當修改原始引數,需動態新增的原始測試資料可以不刪,可以覆蓋)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
  <!-- 引入 jquery -->
  <
script
src="<%=request.getContextPath() %>/vendor/jquery.min.js">
</script> <!-- 引入 echarts.js --> <script src="<%=request.getContextPath() %>/vendor/echarts.js"></script> </head> <body> <!-- 為ECharts準備一個具備大小(寬高)的Dom --> <div id="main"
style="width: 800px;height:600px;">
</div> <script type="text/javascript"> // 基於準備好的dom,初始化echarts例項 var myChart = echarts.init(document.getElementById('main')); // 指定圖表的配置項和資料 var option = { title: { text: '堆疊區域圖' }
, tooltip : { trigger: 'axis', axisPointer: { type: 'cross', label: { backgroundColor: '#6a7985' } } }, legend: { //data為需動態新增的資料,原始測試資料可刪可不刪 data:['郵件營銷','聯盟廣告','視訊廣告','直接訪問','搜尋引擎'] }, toolbox: { feature: { saveAsImage: {} } }, grid: { left: '3%', right: '4%', bottom: '3%', containLabel: true }, xAxis : [ { type : 'category', boundaryGap : false, //按需求手動設定了月份引數 data : ['一月','二月','三月','四月','五月','六月','七月','八月','九月','十月','十一月','十二月'] } ], yAxis : [ { type : 'value' } ], //series中資料為需動態新增的資料,原始測試資料可刪可不刪 series : [ { name:'郵件營銷', type:'line', stack: '總量', areaStyle: {}, data:[120, 132, 101, 134, 90, 230, 210, 0, 0, 0, 0, 0] }, { name:'聯盟廣告', type:'line', stack: '總量', areaStyle: {}, data:[220, 182, 191, 234, 290, 330, 310, 100, 110, 110, 110, 110] }, { name:'視訊廣告', type:'line', stack: '總量', areaStyle: {}, data:[150, 232, 201, 154, 190, 330, 410, 20, 20, 20, 20, 20] }, { name:'直接訪問', type:'line', stack: '總量', areaStyle: {normal: {}}, data:[320, 332, 301, 334, 390, 330, 320, 60, 60, 60, 60, 60] }, { name:'搜尋引擎', type:'line', stack: '總量', label: { normal: { show: true, position: 'top' } }, areaStyle: {normal: {}}, data:[820, 932, 901, 934, 1290, 1330, 1320, 1000, 1000, 1000, 1000, 1000] } ] }; var url = '<%=request.getContextPath()%>/consume/photoServlet?method=photo'; $.post(url,function(jsonData){ //更新資料 option.legend.data=jsonData[0]; option.series=jsonData[1]; myChart.hideLoading(); // 更新顯示圖表。 myChart.setOption(option); },'json');
</script> </body> </html>

後臺srevlet:

package com.consume.bhy.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSONArray;
import com.consume.bhy.service.PhotoService;

@WebServlet(urlPatterns="/consume/photoServlet")
public class PhotoServlet extends HttpServlet{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		Class<?> class1 = this.getClass();	
		String methodName = request.getParameter("method");
		
		try {
			Method method = class1.getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			method.setAccessible(true);
			try {
				method.invoke(this, request,response);
				
			} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
				e.printStackTrace();
			}
			
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
		
	}

	public void photo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/palin;charset=utf-8");
		
		//建立一個JSON陣列存放返回的資料
		JSONArray jsonData = new JSONArray();
		
        PhotoService ps = new PhotoService();
        jsonData = ps.getJsonData();
 
        //獲取輸出流寫資料
        PrintWriter writer = response.getWriter();
        writer.print(jsonData);
		
	}
	
}

後臺service:

package com.consume.bhy.service;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.consume.bhy.jdbc.JDBC_Util;

public class PhotoService {
	public JSONArray getJsonData() throws SQLException {
		//建立陣列存放legend中date資料
		JSONArray legendData = new JSONArray();
		//建立陣列存放series的資料
		JSONArray series = new JSONArray();
		//連線操作資料庫,查詢資料
		Connection conn = JDBC_Util.getConnection();
		String sql = "select consume_type_id,consume_type_name from consume_type";
		PreparedStatement prepared = conn.prepareStatement(sql);
		ResultSet resultSet = prepared.executeQuery();
		while(resultSet.next()) {
			String sql2 = "select month(consume_date) m, SUM(consume_price*consume_count) s from consume_info where consume_type_id=? group by month(consume_date) ORDER BY month(consume_date);";
			PreparedStatement prepared2 = conn.prepareStatement(sql2);
			prepared2.setInt(1, resultSet.getInt("consume_type_id"));
			ResultSet resultSet2 = prepared2.executeQuery();
			double[] consumedate =new double[12];
			while(resultSet2.next()) {
				consumedate[resultSet2.getInt("m")-1]= resultSet2.getBigDecimal("s").doubleValue();
			}
			JDBC_Util.clossJDBC(prepared2, resultSet2);
			JSONObject serie = new JSONObject();
			
			//將每種消費型別相應的引數存入serie物件並按順序存入series陣列
			serie.put("name", resultSet.getString("consume_type_name"));
		    serie.put("type", "line");
		    serie.put("stack", "總量");
		    serie.put("areaStyle", new JSONObject());
		    serie.put("data", consumedate);
			
		    series.add(serie);
		    //將消費型別順序存入legendData
			legendData.add(resultSet.getString("consume_type_name"));
		}
		//最後新增月總消費到legendData
		legendData.add("月總消費");
		JDBC_Util.clossJDBC(prepared, resultSet);
		String sql3 = "select month(consume_date) m, SUM(consume_price*consume_count) s from consume_info group by month(consume_date) ORDER BY month(consume_date);";
		PreparedStatement prepared3 = conn.prepareStatement(sql3);
		ResultSet resultSet3 = prepared3.executeQuery();
		double[] allConsume =new double[12];
		while(resultSet3.next()) {
			allConsume[resultSet3.getInt("m")-1]= resultSet3.getBigDecimal("s").doubleValue();
		}
		JDBC_Util.clossJDBC(conn, prepared3, resultSet3);
		
		JSONObject allSerie = new JSONObject();
		
		allSerie.put("name", "月總消費");
		allSerie.put("type", "line");
		allSerie.put("stack", "總量");
		allSerie.put("areaStyle", new JSONObject());
		allSerie.put("data", allConsume);
		//將月總消費的相應的引數存入allSerie物件並存入series陣列
	    series.add(allSerie);

	    //建立jsonData陣列儲存legendData和series陣列並返回
		JSONArray jsonData = new JSONArray();
		jsonData.add(legendData);
		jsonData.add(series);

		return jsonData;
	}

}

效果圖:在這裡插入圖片描述