①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);
}
}