這次目標(biāo)就是生成簡單的圖表
先上個(gè)動(dòng)圖
文章涉及到的幾個(gè)知識(shí)點(diǎn)
- 數(shù)據(jù)庫鏈接
- servlet 傳遞值給 JSP頁面
- canvasjs庫生成的圖表
首先,去 canvasjs官網(wǎng) 看一下生成圖表的一些例子
比如: Pie Chart
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer",
{
theme: "theme2",
title:{
text: "Gaming Consoles Sold in 2012"
},
data: [
{
type: "pie",
showInLegend: true,
toolTipContent: "{y} - #percent %",
yValueFormatString: "#,##0,,.## Million",
legendText: "{indexLabel}",
dataPoints: [
{ y: 4181563, indexLabel: "PlayStation 3" },
{ y: 2175498, indexLabel: "Wii" },
{ y: 3125844, indexLabel: "Xbox 360" },
{ y: 1176121, indexLabel: "Nintendo DS"},
{ y: 1727161, indexLabel: "PSP" },
{ y: 4303364, indexLabel: "Nintendo 3DS"},
{ y: 1717786, indexLabel: "PS Vita"}
]
}
]
});
chart.render();
}
</script>
<script type="text/javascript" src="/assets/script/canvasjs.min.js"></script></head>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;"></div>
</body>
</html>
生成的樣子就是這樣
通過研究代碼 我們會(huì)發(fā)現(xiàn)纪铺,有一個(gè)js 數(shù)組娩梨,canvasjs 根據(jù) 這個(gè)數(shù)組的內(nèi)容生成對(duì)應(yīng)的圖表。既然如此叔扼,我們這里暫且不研究具體的canvasjs事哭, 我們目的是了解js需要什么樣的數(shù)據(jù),然后提供數(shù)據(jù)瓜富,最后生成我們需要的圖表鳍咱。
json數(shù)據(jù)
細(xì)心的讀者就會(huì)發(fā)現(xiàn),上面的 js 代碼中与柑, 有一個(gè)數(shù)組谤辜, 數(shù)組里面都是json數(shù)據(jù)澎现。
dataPoints: [
{ y: 4181563, indexLabel: "PlayStation 3" },
{ y: 2175498, indexLabel: "Wii" },
{ y: 3125844, indexLabel: "Xbox 360" },
{ y: 1176121, indexLabel: "Nintendo DS"},
{ y: 1727161, indexLabel: "PSP" },
{ y: 4303364, indexLabel: "Nintendo 3DS"},
{ y: 1717786, indexLabel: "PS Vita"}
]
如果讀者不知道什么是json數(shù)據(jù),可以先google查閱一下每辟,補(bǔ)充一下知識(shí)剑辫。 這里簡單說一下, 就是用于 名稱 / 值對(duì) 來表示渠欺。
上例{ y: 4181563, indexLabel: "PlayStation 3" }
y 就是一個(gè) key妹蔽,它對(duì)應(yīng)著一個(gè)value 4181563,
indexLabel 也是一個(gè) key,它對(duì)應(yīng)著一個(gè)value "PlayStation 3",挠将。
數(shù)據(jù)庫
建立數(shù)據(jù)庫 test胳岂,并創(chuàng)建表名 pie, 字段 y (int) indexLable(varchar)
錄入數(shù)據(jù)
用eclipse 創(chuàng)建一個(gè) Dynamic Web Project,項(xiàng)目名稱 ChartDemo
因?yàn)樾枰溄覯ySQL數(shù)據(jù)庫舔稀,我們必須引用 com.mysql.jdbc_5.1.5.jar
將此jar 包 放于
WebContent
-- Web-INT
-- lib (放于這個(gè)文件夾內(nèi))
在 src 內(nèi) 乳丰, 創(chuàng)建一個(gè) MySQLDB 工具類
package cn.hejing.util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
* @author hejing
* @email 2010jing@gmail.com
* @date datetime 2016年9月21日 下午11:14:50
* @description
* @version 1.0
* @since
*/
public class MySQLDB {
/**
* @param args
*/
//驅(qū)動(dòng)程序就是之前在classpath中配置的JDBC的驅(qū)動(dòng)程序的JAR 包中
public static final String DBDRIVER = "com.mysql.jdbc.Driver";
//連接地址是由各個(gè)數(shù)據(jù)庫生產(chǎn)商單獨(dú)提供的,所以需要單獨(dú)記住
public static final String DBURL = "jdbc:mysql://localhost:3306/test";
//連接數(shù)據(jù)庫的用戶名
public static final String DBUSER = "root";
//連接數(shù)據(jù)庫的密碼
public static final String DBPASS = "";
Connection conn = null; //表示數(shù)據(jù)庫的連接對(duì)象
/**
* 建立數(shù)據(jù)庫連接
* @return 數(shù)據(jù)庫連接
*/
public Connection getConnection() {
try {
Class.forName(DBDRIVER);
} catch (ClassNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} //1内贮、使用CLASS 類加載驅(qū)動(dòng)程序
try {
// 獲取連接
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return conn;
}
}
這個(gè)工具類 用于 鏈接數(shù)據(jù)庫产园,里面提供一個(gè)方法 getConnection(),返回的是一個(gè) Connection。
編寫servlet ShowChart.java
package cn.hejing.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
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 org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import cn.hejing.util.MySQLDB;
/**
* Servlet implementation class ShowChart
*/
@WebServlet("/ShowChart")
public class ShowChart extends HttpServlet {
private static final long serialVersionUID = 1L;
private MySQLDB mysqlDB = new MySQLDB();
/**
* @see HttpServlet#HttpServlet()
*/
public ShowChart() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
Connection conn = mysqlDB.getConnection();
String sql = "select * from pie";
PreparedStatement ps=null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String data = null;
try {
if(rs.next()){
data = resultSetToJson(rs);
}
} catch (JSONException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(data);
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
request.setAttribute("chartData",data);//存值
rd.forward(request,response);//開始跳轉(zhuǎn)
//request.getRequestDispatcher("index.jsp").forward(request, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
public String resultSetToJson(ResultSet rs) throws SQLException,JSONException
{
// json數(shù)組
JSONArray array = new JSONArray();
// 獲取列數(shù)
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
// 遍歷ResultSet中的每條數(shù)據(jù)
while (rs.next()) {
JSONObject jsonObj = new JSONObject();
// 遍歷每一列
for (int i = 1; i <= columnCount; i++) {
String columnName =metaData.getColumnLabel(i);
if(columnName.equals("y")){
int value = rs.getInt(columnName);
jsonObj.put(columnName, value);
}else{
String value = rs.getString(columnName);
jsonObj.put(columnName, value);
}
//jsonObj.put(columnName, value);
}
array.put(jsonObj);
}
return array.toString();
}
}
在servlet 內(nèi)
private MySQLDB mysqlDB = new MySQLDB();
實(shí)例化一個(gè)MySQLDB對(duì)象
Connection conn = mysqlDB.getConnection();
String sql = "select * from pie";
PreparedStatement ps=null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
這里獲取到Connetion, 并且從數(shù)據(jù)庫內(nèi)獲取數(shù)據(jù)夜郁,返回結(jié)果集什燕。
String data = null;
try {
if(rs.next()){
data = resultSetToJson(rs);
}
} catch (JSONException | SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
將獲取的結(jié)果集 轉(zhuǎn)成 json格式。
轉(zhuǎn)成json格式竞端, 利用了這個(gè)方法
public String resultSetToJson(ResultSet rs) throws SQLException,JSONException
{
// json數(shù)組
JSONArray array = new JSONArray();
// 獲取列數(shù)
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
// 遍歷ResultSet中的每條數(shù)據(jù)
while (rs.next()) {
JSONObject jsonObj = new JSONObject();
// 遍歷每一列
for (int i = 1; i <= columnCount; i++) {
String columnName =metaData.getColumnLabel(i);
if(columnName.equals("y")){
int value = rs.getInt(columnName);
jsonObj.put(columnName, value);
}else{
String value = rs.getString(columnName);
jsonObj.put(columnName, value);
}
//jsonObj.put(columnName, value);
}
array.put(jsonObj);
}
return array.toString();
}
打印出來就是這樣的結(jié)果:
[
{
"indexLabel": "Wii",
"y": 2175498
},
{
"indexLabel": "Xbox 360",
"y": 3125844
},
{
"indexLabel": "Nintendo DS",
"y": 1176121
},
{
"indexLabel": "PSP",
"y": 1727161
},
{
"indexLabel": "Nintendo 3DS",
"y": 4303364
},
{
"indexLabel": "PS Vita",
"y": 1717786
}
]
打印出來本來是字符串屎即。
為了好看,格式化了一下事富,方便查看技俐。
注意: 需要添加 json-20160810.jar
WebContent
-- Web-INT
-- lib (放于這個(gè)文件夾內(nèi))
servlet 傳遞值 給 JSP 頁面
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
request.setAttribute("chartData",data);//存值
rd.forward(request,response);//開始跳轉(zhuǎn)
index.jsp 頁面
在此之前,需要在 WebContent下 創(chuàng)建一個(gè)文件夾asset,并將canvasjs.min.js文件放入內(nèi)
WebContent
-- asset (放于這個(gè)文件夾內(nèi))
-- Web-INT
-- lib
index.jsp 代碼
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Pie Chart</title>
</head>
<body>
<%
String piadata = request.getAttribute("chartData");
%>
<div id="chartContainer1" style="height: 400px; width: 100%;">
</body>
<script src="asset/canvasjs.min.js"></script>
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer1",
{
theme: "theme2",
title:{
text: "Gaming Consoles Sold in 2012"
},
data: [
{
type: "pie",
showInLegend: true,
toolTipContent: "{y} - #percent %",
yValueFormatString: "#,##0,,.## Million",
legendText: "{indexLabel}",
dataPoints:<%out.print(piadata);%>
}
]
});
chart.render();
}
</script>
</html>
jsp頁面 獲取從servlet 傳遞過來的數(shù)據(jù)
<%
String piadata = request.getAttribute("chartData");
%>
把代碼 輸出到 js內(nèi)
dataPoints:<%out.print(piadata);%>
到此统台,基本上完成雕擂。
項(xiàng)目結(jié)構(gòu)如下
運(yùn)行結(jié)果: