JSP 图表

作者: 2010jing | 来源:发表于2016-09-22 15:17 被阅读380次

这次目标就是生成简单的图表

先上个动图

word.gif

文章涉及到的几个知识点

  • 数据库链接
  • servlet 传递值给 JSP页面
  • canvasjs库生成的图表

首先,去 canvasjs官网 看一下生成图表的一些例子

比如: 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>

生成的样子就是这样

pieChart.png

通过研究代码 我们会发现,有一个js 数组,canvasjs 根据 这个数组的内容生成对应的图表。既然如此,我们这里暂且不研究具体的canvasjs, 我们目的是了解js需要什么样的数据,然后提供数据,最后生成我们需要的图表。

json数据

细心的读者就会发现,上面的 js 代码中, 有一个数组, 数组里面都是json数据。

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数据,可以先google查阅一下,补充一下知识。 这里简单说一下, 就是用于 名称 / 值对 来表示。
上例{ y: 4181563, indexLabel: "PlayStation 3" }
y 就是一个 key,它对应着一个value 4181563,
indexLabel 也是一个 key,它对应着一个value "PlayStation 3",。

数据库

建立数据库 test,并创建表名 pie, 字段 y (int) indexLable(varchar)

table1.png

录入数据

table2.png

用eclipse 创建一个 Dynamic Web Project,项目名称 ChartDemo

因为需要链接MySQL数据库,我们必须引用 com.mysql.jdbc_5.1.5.jar

将此jar 包 放于

WebContent
      -- Web-INT
         -- lib (放于这个文件夹内)

在 src 内 , 创建一个 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 
    */  
   //驱动程序就是之前在classpath中配置的JDBC的驱动程序的JAR 包中  
   public static final String DBDRIVER = "com.mysql.jdbc.Driver";  
   //连接地址是由各个数据库生产商单独提供的,所以需要单独记住  
   public static final String DBURL = "jdbc:mysql://localhost:3306/test";  
   //连接数据库的用户名  
   public static final String DBUSER = "root";  
   //连接数据库的密码  
   public static final String DBPASS = ""; 
   
   
   Connection conn = null; //表示数据库的连接对象 
   
   /** 
    * 建立数据库连接 
    * @return 数据库连接 
    */  
   public Connection getConnection() {  
       try {
           Class.forName(DBDRIVER);
       } catch (ClassNotFoundException e1) {
           // TODO Auto-generated catch block
           e1.printStackTrace();
       } //1、使用CLASS 类加载驱动程序  
       try {  
           // 获取连接  
           conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);  
       } catch (SQLException e) {  
           System.out.println(e.getMessage());  
       }  
       return conn;  
   } 
}

这个工具类 用于 链接数据库,里面提供一个方法 getConnection(),返回的是一个 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);//开始跳转 
        
        
        //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数组  
       JSONArray array = new JSONArray();  
        
       // 获取列数  
       ResultSetMetaData metaData = rs.getMetaData();  
       int columnCount = metaData.getColumnCount();  
        
       // 遍历ResultSet中的每条数据  
        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 内

private MySQLDB mysqlDB = new MySQLDB();

实例化一个MySQLDB对象

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, 并且从数据库内获取数据,返回结果集。

String data = null;
        
        try {
            if(rs.next()){
                data = resultSetToJson(rs);
                
            }
        } catch (JSONException | SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

将获取的结果集 转成 json格式。

转成json格式, 利用了这个方法

    public String resultSetToJson(ResultSet rs) throws SQLException,JSONException  
    {  
       // json数组  
       JSONArray array = new JSONArray();  
        
       // 获取列数  
       ResultSetMetaData metaData = rs.getMetaData();  
       int columnCount = metaData.getColumnCount();  
        
       // 遍历ResultSet中的每条数据  
        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();  
    }

打印出来就是这样的结果:

[
    {
        "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 (放于这个文件夹内)

servlet 传递值 给 JSP 页面

RequestDispatcher rd = request.getRequestDispatcher("index.jsp");  
        request.setAttribute("chartData",data);//存值  
        rd.forward(request,response);//开始跳转

index.jsp 页面

在此之前,需要在 WebContent下 创建一个文件夹asset,并将canvasjs.min.js文件放入内

WebContent
      -- asset (放于这个文件夹内)
      -- 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 传递过来的数据

<% 
    String piadata = request.getAttribute("chartData");  
%>

把代码 输出到 js内

    dataPoints:<%out.print(piadata);%>

到此,基本上完成。
项目结构如下

structure.png

运行结果:

result.png

相关文章

  • JSP 图表

    这次目标就是生成简单的图表 先上个动图 文章涉及到的几个知识点 数据库链接 servlet 传递值给 JSP页面 ...

  • java基础-day43-JSP

    JSP 1. JSP 1.1 JSP概述 1.2 为什么要用JSP 1.3 JSP语法 1.3.1 JSP语法格式...

  • jsp学习 EL JSTL C标签

    JSP 第一个JSP程序 JSP对比servlet JSP中java脚本元素 JSP原理 JSP的翻译规则 JSP...

  • JSP基础学习笔记(3)--JavaBean

    JSP动作标签:

  • 用session对象实现用户登录

    index.jsp deal.jsp main.jsp exit.jsp

  • JavaWeb之JSP

    八、JSP 目录:什么是JSP、JSP原理、JSP基础语法、JSP指令、9大内置对象、JSP标签 JSTL标签 E...

  • jsp语法

    Jsp语法包含:注释、jsp指令、jsp脚本元素、jsp动作元素。 Jsp注释: Htm...

  • jsp

    jsp介绍 jsp语法 jsp指令 EL表达式 自定义标签 jsp指令 - page jsp指令 - includ...

  • JSP入门

    JSP的基本语法:1.JSP声明语法。2、JSP程序脚本。3、JSP脚本注释。4、JSP内容输出表达式。5、JSP...

  • jsp的内置标签

    jsp:forward 重定向标签

网友评论

    本文标题:JSP 图表

    本文链接:https://www.haomeiwen.com/subject/mqezettx.html