vue+springboot实现echarts数据图统计

①vue项目修改配置

 安装依赖:

npm i echarts -S

修改路由index.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Manager from '../views/Manager.vue'
// 解决导航栏或者底部导航tabBar中的vue-router在3.0版本以上频繁点击菜单报错的问题。
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push (location) {
  return originalPush.call(this, location).catch(err => err)
}
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'manager',
    component: Manager,
    children:[
      {path:'orders',name:'Orders',meta:{name:'订单管理'},component:()=>import('../views/manager/Orders.vue')},
      {path:'charts',name:'Charts',meta:{name:'数据统计'},component:()=>import('../views/manager/Charts.vue')},
      {path:'logs',name:'Logs',meta:{name:'系统日志'},component:()=>import('../views/manager/Logs.vue')},
      {path:'notice',name:'Notice',meta:{name:'系统公告'},component:()=>import('../views/manager/Notice.vue')},
      {path:'news',name:'News',meta:{name:'新闻信息'},component:()=>import('../views/manager/News.vue')},
      {path:'newsDetail',name:'NewsDetail',meta:{name:'新闻详情页'},component:()=>import('../views/manager/NewsDetail.vue')},
      {path:'home',name:'Home',meta:{ name:'系统首页' },component:()=>import('../views/manager/Home.vue')},
      {
        path:'user',name:'User',meta:{ name:'用户信息' },component:()=>import('../views/manager/User.vue')
      },
      {
        path:'403',name:'Auth',meta:{ name:'无权限' },component:()=>import('../views/Auth.vue')
      },
      {
        path:'Person',name:'person',meta:{ name:'个人信息' },component:()=>import('../views/manager/Person.vue')
      },
      {
        path:'Password',name:'password',meta:{ name:'修改密码' },component:()=>import('../views/manager/Password.vue')
      }
    ],
    redirect:'/home'
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  {
    path:'/login',
    name:'login',
    meta:{ name:'登录' },
    component: ()=>import('../views/login.vue')
  },
  {
    path:'/register',
    name:'register',
    meta:{ name:'注册' },
    component: ()=>import('../views/register.vue')
  },
  {
    path:'*',
    name:'404',
    meta:{ name:'无法访问' },
    component: ()=>import('../views/404.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to,from,next)=>{
  let adminPaths=['/user']
  let user=JSON.parse(localStorage.getItem('honey-user')||'{}')
  if(user.role !== '管理员' && adminPaths.includes(to.path)){
    next('/403')
  }else{
    next()
  }
})
export default router

修改Manager.vue:

<template>
  <div>
    <el-container>
      <!--    侧边栏  -->
      <el-aside :width="asideWidth" style="min-height: 100vh; background-color: #001529">
        <div style="height: 60px; color: white; display: flex; align-items: center; justify-content: center">
          <img src="@/assets/logo1.png" alt="" style="width: 40px; height: 40px">
          <span class="logo-title" v-show="!isCollapse">honey2024</span>
        </div>

        <el-menu :default-openeds="['info']" :collapse="isCollapse" :collapse-transition="false" router background-color="#001529" text-color="rgba(255, 255, 255, 0.65)" active-text-color="#fff" style="border: none" :default-active="$route.path">
          <el-menu-item index="/home">
            <i class="el-icon-s-home"></i>
            <span slot="title">系统首页</span>
          </el-menu-item>
          <el-submenu index="info" >
            <template slot="title">
              <i class="el-icon-menu"></i>
              <span>信息管理</span>
            </template>
            <el-menu-item index="/user" v-if="user.role === '管理员'">用户信息</el-menu-item>
            <el-menu-item index="/news" v-if="user.role === '管理员'">新闻信息</el-menu-item>
            <el-menu-item index="/notice" v-if="user.role === '管理员'">系统公告</el-menu-item>
            <el-menu-item index="/logs" v-if="user.role === '管理员'">系统日志</el-menu-item>
            <el-menu-item index="/charts" v-if="user.role === '管理员'">数据统计</el-menu-item>
            <el-menu-item index="/orders">订单管理</el-menu-item>
          </el-submenu>

        </el-menu>

      </el-aside>

      <el-container>
        <!--        头部区域-->
        <el-header>

          <i :class="collapseIcon" style="font-size: 26px" @click="handleCollapse"></i>
          <el-breadcrumb separator-class="el-icon-arrow-right" style="margin-left: 20px">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: $route.path }">{{ $route.meta.name }}</el-breadcrumb-item>
          </el-breadcrumb>

          <div style="flex: 1; width: 0; display: flex; align-items: center; justify-content: flex-end">
            <i class="el-icon-quanping" style="font-size: 26px" @click="handleFull"></i>
            <el-dropdown placement="bottom">
              <div style="display: flex; align-items: center; cursor: default">
                <img :src="user.avatar||'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" alt="" style="width: 40px; height: 40px; margin: 0 5px;border-radius: 50%">
                <span>{{user.name}}</span>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="$router.push('/person')">个人信息</el-dropdown-item>
                <el-dropdown-item @click.native="$router.push('/password')">修改密码</el-dropdown-item>
                <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>

        </el-header>

        <!--        主体区域-->
        <el-main>
          <router-view @update:user="updateUser"></router-view>
        </el-main>

      </el-container>


    </el-container>
  </div>
</template>

<script>
import axios from "axios";
import request from '@/utils/request'

export default {
  name: 'HomeView',
  data() {
    return {
      isCollapse: false,  // 不收缩
      asideWidth: '200px',
      collapseIcon: 'el-icon-s-fold',
      user:JSON.parse(localStorage.getItem('honey-user')||'{}'),
    }
  },
  mounted() {
    if(!this.user.id){
      this.$router.push('/login')
    }
    // axios.get('http://localhost:9090/user/selectall').then(res=>{
    //   console.log(res.data);
    //   this.users=res.data.data
    // })

    // request.get('/user/selectall').then(res => {
    //   this.users = res.data
    // })
  },
  methods: {
    updateUser(user){
      this.user=JSON.parse(JSON.stringify(user))
    },
    handleFileUpload(response,file,fileList){
      this.fileList=fileList
      console.log(response,file,fileList)
    },
    logout() {
      localStorage.removeItem("honey-user")
      this.$router.push('/login')
    },
    handleFull() {
      document.documentElement.requestFullscreen()
    },
    handleCollapse() {
      this.isCollapse = !this.isCollapse
      this.asideWidth = this.isCollapse ? '64px' : '200px'
      this.collapseIcon = this.isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'
    }
  }
}
</script>

<style>
.el-menu--inline {
  background-color: #000c17 !important;
}

.el-menu--inline .el-menu-item {
  background-color: #000c17 !important;
  padding-left: 49px !important;
}

.el-menu-item:hover, .el-submenu__title:hover {
  color: #fff !important;
}

.el-submenu__title:hover i {
  color: #fff !important;
}

.el-menu-item:hover i {
  color: #fff !important;
}

.el-menu-item.is-active {
  background-color: #1890ff !important;
  border-radius: 5px !important;
  width: calc(100% - 8px);
  margin-left: 4px;
}

.el-menu-item.is-active i, .el-menu-item.is-active .el-tooltip {
  margin-left: -4px;
}

.el-menu-item {
  height: 40px !important;
  line-height: 40px !important;
}

.el-submenu__title {
  height: 40px !important;
  line-height: 40px !important;
}

.el-submenu .el-menu-item {
  min-width: 0 !important;
}

.el-menu--inline .el-menu-item.is-active {
  padding-left: 45px !important;
}

/*.el-submenu__icon-arrow {*/
/*  margin-top: -5px;*/
/*}*/

.el-aside {
  transition: width .3s;
  box-shadow: 2px 0 6px rgba(0, 21, 41, .35);
}

.logo-title {
  margin-left: 5px;
  font-size: 20px;
  transition: all .3s; /* 0.3s */
}

.el-header {
  box-shadow: 2px 0 6px rgba(0, 21, 41, .35);
  display: flex;
  align-items: center;
}
</style>

新建Charts.vue:

 

Charts.vue:静态版

<template>
<div>
  <el-row :gutter="10">
    <el-col :span="12">
      <el-card>
        <div style="height: 400px;width: 100%" id="line"></div>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card>
        <div style="height: 400px;width: 100%" id="bar"></div>
      </el-card>
    </el-col>
  </el-row>

  <el-row :gutter="10" style="margin: 10px 0">
    <el-col :span="12">
      <el-card>
        <div style="height: 400px;width: 100%" id="pie"></div>
      </el-card>
    </el-col>
  </el-row>>
</div>
</template>
<script>
import * as echarts from 'echarts';
const option = {
  title: {
    text: '订单金额统计图',
    left:'center'
  },
  legend: {
    left: 'left'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name:'金额',
      data: [150, 230, 224, 218, 135, 147, 260],
      type: 'line',
      smooth:true
    },
    {
      name:'库存',
      data: [15, 20, 22, 21, 110, 160, 225],
      type: 'line',
      smooth:true
    }
  ]
};
const option1 = {
  title: {
    text: '订单金额柱状图',
    left:'center'
  },
  legend: {
    left: 'left'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['水果', '零食', '奶制品', '饮料', '生活用品']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name:'金额',
      data: [15000, 23000, 224000, 21800, 13500, 14700, 26000],
      type: 'bar',
      smooth:true
    },
    {
      name:'销量',
      data: [1500, 2000, 2200, 2100, 11000, 16000, 22500],
      type: 'bar',
      smooth:true
    }
  ]
};
const option2={
  title: {
    text: '订单销售比例图',
    subtext: '比例图',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: 'Access From',
      type: 'pie',
      center:['50%','60%'],
      radius: '50%',
      data: [
        { value: 1048, name: 'Search Engine' },
        { value: 735, name: 'Direct' },
        { value: 580, name: 'Email' },
        { value: 484, name: 'Union Ads' },
        { value: 300, name: 'Video Ads' }
      ],
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};
export default {
  data(){},
  mounted() {
    let lineDom = document.getElementById('line');
    let lineChart = echarts.init(lineDom);
    lineChart.setOption(option)
    let barDom = document.getElementById('bar');
    let barChart = echarts.init(barDom);
    barChart.setOption(option1)
    let pieDom = document.getElementById('pie');
    let pieChart = echarts.init(pieDom);
    pieChart.setOption(option2)
  }
}
</script>
<style scoped>

</style>

新建Orders.vue:

<template>
  <div>
    <div>
      <el-input style="width: 200px" placeholder="查询名称" v-model="name"></el-input>
      <el-button type="primary" style="margin-left: 10px" @click="load(1)">查询</el-button>
      <el-button type="info" @click="reset">重置</el-button>
    </div>
    <div style="margin: 10px 0">
      <el-button type="primary" plain @click="handleAdd">新增</el-button>
      <el-button type="danger" plain @click="delBatch">批量删除</el-button>
    </div>
    <el-table :data="tableData" stripe :header-cell-style="{ backgroundColor: 'aliceblue', color: '#666' }" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column prop="id" label="序号" width="70" align="center"></el-table-column>
      <el-table-column prop="no" label="编号"></el-table-column>
      <el-table-column prop="name" label="订单名称"></el-table-column>
      <el-table-column prop="money" label="金额" show-overflow-tooltip></el-table-column>
      <el-table-column prop="user" label="用户"></el-table-column>
      <el-table-column prop="date" label="创建时间"></el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template v-slot="scope">
          <el-button size="mini" type="primary" plain @click="handleEdit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" plain @click="del(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="margin: 10px 0">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="pageNum"
          :page-size="pageSize"
          layout="total, prev, pager, next"
          :total="total">
      </el-pagination>
    </div>

    <el-dialog title="公告信息" :visible.sync="fromVisible" width="40%" :close-on-click-modal="false">
      <el-form :model="form" label-width="80px" style="padding-right: 20px" :rules="rules" ref="formRef">
        <el-form-item label="订单名称" prop="name">
          <el-input v-model="form.name" placeholder="名称"></el-input>
        </el-form-item>
        <el-form-item label="订单金额" prop="money">
          <el-input type="textarea" v-model="form.money" placeholder="金额"></el-input>
        </el-form-item>
        <el-form-item label="订单分类" prop="money">
          <el-select style="width: 100%" v-model="form.category">
            <el-option v-for="item in ['水果','蔬菜','零食','饮料','奶制品','糕点']" :key="item" :value="item"></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="fromVisible = false">取 消</el-button>
        <el-button type="primary" @click="save">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: "Orders",
  data() {
    return {
      tableData: [],  // 所有的数据
      pageNum: 1,   // 当前的页码
      pageSize: 5,  // 每页显示的个数
      username: '',
      name: '',
      total: 0,
      fromVisible: false,
      form: {},
      user: JSON.parse(localStorage.getItem('honey-user') || '{}'),
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
        ],
        money: [
          { required: true, message: '请输入金额', trigger: 'blur' },
        ],
        category: [
          { required: true, message: '请输入分类', trigger: 'blur' },
        ],
      },
      ids: [],
      content:'',
    }
  },
  created() {
    this.load()
  },
  methods: {
    delBatch() {
      if (!this.ids.length) {
        this.$message.warning('请选择数据')
        return
      }
      this.$confirm('您确认批量删除这些数据吗?', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/orders/delete/batch', { data: this.ids }).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {})
    },
    handleSelectionChange(rows) {   // 当前选中的所有的行数据
      this.ids = rows.map(v => v.id)
    },
    del(id) {
      this.$confirm('您确认删除吗?', '确认删除', {type: "warning"}).then(response => {
        this.$request.delete('/orders/delete/' + id).then(res => {
          if (res.code === '200') {   // 表示操作成功
            this.$message.success('操作成功')
            this.load(1)
          } else {
            this.$message.error(res.msg)  // 弹出错误的信息
          }
        })
      }).catch(() => {})
    },
    handleEdit(row) {   // 编辑数据
      this.form = JSON.parse(JSON.stringify(row))  // 给form对象赋值  注意要深拷贝数据
      this.fromVisible = true   // 打开弹窗
    },
    handleAdd() {   // 新增数据
      this.form = {}  // 新增数据的时候清空数据
      this.fromVisible = true   // 打开弹窗
    },
    save() {
      // 保存按钮触发的逻辑  它会触发新增或者更新
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          this.sendSaveRequest();
        }
      })
    },
    sendSaveRequest(){
      this.$request({
        url: this.form.id ? '/orders/update': '/orders/add',
        method: this.form.id ? 'PUT' : 'POST',
        data: this.form
      }).then(res => {
        if (res.code === '200') {  // 表示成功保存
          this.$message.success('保存成功')
          this.load(1)
          this.fromVisible = false
        } else {
          this.$message.error(res.msg)  // 弹出错误的信息
        }
      })
    },
    reset() {
      this.name = ''
      this.load()
    },
    load(pageNum) {  // 分页查询
      if (pageNum)  this.pageNum = pageNum
      this.$request.get('/orders/selectByPage', {
        params: {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          name: this.name
        }
      }).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total
      })
    },
    handleCurrentChange(pageNum) {
      this.load(pageNum)
    },
  }
}
</script>

<style>
.el-tooltip__popper{
  width: 200px !important;
}
</style>

 Charts.vue:动态版

<template>
<div>
  <el-row :gutter="10">
    <el-col :span="12">
      <el-card>
        <div style="height: 400px;width: 100%" id="line"></div>
      </el-card>
    </el-col>
    <el-col :span="12">
      <el-card>
        <div style="height: 400px;width: 100%" id="bar"></div>
      </el-card>
    </el-col>
  </el-row>

  <el-row :gutter="10" style="margin: 10px 0">
    <el-col :span="12">
      <el-card>
        <div style="height: 400px;width: 100%" id="pie"></div>
      </el-card>
    </el-col>
  </el-row>>
</div>
</template>
<script>
import * as echarts from 'echarts';
const option = {
  title: {
    text: '订单金额统计图',
    left:'center'
  },
  legend: {
    left: 'left'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name:'金额',
      data: [],
      type: 'line',
      smooth:true
    },
  ]
};
const option1 = {
  title: {
    text: '订单金额柱状图',
    left:'center'
  },
  legend: {
    left: 'left'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name:'金额',
      data: [],
      type: 'bar',
      smooth:true
    },
  ]
};
const option2={
  title: {
    text: '订单销售比例图',
    subtext: '比例图',
    left: 'center'
  },
  tooltip: {
    trigger: 'item'
  },
  legend: {
    orient: 'vertical',
    left: 'left'
  },
  series: [
    {
      name: '金额',
      type: 'pie',
      center:['50%','60%'],
      radius: '50%',
      data: [],
      label:{
        show:true,
        formatter(param){
          return param.name+'('+param.percent+'%)';
        }
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowOffsetX: 0,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }
  ]
};
export default {
  data(){},
  mounted() {
    let lineDom = document.getElementById('line');
    let lineChart = echarts.init(lineDom);
    let barDom = document.getElementById('bar');
    let barChart = echarts.init(barDom);
    let pieDom = document.getElementById('pie');
    let pieChart = echarts.init(pieDom);
    pieChart.setOption(option2)
    this.$request.get('/charts').then(res=>{
      option.xAxis.data=res.data?.line?.map(v=>v.date)||[]
      option.series[0].data=res.data?.line?.map(v=>v.value)||[]
      lineChart.setOption(option)
      option1.xAxis.data=res.data?.bar?.map(v=>v.name)||[]
      option1.series[0].data=res.data?.bar?.map(v=>v.value)||[]
      barChart.setOption(option1)
      option2.series[0].data=res.data?.bar||[]
      pieChart.setOption(option2)
    })
  }
}
</script>
<style scoped>

</style>

②后端配置

 新建数据库:

CREATE TABLE `orders` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `no` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '订单编号',
  `name` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '订单名称',
  `money` decimal(10,2) DEFAULT NULL COMMENT '订单金额',
  `userid` int(11) DEFAULT NULL COMMENT '用户ID',
  `category` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '订单分类',
  `date` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '订单日期',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='订单表';

 springboot项目中创建Orders实体类

package com.example.springboot.entity;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;

@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class Orders {
    @TableId(type = IdType.AUTO)
    private Integer id;
    private String no;
    private String name;
    private BigDecimal money;
    private Integer userid;
    private String category;
    private String date;
    @TableField(exist = false)
    private String user;
}

创建OrdersMapper:

 

package com.example.springboot.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.example.springboot.entity.Logs;
import com.example.springboot.entity.Orders;

public interface OrdersMapper extends BaseMapper<Orders> {

}

创建OrdersService:

package com.example.springboot.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.springboot.entity.Logs;
import com.example.springboot.entity.Orders;
import com.example.springboot.mapper.LogsMapper;
import com.example.springboot.mapper.OrdersMapper;
import org.springframework.stereotype.Service;

@Service
public class OrdersService extends ServiceImpl<OrdersMapper, Orders> {

}

创建OrdersController:

 

package com.example.springboot.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Orders;
import com.example.springboot.entity.User;
import com.example.springboot.service.OrdersService;
import com.example.springboot.service.UserService;
import com.example.springboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/orders")
public class OrdersController {

    @Autowired
    OrdersService ordersService;

    @Autowired
    UserService userService;

    /**
     * 新增信息
     */
    @HoneyLogs(operation = "订单",type= LogType.ADD)
    @PostMapping("/add")
    public Result add(@RequestBody Orders orders) {
        User currentUser= TokenUtils.getCurrentUser();
        orders.setUserid(currentUser.getId());
        orders.setDate(DateUtil.today());
        orders.setNo(IdUtil.fastSimpleUUID());
        ordersService.save(orders);
        return Result.success();
    }

    /**
     * 修改信息
     */
    @HoneyLogs(operation = "订单",type= LogType.UPDATE)
    @PutMapping("/update")
    public Result update(@RequestBody Orders orders) {
        ordersService.updateById(orders);
        return Result.success();
    }

    /**
     * 删除信息
     */
    @HoneyLogs(operation = "订单",type= LogType.DELETE)
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        ordersService.removeById(id);
        return Result.success();
    }


    /**
     * 批量删除信息
     */
    @HoneyLogs(operation = "订单",type= LogType.BATCH_DELETE)
    @DeleteMapping("/delete/batch")
    public Result batchDelete(@RequestBody List<Integer> ids) {
        ordersService.removeBatchByIds(ids);
        return Result.success();
    }

    /**
     * 查询全部信息
     */
    @GetMapping("/selectAll")
    public Result selectAll() {
        List<Orders> ordersList = ordersService.list(new QueryWrapper<Orders>().orderByDesc("id"));
        return Result.success(ordersList);
    }

    @GetMapping("/selectUserData")
    public Result selectUserData() {
        QueryWrapper<Orders> queryWrapper=new QueryWrapper<Orders>().orderByDesc("id");
        queryWrapper.eq("open",1);
        List<Orders> userList = ordersService.list(queryWrapper);
        return Result.success(userList);
    }

    /**
     * 根据ID查询信息
     */
    @GetMapping("/selectById/{id}")
    public Result selectById(@PathVariable Integer id) {
        Orders orders = ordersService.getById(id);
        User user=userService.getById(orders.getUserid());
        if(user!=null){
            orders.setUser(user.getName());
        }
        return Result.success(orders);
    }


    /**
     * 多条件模糊查询信息
     * pageNum 当前的页码
     * pageSize 每页查询的个数
     */
    @GetMapping("/selectByPage")
    public Result selectByPage(@RequestParam Integer pageNum,
                               @RequestParam Integer pageSize,
                               @RequestParam String name) {
        QueryWrapper<Orders> queryWrapper = new QueryWrapper<Orders>().orderByDesc("id");  // 默认倒序,让最新的数据在最上面
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        Page<Orders> page = ordersService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<Orders> records=page.getRecords();
//        List<User> list=userService.list();
        for(Orders record:records){
            Integer authorid=record.getUserid();
            User user=userService.getById(authorid);
//            String author=list.stream().filter(u->u.getId().equals(authorid)).findFirst().map(User::getName).orElse("");
            if(user!=null){
                record.setUser(user.getName());
            }
        }
        return Result.success(page);
    }


}

修改WebController:

package com.example.springboot.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import com.example.springboot.common.AuthAccess;
import com.example.springboot.common.HoneyLogs;
import com.example.springboot.common.LogType;
import com.example.springboot.common.Result;
import com.example.springboot.entity.Orders;
import com.example.springboot.entity.User;
import com.example.springboot.exception.ServiceException;
import com.example.springboot.service.OrdersService;
import com.example.springboot.service.UserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
public class WebController {
    @Resource
    UserService userService;
    @Resource
    OrdersService ordersService;
    @AuthAccess
    @GetMapping("/")
    public Result hello(){
        return Result.success("success");
    }

    @HoneyLogs(operation = "用户",type = LogType.LOGIN)
    @PostMapping("/login")
    public Result login(@RequestBody User user){
        if(StrUtil.isBlank(user.getUsername())||StrUtil.isBlank(user.getPassword())){
            return Result.error("数据输入错误");
        }
        user=userService.login(user);
        return Result.success(user);
    }

    @HoneyLogs(operation = "用户",type = LogType.REGISTER)
    @AuthAccess
    @PostMapping("/register")
    public Result register(@RequestBody User user){
        if(StrUtil.isBlank(user.getUsername())||StrUtil.isBlank(user.getPassword())){
            throw new ServiceException("输入不合法");
        }
        if(user.getUsername().length()>10||user.getPassword().length()>20){
            throw new ServiceException("长度过长");
        }
        user=userService.register(user);
        return Result.success(user);
    }
    @HoneyLogs(operation = "用户",type = LogType.UPDATE)
    @AuthAccess
    @PutMapping("/password")
    public Result password(@RequestBody User user){
        if(StrUtil.isBlank(user.getUsername())||StrUtil.isBlank(user.getPhone())){
            throw new ServiceException("输入不合法");
        }
        userService.resetPassword(user);
        return Result.success();
    }

    @GetMapping("/charts")
    public Result charts(){
        List<Orders> list = ordersService.list();
        Set<String> dates=list.stream().map(Orders::getDate).collect(Collectors.toSet());
        List<String> dateList=CollUtil.newArrayList(dates);
        dateList.sort(Comparator.naturalOrder());
        List<Dict> lineList=new ArrayList<>();
        for(String date:dates){
            BigDecimal sum=list.stream().filter(orders -> orders.getDate().equals(date)).map(Orders::getMoney).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            Dict dict=Dict.create();
            Dict line=dict.set("date",date).set("value",sum);
            lineList.add(line);
        }
        Set<String> categories=list.stream().map(Orders::getCategory).collect(Collectors.toSet());
        List<Dict> barList=new ArrayList<>();
        for(String category:categories){
            BigDecimal sum=list.stream().filter(orders -> orders.getCategory().equals(category)).map(Orders::getMoney).reduce(BigDecimal::add).orElse(BigDecimal.ZERO);
            Dict dict=Dict.create();
            Dict bar=dict.set("name",category).set("value",sum);
            barList.add(bar);
        }
        Dict res=Dict.create().set("line",lineList).set("bar",barList);
        return Result.success(res);
    }
}

 

 

 

 

 

 

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/632952.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

【编译原理复习笔记】语法分析-补充(二义性与LR错误处理)

二义性文法的 LR 分析 每个二义性文法都不是 LR 的 但是某些二义性文法更加简短&#xff0c;描述更方便 如 I7 和 I8 具有移进归约冲突 使用优先级和结合性解决冲突 对于 I7&#xff0c;由于乘号优先级高于加号&#xff0c;所以当下一个输入符号为乘号时&#xff0c;我们优…

03-02-Vue组件之间的传值

前言 我们接着上一篇文章 03-01-Vue组件的定义和注册 来讲。 下一篇文章 04-Vue&#xff1a;ref获取页面节点–很简单 父组件向子组件传值 我们可以这样理解&#xff1a;Vue实例就是一个父组件&#xff0c;而我们自定义的组件&#xff08;包括全局组件、私有组件&#xff09;…

Java基础入门day49

day49 tomcat 启动 进入tomcat的bin目录&#xff0c;双击或者运行startup.bat文件启动tomcat 控制台最后出现服务器启动在多少毫米之内&#xff0c;代表服务器成功启动 org.apache.catalina.startup.Catalina.start Server startup in 405 ms 验证tomcat 在浏览器中输入 loca…

linux---进程通信

提示&#xff1a;以下是本篇文章正文内容&#xff0c;下面案例可供参考 一、匿名管道 进程之间的通信目的一般是来控制另一个进程。也可以用来实现数据的交流&#xff0c;还有资源共享等。 匿名管道原理&#xff1a; &#xff08;铺垫&#xff09;进程之间是具有独立性&…

超市进销存|基于SprinBoot+vue的超市进销存系统(源码+数据库+文档)

超市进销存系统 目录 基于SprinBootvue的超市进销存系统 一、前言 二、系统设计 三、系统功能设计 1 登录注册 2 管理员功能模块 3员工功能模块 四、数据库设计 五、核心代码 六、论文参考 七、最新计算机毕设选题推荐 八、源码获取&#xff1a; 博主介绍&#x…

【时间复杂度和空间复杂度之间的故事】

【时间复杂度和空间复杂度之间的故事】 一.前言 二.时间复杂度定义时间复杂度的计算规则习题 三.空间复杂度定义计算方法习题空间复杂度 O(1)空间复杂度 O(n) 本文主要讲解关于时间复杂度与空间复杂度 &#x1f600;&#x1f603;&#x1f601;&#x1f601;&#x1f607;&…

桂林电子科技大学计算机工程学院、广西北部湾大学计信学院莅临泰迪智能科技参观交流

5月18日&#xff0c;桂林电子科技大学计算机工程学院副院长刘利民、副书记杨美娜、毕业班辅导员黄秀娟、广西北部湾大学计信学院院长助理刘秀平莅临广东泰迪智能科技股份有限公司产教融合实训基地参观交流。泰迪智能科技副总经理施兴、广西分公司郑廷和、梁霜、培训业务部孙学镂…

Outlook 开启smtp配置

微软 Outlook 邮箱各种服务详细信息 服务类型服务器地址端口加密方法POPoutlook.office365.com995TLSIMAPoutlook.office365.com993TLSSMTPsmtp.office365.com587STARTTLS 然而仅仅有以上信息还不够&#xff0c;需要获取服务密码 (授权码) 才能够使用 POP, IMAP, SMTP 这三种…

常见应用流量特征分析

目录 1.sqlmap 1.常规GET请求 2.通过--os-shell写入shell 3.post请求 2.蚁剑 编码加密后 3.冰蝎 冰蝎_v4.1 冰蝎3.2.1 4.菜刀 5.哥斯拉 1.sqlmap 1.常规GET请求 使用的是sqli-labs的less7 &#xff08;1&#xff09;User-Agent由很明显的sqlmap的标志&#xff0c;展…

基础常用动词,柯桥西班牙语培训

1. Ser&#xff1a;是 表示身份: Soy Ana. Soy estudiante. 我是安娜。我是一名学生。 表示属性: Es duro. 这是硬的。 表示国籍: Soy espaol, de Madrid. 我是西班牙人&#xff0c;来自马德里。 2. Estar: 是..., 在... 表示身体状况: Estoy muy cansada, necesito dormir.我很…

JMH301【亲测】5月最新整理【神鬼传奇】斗罗超变单机版175级新宠物宝宝坐骑丰富超变定制装备带完整GM命令网游单机虚拟机一键端

资源介绍&#xff1a; 是否需要虚拟机&#xff1a;是 文件大小&#xff1a;压缩包约8.6G 支持系统&#xff1a;win7、win10、win11 硬件需求&#xff1a;运行内存8G 4核及以上CPU 下载方式&#xff1a;百度网盘 内容持续更新&#xff01; 资源截图&#xff1a; 下载地址…

DataBinding viewBinding(视图绑定与数据双向绑定)简单案例 (kotlin)

先上效果&#xff1a; 4个view的文字都是通过DataBinding填充的。交互事件&#xff1a;点击图片&#xff0c;切换图片 创建项目&#xff08;android Studio 2023.3.1&#xff09; Build.gradle(:app) 引入依赖库&#xff08;完整源码&#xff09; buildFeatures { vie…

Docker访问文件权限受限问题解决

问题描述 运行项目的docker环境&#xff0c;新添加了一个数据集&#xff0c;但是数据集的访问权限受限&#xff08;Permission dinied&#xff09;&#xff0c;运行的命令如图所示 问题解决 chmod 777 xxx YYDS&#xff01;&#xff01;&#xff01;但是单纯直接运行会因为权限…

产品经理-交互说明撰写(八)

1. 交互说明 交互说明可以看做是交互设计师或者产品经理输出的最核心的”产品“交互说明面向的”用户“是下游的同事 ⇒ UI设计师、开发工程师、测试工程师 2. 基本交互形式 2.1 页面交互 2.2 元素控件交互 3. 交互说明主要包括以下3个维度 3.1 页面流程&#xff08;页面之…

OpenFeign高级用法:缓存、QueryMap、MatrixVariable、CollectionFormat优雅地远程调用

码到三十五 &#xff1a; 个人主页 微服务架构中&#xff0c;服务之间的通信变得尤为关键。OpenFeign&#xff0c;一个声明式的Web服务客户端&#xff0c;使得REST API的调用变得更加简单和优雅。OpenFeign集成了Ribbon和Hystrix&#xff0c;具有负载均衡和容错的能力&#xff…

在 Android 上存档短信:4 种方法的终极指南

概括 无论是个人对话还是专业信件&#xff0c;我们的短信收件箱很快就会因大量线程和对话而变得混乱。为了帮助管理这种过载&#xff0c;许多 Android 用户转向了归档短信这一便捷功能。在本指南中&#xff0c;我们将探讨如何在 Android 设备上存档短信的详细信息&#xff0c;…

Django中使用Celery(通用方案、官方方案)

Django中使用Celery&#xff08;通用方案、官方方案&#xff09; 目录 Django中使用Celery&#xff08;通用方案、官方方案&#xff09;通用方案场景前置准备完整代码 Celery官方方案【1】注册celery配置【2】创建celery文件【3】init注册【4】添加任务【5】启动worker异步任务…

【qt】下拉列表组件

下拉列表组件 一.Combo Box1.可以直接双击编辑下拉内容2.代码初始化下拉内容3.一次性添加多个下拉内容4.下拉框手动编辑5.下拉内容添加附加值6.下拉添加图标7.获取下拉值 二.总结 一.Combo Box 还是老样子&#xff0c;咱们边做边练 目标图&#xff1a; 1.可以直接双击编辑下…

ThreadLocal原理及使用

一、引言 在Java多线程编程中&#xff0c;ThreadLocal是一个非常有用的工具&#xff0c;它提供了一种将对象与线程关联起来的机制&#xff0c;使得每个线程都可以拥有自己独立的对象副本&#xff0c;从而避免了线程安全问题。然而&#xff0c;使用不当会导致内存泄漏问题。 二…

el-input 自动获取焦点

前言&#xff1a; 需求描述&#xff1a;在 Dialog 对话框中 使用 input 组件&#xff1b;当点击按钮&#xff0c;Dialog 对话框显示&#xff0c;且里面的 input 组件要自动获取焦点。因为页面上还存在其他的 input 组件&#xff0c;所以使用 自动获取焦点属性没用&#xff01;&…