绘制echarts折线图

利用eclipse和MySQL数据库完成了折线图表的绘制,通过向MySQL数据库中引入老师提供的sql文件来获取了全国的疫情信息,然后再通过访问echart官网学习了它的基本结构以及各项结构的功能,并运行了官网的实例来更清楚的了解echarts。首先依然是在后台先连接数据库,然后写bean,不同的是需要写两个bean,一个是存放数据库中的对象,另一个则是存放图标的横轴与纵轴的信息。首先需要把数据库中的数据全都输出出来,需要在servlet里面写一个遍历输出表的函数findAll(),然后通过另一个service调用这个函数,并且获得一个List数组,并且进行循环,在循环中把每条信息的省份和确诊人数分别赋给坐标轴的横轴和纵轴,然后把获取到的横轴和纵轴装到json中去。然后通过jsp中的result来取出信息并且给坐标轴,这样坐标轴便可以显示数据了,然后就通过折现图表来显示数据库中的所有信息。

代码如下:

<%@page import="servlet.yqServlet"%>
<%@page import="java.util.List"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@page import="java.util.ArrayList"%>
    <%@page import="bean.yq"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="js/bootstrap.min.css">
<script src="js/jquery-1.8.3.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/echarts.min.js"></script>
<jsp:useBean id="b" class="servlet.yqServlet"></jsp:useBean>
<script type="text/javascript">
function onload() {
    <% 
    
    List<yq> yq = null;
    yq = b.findAll();
    %>
}
</script>
</head>


<body>
<!-- <div style="text-align: center;">
时间:<input type="text" name="Date" >
<a href="1.jsp">查询</a>
</div> -->
<div id="main" style="width:1000px; height: 600px;"></div>

<div align="center">
        <h1 >全国各省疫情信息</h1>
        <table >
            <tr>
                <td>日期</td>
                <td>省份</td>
                <td>城市</td>
                <td>确诊人数</td>
                <td>疑似病例</td>
                <td>治愈人数</td>
                <td>死亡人数</td>
            </tr>
            <c:forEach items="<%=yq %>" var="item">
                <tr>
                    <td>${item.getDate()}</td>
                    <td>${item.getProvince()}</td>
                    <td>${item.getCity()}</td>
                    <td>${item.getConfirmed_num()}</td>
                    <td>${item.getYisi_num()}</td>
                    <td>${item.getCured_num()}</td>
                    <td>${item.getDead_num()}</td>
                </tr>
            </c:forEach>
        </table>
    </div>
</body>
<script type="text/javascript">

        // 基于准备好的dom,初始化echarts实例
        var myChart = echarts.init(document.getElementById('main'));

        // 指定图表的配置项和数据
        myChart.setOption({
            title: { 
                text: '全国各省确诊人数'
            },
            tooltip: {},
            legend: {
                data:['确诊人数'],
                width:'auto',
                height:'auto'
            },
            xAxis: {
                data: []
            },
            yAxis: {},
            series: [{
                name: '确诊人数',
                type: 'line',
                data: []
            }]
        });
        myChart.showLoading();
        var names=[];    //类别数组(实际用来盛放X轴坐标值)
        var nums=[];    //销量数组(实际用来盛放Y坐标值)
        // 使用刚指定的配置项和数据显示图表。
        $.ajax({
        type : "post",
        async : true,            //异步请求(同步请求将会锁住浏览器,用户其他操作必须等待请求完成才可以执行)
        url : "s",    //请求发送到TestServlet处
        success : function(resultJson) {
            var result= jQuery.parseJSON(resultJson);
            //请求成功时执行该函数内容,result即为服务器返回的json对象
            if (result) {
                for(var i=0;i<result.length;i++){
                      names.push(result[i].name);    //挨个取出类别并填入类别数组
                      nums.push(result[i].value);
                    }
                   myChart.hideLoading();    //隐藏加载动画
                   myChart.setOption({        //加载数据图表
                       xAxis: {
                           data: names
                       },
                       series: [{
                           // 根据名字对应到相应的系列
                           name: '确诊人数',
                           data: nums
                       }]
                   });
                   
            }
       },
        error : function(errorMsg) {
            //请求失败时执行该函数
        alert("图表请求数据失败!");
        myChart.hideLoading();
        }
   });
    </script>
</html>
package bean;

public class date {
private String name;
private String value;
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public String getValue() {
    return value;
}
public void setValue(String value) {
    this.value = value;
}
}
package bean;


public class yq {
private String Date;
private String Province;
private String City;
private String Confirmed_num;
private String Yisi_num;
private String Cured_num;
private String Dead_num;
public String getDate() {
    return Date;
}
public void setDate(String date) {
    this.Date = date;
}
public String getProvince() {
    return Province;
}
public void setProvince(String province) {
    Province = province;
}
public String getCity() {
    return City;
}
public void setCity(String city) {
    City = city;
}
public String getConfirmed_num() {
    return Confirmed_num;
}
public void setConfirmed_num(String confirmed_num) {
    Confirmed_num = confirmed_num;
}
public String getYisi_num() {
    return Yisi_num;
}
public void setYisi_num(String yisi_num) {
    Yisi_num = yisi_num;
}
public String getCured_num() {
    return Cured_num;
}
public void setCured_num(String cured_num) {
    Cured_num = cured_num;
}
public String getDead_num() {
    return Dead_num;
}
public void setDead_num(String dead_num) {
    Dead_num = dead_num;
}

}
package servlet;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.sun.org.apache.bcel.internal.generic.Select;

import bean.yq;
import jdk.nashorn.internal.objects.annotations.Where;
import bean.yq;

@SuppressWarnings("unused")
public class yqServlet {
    private Connection conn;
    private PreparedStatement pstmt;
    @SuppressWarnings("static-access")
    public yqServlet()
    {
        conn=new util.DBUtil().getConn();
    }
    public List<yq> findAll()
    {
        try {  
            String sql = "select * from info where id < 33";
            pstmt=conn.prepareStatement(sql);
            ResultSet rs = pstmt.executeQuery();
            List<yq> Y = new ArrayList<yq>();
            while(rs.next()) 
            {
                yq user=new yq();
                user.setDate(rs.getString(2));
                user.setProvince(rs.getString(3));
                user.setCity(rs.getString(4));
                user.setConfirmed_num(rs.getString(5));
                user.setYisi_num(rs.getString(5));;
                user.setCured_num(rs.getString(7));;
                user.setDead_num(rs.getString(8));;
                Y.add(user);
            }
            return Y;
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}
package servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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.google.gson.Gson;

import bean.yq;
import bean.date;
import util.DBUtil;

/**
 * servlet implementation class search
 */
@WebServlet("/s")
public class s extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public s() {
        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
         request.setCharacterEncoding("utf-8"); 
         response.setContentType("text/html;charset=utf-8");
         List<yq> Y = new ArrayList<yq>();
         yqServlet b = new yqServlet();
         Y = b.findAll();
         List<date> date = new ArrayList<date>();
         for(yq y:Y){
             date d = new date();
             d.setName(y.getProvince());
             d.setValue(y.getConfirmed_num());
             date.add(d);
         }
            Gson gson = new Gson();
            String json = gson.toJson(date);
            System.out.println(json);
            response.getWriter().write(json);
    }

    /**
     * @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);
    }

}
package util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.mysql.jdbc.PreparedStatement;
public class DBUtil {
    public static String db_url = "jdbc:mysql://localhost:3306/yiqing?useUnicode=true&characterEncoding=utf8";
    public static String db_user = "root";
    public static String db_pass = "20183602";
    
    public static Connection getConn () {
        Connection conn = null;
        
        try {
            Class.forName("com.mysql.jdbc.Driver");//加载JDBC驱动
            conn = DriverManager.getConnection(db_url, db_user, db_pass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return conn;
    }
    
    
    public static void close (ResultSet rs, PreparedStatement state, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
        if (state != null) {
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    
}

结果展示:

 

posted @ 2020-03-05 18:49  20183602  阅读(955)  评论(0编辑  收藏  举报