利用AJAX JAVA 通過Echarts實現豆瓣電影TOP250的數據可視化

1.mysql表的結構

2.數據(數據是通過爬蟲得來的,本篇文章不介紹怎麼爬取數據,只介紹將數據庫中的數據可視化):

下面就是寫代碼了:
首先看一下項目目錄:

數據庫層:

業務邏輯層:

package dao;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.sql.Connection;

import db.DbHelper;

import entity.Info;
public class Deal {
  
  public ArrayList<Info> query(){            //這裏的query()方法是將從數據庫中讀取到的數據存儲到集合中
      ResultSet rs = null;
   Statement st = null;
   Connection conn=null;
   ArrayList<Info> barArr=new ArrayList<Info>();
  try{
  conn =DbHelper.getConnection();  //獲取數據庫連接對象
  st = conn.createStatement();
  rs = st.executeQuery("select * from doubancn");
   while(rs.next()){
    Info movie=new Info();
    movie.setCountries(rs.getString("countries"));
    movie.setNum(rs.getInt("num"));
    barArr.add(movie);          //使用循環將從數據庫中讀到的內容存儲到集合對象中
   }
   
  }catch(SQLException e){
   e.printStackTrace();
  }
  catch(Exception e){
   e.printStackTrace();
  }
  finally{
//   try{
//   if(rs!=null)
//    rs.close();
//   }catch(Exception e){
//    e.printStackTrace();
//   }
//   try{
//    if(st!=null)
//     st.close();
//    }catch(Exception e){
//     e.printStackTrace();
//    }
//   try{
//    if(conn!=null)
//     conn.close();
//    }catch(Exception e){
//     e.printStackTrace();
//    }
//   
   
  }
  return barArr;  //返回該集合對象
  
  }
 
}


實體類:
package entity;
public class Info {
 private String countries;
 private Integer num;
 public Info(){
  
 }
 public String getCountries() {
  return countries;
 }
 public void setCountries(String countries) {
  this.countries = countries;
 }
 public Integer getNum() {
  return num;
 }
 public void setNum(Integer num) {
  this.num = num;
 }
 
 
 
}

servlet:

package com.wzs.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.Deal;
import net.sf.json.JSONArray;
import entity.Info;
public class Barservice extends HttpServlet {
 /**
  * Constructor of the object.
  */
 public Barservice() {
  super();
 }
 /**
  * Destruction of the servlet. <br>
  */
 public void destroy() {
  super.destroy(); // Just puts "destroy" string in log
  // Put your code here
 }
 /**
  * The doGet method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to get.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  doPost(request, response);
  
 }
 /**
  * The doPost method of the servlet. <br>
  *
  * This method is called when a form has its tag value method equals to post.
  *
  * @param request the request send by the client to the server
  * @param response the response send by the server to the client
  * @throws ServletException if an error occurred
  * @throws IOException if an error occurred
  */
 public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  Deal dl=new Deal();
  
  ArrayList<Info> brrar=dl.query();  //調用方法,獲取數據
  response.setContentType("text/html;charset=utf-8");
  JSONArray json=JSONArray.fromObject(brrar);  //將ArrayList類型轉爲JSONArray類型,因爲Echarts只識別JsonArray
             //注意,這裏需要導入許多jar包
  
  PrintWriter writer =response.getWriter();
  writer.println(json);
  writer.flush();
  //關閉輸出流
  writer.close();
 }
 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
  // Put your code here
 }
}


jsp頁面代碼:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
   
    <title>My JSP 'index.jsp' starting page</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">   
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
   <script src="echarts.min.js"></script>
  <script src="jquery-1.8.3.min.js"></script>
  </head>
   <body  οnlοad="loadData()"> <!-- 打開網頁的時候就執行該方法加載數據 -->
 
  <!-- 畫圖 -->
 
  <h1>豆瓣TOP</h1>
<div id="content" style="margin:40px auto;">
 
 <div id="myBarDiv" style="height:300px;width:1550px;display:inline-block"></div> 
  <div id="myLineDiv" style="height:300px;width:1550px;display:inline-block"></div>
 <div id="myPieDiv" style="height:600px;width:1300px;display:inline-block"></div> 
</div>

 
 <script type="text/javascript">
  function loadData(option){
   $.ajax({
    type:"post",   //跳轉方式
    async:false,            //採用同步傳輸
    url:'servlet/Barservice',   //跳轉的servlet。跳轉到該servlet之後執行dopost方法,獲取到JSONArray類型的數據,可以被Echarts識別。
    data:{},
    dataType:'json',
    success:function(result){
     if(result){
      option.xAxis[0].data=[];
      for(var i=0;i<result.length;i++){
       option.xAxis[0].data.push(result[i].countries);  //設置橫座標的數據
      }
      
      //初始化series[0]的data
      option.series[0].data=[];
      for(var i=0;i<result.length;i++){
       option.series[0].data.push(result[i].num);   //設置縱座標的數據
      }
     }
    },
    error:function(errorMsg){
     alert("數據加載失敗");
    }
    
    
   });
  }
 //初始化Echarts
 var myChart=echarts.init(document.getElementById('myBarDiv'));
 var option={
  title:{
   text:'柱狀圖'
  },
  tooltip:{
   show:true
  },
  legend:{
   data:['數量']
  },
  xAxis:[{
  
   type:'category',
   axisTick:{
                alignWithLabel: true,//豎線對準文字
       interval:0,   //橫座標的豎線的間隔
   },
   axisLabel:{ 
                        interval:0
                    } //橫座標顯示全部信息
  }],
  yAxis:[{
   type:'value'
  }],
  series:[{
   name:'數量',
   type:'bar',
   
  }]
 };
 loadData(option);  //加載數據到option
 myChart.setOption(option);  //設置option(畫圖)
 </script>
 
  <script type="text/javascript">
 
  function loadData(option){
   $.ajax({
    type:"post",   //跳轉方式
    async:false,            //採用同步傳輸
    url:'servlet/Barservice',   //跳轉的servlet。跳轉到該servlet之後執行dopost方法,獲取到JSONArray類型的數據,可以被Echarts識別。
    data:{},
    dataType:'json',
    success:function(result){
     if(result){
      option.xAxis[0].data=[];
      for(var i=0;i<result.length;i++){
       option.xAxis[0].data.push(result[i].countries);  //設置橫座標的數據
      }
      
      //初始化series[0]的data
      option.series[0].data=[];
      for(var i=0;i<result.length;i++){
       option.series[0].data.push(result[i].num);   //設置縱座標的數據
      }
     }
    },
    error:function(errorMsg){
     alert("數據加載失敗");
    }
    
    
   });
  }
  
  
 var myChart=echarts.init(document.getElementById('myLineDiv'));
 var option={
  title:{
   text:'折線圖'
  },
  tooltip:{
   show:true,
   trigger:'item'
  },
  legend:{
   data:['數量']
  },
   toolbox:{   //工具欄組件
               show:true,
               feature:{  //需要的功能
                   saveAsImage:{
                       show:true
                   },                      //保存爲圖片
                   dataView:{
                       show:true          //數據視圖
                   },
                   dataZoom:{
                       show:true            //區域縮放與區域縮放還原
                   },
                   magicType:{
                       type:['line','bar']       //動態類型轉換
                   }
               }
           },
  xAxis:[{
  
   type:'category',
   axisTick:{
                alignWithLabel: true,//豎線對準文字
       interval:0,   //座標軸刻度標籤的顯示間隔(在類目軸中有效哦),默認會採用標籤不重疊的方式顯示標籤(也就是默認會將部分文字顯示不全)
//可以設置爲0強制顯示所有標籤,如果設置爲1,表示隔一個標籤顯示一個標籤,如果爲3,表示隔3個標籤顯示一個標籤,以此類推
   },
   axisLabel:{ 
                        interval:0
                    } //顯示全部信息
  }],
  yAxis:[{
   type:'value'
  }],
  series:[{
   name:'數量',
   type:'line'
   
  }]
 };
 loadData(option);  //加載數據到option
 myChart.setOption(option);  //設置option
 
 
 </script>
 
 
 
 <script type="text/javascript">
 var myChart=echarts.init(document.getElementById('myPieDiv'));
 
 function loadData(option){
   $.ajax({
    type:"post",   //跳轉方式
    async:false,            //採用同步傳輸
    url:'servlet/Barservice',   //跳轉的servlet。跳轉到該servlet之後執行dopost方法,獲取到JSONArray類型的數據,可以被Echarts識別。
    data:{},
    dataType:'json',
    success:function(result){
     
     if(result){
     var country=[];
     var number=[];         //定義兩個數組,用來存放餅狀圖的legend和data.
     
     for(var i=0;i<result.length;i++){
     country[i]=result[i].countries;
     var obj =new Object();
     obj.name=result[i].countries;     
     obj.value=result[i].num;
     number[i]=obj;
    
   }
     
  var option={
  title:{
   text:'餅狀圖',
   x:'center'
  },
  tooltip:{
   show:true,                         //注意:餅狀圖的數據的動態獲取需要將option放在result裏面。這與柱狀圖和折線圖不同
   trigger:'item'
  },
  legend:{
   data:country,        //這裏的legend使用的是數組,在上面動態獲取的
   left:'left',
   orient:'vertical'
  },
  series:[{
   name:'數量',
   type:'pie',
   radius:'60%', 
   data:number         //這裏的number也是數組,他裏面存的是對象,擁有name和value兩個屬性,也是在上面動態獲取到的數據
  
  }]
 };
      
      myChart.setOption(option);
      
     }
    },
    error:function(errorMsg){
     alert("數據加載失敗");
    }
    
    
   });
  }
 
 
 </script>
  </body>
 
</html>


運行結果:








至此,整個項目就完成了,通過Ajax和java的相關知識再使用Echarts工具實現 從數據庫中讀取數據並將數據可視化。我們還可以做數據的增刪改查,只需要在業務邏輯層加上新的方法。通過另外一個servlet調用,並在jsp頁面通過Ajax將需要修改的字段傳過去即可。具體的方法就不再演示了。至此,豆瓣電影TOP250的按國家分類的可視化就完成了。我們還可以按劇情分類 並可視化出來 方法一樣的,只是利用的數據表不同。
發佈了41 篇原創文章 · 獲贊 15 · 訪問量 12萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章