1. 程式人生 > 程式設計 >Springboot運用vue+echarts前後端互動實現動態圓環圖

Springboot運用vue+echarts前後端互動實現動態圓環圖

前言

我們做專案的時候http://www.cppcns.com,常常需要一些統計圖來展示我們的資料,作為web開發人員,會實現統計圖是我們必會的技能。我將帶大家來實現動態餅圖的實現

一、環境配置

1.1 安裝acharts

//npm也一樣
cnpm install echarts --save

1.2 全域性引用

main.js中配置

//引入 echarts
import echarts from 'echarts'
//註冊元件
vue.prototype.$echarts = echarts

全域性註冊好元件之後就讓我們進入正題吧,第一步先繪製圓環圖吧。先上結果圖:

在這裡插入圖片描述

二、圓環圖前端實現

2.1 先在vue頁面新增渲染盒子

<template>
  <div class="test2" style="width:600px;height:400px;">
      <div id="myChart" style="width:100%;height:278px;float:left;"></div>
  </div>
</template>

2.2 前端邏輯實現部分

引入echart

import * as echarts from 'echarts'

注意:這裡有一個大坑,如果你安裝的是高版本的echarts,一定要按我這個來,import echarts from 'echarts'網上很多人都這麼分享會發生init函式初始化錯誤

<script>
     import * as echarts from 'echarts'
     export default {
       name: 'test2',data () {
         return {
         queryInfo: {
         query: "",pageNum: 1,pageSize: 4,//後端請求的資料類別4個,如果你有多個,就更改這個引數
       },queryInfof: {
         query: "",pageSize: 100,},myChart: '',opinionData2: [
           
           {"itemStyle":"#3F8FFF","name":"威脅攻擊日誌","value":200},{"itemStyle":"#6DC8EC","name":"審計url異常","value":388},{"itemStyle":"#1FC48D","name":"正常網路日誌","value":5287},{"itemStyle":"red","name":"流量日誌異常","value":320}      
           ]
         }
       },mounted: function () {
          this.drawLine();

       },methods: {
          async  drawLine () {
              // 呼叫post請求
     /* const { data: res } = await this.$http.get("alldate",{
        params: this.queryInfo
      });
      if (res.flag != "success") {
        return this.$message.error("該資料獲取失敗!!!");
      }

      console.log(res.flag)
       this.opinionData2 = res.opinionData2; // 將返回資料賦值*/
           this.myChart = echarts.init(document.getElementById('myChart'))
           this.myChart.setOption({
             title: {
               text: '網路日誌異常流量分析',// 主標題
               subtext: '',// 副標題
               x: 'left' // x軸
程式設計客棧
方向對齊方式 },grid: { containLabel: true },tooltip: { trigger: 'item',formatter: '{a} <br/>{b} : {d}%' },// color: ['#1FC48D','#F5A60A','#6DC8EC','#3F8FFF'],colorhttp://www.cppcns.com: ['#1FC48D','red',// backgroundColor: '#ffffff',legend: { orient: 'vertical',icon: 'circle',align: 'left',x: 'right',y: 'bottom',data: ['審計url異常','正常網路日誌','流量日誌異常','威脅攻擊日誌'] },series: [ { name: '網路日誌狀態',type: 'pie',radius: ['50%','70%'],avoidLabelOverlap: false,center: ['40%','50%'],itemStyle: { emphasis: { shadowBlur: 10,shadowOffsetX: 0,shadowColor: 'rgba(0,0.5)' },color: function (params) { // 自定義顏色 var colorList = ['#1FC48D','#3F8FFF'] return colorList[params.dataIndex] } },data: this.opinionData2 } ] }) },} } </script>

2.3 展示(可按自己需求更改前端樣式)

在這裡插入圖片描述

三、前後端資料互動實現

3.1 建立資料庫

表結構:(根據你的業務需要建立)

在這裡插入圖片描述

表資料

在這裡插入圖片描述

3.2 後臺程式碼的編寫

3.2.1 在bean包下建立QueryInfo類

該類實現得到前端請求的資料條數。相當於分頁功能。

public class QueryInfo {
    private String query;
    private int pageNum=1;
    private int pageSize=1;

    public QueryInfo() {
    }

    public QueryInfo(String query,int pageNum,int pageSize) {
        this.query = query;
        this.pageNum = pageNum;
        this.pageSize = pageSize;
    }

    public String getQuery() {
        return query;
    }

    public int getPageNum() {
        return pageNum;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setQuery(String query) {
        this.query = query;
    }

    public void setPageNum(int pageNum) {
        this.pageNum = pageNum;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    @Override
    public String toString() {
        return "QueryInfo{" +
                "query='" + query + '\'' +
                ",pageNum=" + pageNum +
                ",pageSize=" + pageSize +
                '}';
    }
}

3.2.2 在bean包下建立Showdate類

public class Showdate {
    private  String name;
    private  String itemStyle;
    private  int value;


    public Showdate() {

    }

    public Showdate(String name,String itemStyle,int value) {
        this.name = name;
        this.itemStyle = itemStyle;
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName1(String name) {
        this.name= name;
    }

    public String getItemStyle() {
        return itemStyle;
    }

    public void setItemStyle(String itemStyle) {
        this.itemStyle = itemStyle;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Showdate{" +
                "name='" + name + '\'' +
                ",itemStyle='" + itemStyle + '\'' +
                ",value=" + value +
                '}';
    }
}

3.2.3 在resources下建立Mapper

1.在Mapper中建立ShowDataMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.naughty.userlogin02.dao.ShowdateDao">


    <select id="getAlldate" resultType="com.naughty.userlogin02.bean.Showdate">
        SELECT * FROM date1
        <if test="name!=null ">
            WHERE name like #{name}
        </if>
        LIMIT #{pageStart},#{pageSize}
    </select>

    <update id="updatenew">
        UPDATE date1 SET value = #{count} WHERE name = #{name}
    </update>


</mapper>

2.在resources下建立application.yml用於配置資料庫和埠號

# mysql
spring:
  datasource:
    #MySQL配置
    driverClassName:  com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/weblog?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC
    username: root
    password: root

mybatis:
  mapper-locations: classpath:mapper/*.xml
  type-aliases-package: com.example.demo.model
server:
  port: 9000

3.2.4 在Dao下建立ShowdateDao

裡面有兩個介面,如果你需要操作資料庫,就需要在ShowdateDao中編寫介面方法;
在ShowDataMapper.xml中編寫sql語句。
我這裡實現了修改和查詢;

import com.naughty.userlogin02.bean.Showdate;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;

import java.util.List;
@Repository
public interface ShowdateDao {

    public List<Showdate> getAlldate(@Param("name") String name,@Param("pageStart") int pageStart,@Param("pageSize") int pageSize);

    public int updatenew(String name,int count);
}

3.2.5 在Controller下建立ShowdateController

在ShowdateController中要註解使用空間

   @Autowired
    ShowdateDao showdateDao;//你需要傳給前端的資料庫表
    @Autowired
    FlowDao flowDao;//你的資料來源的效果資料庫表
package com.naughty.userlogin02.controller;

import com.alibaba.fastjson.JSON;
import com.naughty.userlogin02.bean.*;
import com.naughty.userlogin02.dao.CheckDao;
import com.naughty.userlogin02.dao.FlowDao;
import com.naughty.userlogin02.dao.SafeDao;
import com.naughty.userlogin02.dao.ShowdateDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Stack;

@RestController
public class ShowdateController {

    @Autowired
    ShowdateDao showdateDao;
    @Autowired
    FlowDao flowDao;
//前臺重新整理日誌資料
    @CrossOrigin
    @RequestMapping("/alldate")//前端請求通道
    public String getAlldateList(QueryInfo queryInfo){
        System.out.println(queryInfo);
        int pageStart = (queryInfo.getPageNum()-1)*queryInfo.getPageSize();
        List<Showdate> dates = showdateDao.getAlldate("%"+queryInfo.getQuery()+"%",pageStart,queryInfo.getPageSize());
   
      for(int i =0;i<dates.size();i++){
          System.out.println(dates.get(i).toString());
      }
        //校驗
        //封裝校驗後的流量日誌
        HashMap<String,Object> res = new HashMap<>();
        res.put("flag","success");
        res.put("opinionData2",dates );
        String date_json= JSON.toJSONString(res);
        System.out.println(date_json.toString());
        return date_json;
    }

//資料庫資料來源的實現方法,就是改變資料庫表Date1中得資料
    @RequestMapping("/getupdata")
    public String updateDate(QueryInfo queryInfo){

        String s = "流量日誌異常";
        String s1 ="審計url異常";
        String s2 ="威脅攻擊日誌";
        String s3 ="正常網路日誌";
        /*int count = getUserList(queryInfo);
        int count1 =getChickList(queryInfo);  //四個方法需要你自己根據具體業務實現
        int count2 =getSafeDate(queryInfo);
        int count3 =allBlognum(queryInfo)-(count+count1+count2);*/
        showdateDao.updatenew(s,count);
        showdateDao.updatenew(s1,count1);
        showdateDao.updatenew(s2,count2);
        int i= showdateDao.updatenew(s3,count3);
        System.out.println("異常型別:"+s);
        System.out.println("異常日誌數量:"+count);
        String str = i >0?"success":"error";
        return str;
    }

}

3.2.6 修改前端介面

Js全部程式碼:

   <script>
     import * as echarts from 'echarts'
     export default {
       name: 'test2',opinionData2: [
     
//清空前端測試資料
           ]
         }
       },created() {
         this.getdateList();  //每次進入頁面重新整理資料庫資料實現動態資料繫結
      },methods: {
          async  drawLine () {
              // 呼叫post請求,獲得後臺資料庫的數值
      const { data: res } = await this.$http.get("alldate",{
        params: this.queryInfo
      });
      if (res.flag != "success") {
        return this.$message.error("該資料獲取失敗!!!");
      }

      console.log(res.flag)
       this.opinionData2 = res.opinionData2; // 將返回資料賦值
           this.myChart = echarts.init(document.getElementById('myChart'))
           this.myChart.setOption({
             title: {
               text: '網路日誌異常流量分析',// 副標題
               x: 'left' // x軸方向對齊方式
             },'#程式設計客棧3F8FFF'],color: ['#1FC48D',程式設計客棧   itemStyle: {
                   emphasis: {
                     shadowBlur: 10,async getdateList() {
      // 呼叫post請求
      const { data: res } = await this.$http.get("getupdata",{
        params: this.queryInfof
      });
      if (res != "success") {
        return this.$message.error("該資料獲取失敗!!!");
      }
      console.log(res)
        },}
     }
     </script>
     

在這裡插入圖片描述

後臺返回資料:

在這裡插入圖片描述

到此這篇關於Springboot運用vue+echarts前後端互動實現動態圓環圖的文章就介紹到這了,更多相關Springboot vue動態圓環圖 內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!