上一篇案例中也是查询到了表单的内容–>前后端分离学习笔记(4) —[路由嵌套, 查询表单显示]
1.前端组件页面
添加管理员操作
要达到点击新增按钮弹出对话框的效果
(1)打开对话框时,会去查询角色信息表,生成角色复选框;
(2)提交表单时,有简单的表单盐验证; 注意最后保存数据时,分两步;首先把管理员信息存入管理员表;这时会得到添加的管理员Id; 然后根据Id和填写的角色ID;将管理员与角色的关联关系存入到管理角色关联表
添加管理员时的表单验证效果
首先新建Add.vue作为添加管理员的组件页面 Add.vue 组件代码;其实就是对话框中嵌套了表单
<template>
<!-- 在此组件中 制作一个对话框 -->
<el-dialog title="新增管理员" :visible.sync="dialogVisible" width="50%">
<!-- 添加管理员的表单信息-->
<el-form :model="form" :rules="rules" ref="form" label-width="100px" class="demo-ruleForm">
<el-form-item label="账号" prop="account">
<el-input v-model="form.account"></el-input>
</el-form-item>
<el-form-item label="手机" prop="phone">
<el-input v-model="form.phone"></el-input>
</el-form-item>
<el-form-item label="性别" prop="sex">
<el-radio v-model="form.sex" label="男">男</el-radio>
<el-radio v-model="form.sex" label="女">女</el-radio>
</el-form-item>
<!-- <el-form-item label="时间">
<el-date-picker type="date" v-model="form.birthday" placeholder="选择日期"> </el-date-picker>
</el-form-item> -->
<el-form-item label="角色" prop="roleId">
<el-checkbox-group v-model="form.roleId">
<!--复选框存入不同的角色 -->
<el-checkbox v-for="role in roles" :label="role.id" :key="role.id">{{role.name}}</el-checkbox>
</el-checkbox-group>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="save('form')">保存</el-button>
<el-button @click="resetForm('form')">重置</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
name: "AddDialog",
data() {
return {
dialogVisible: false,
form: {
account: "",
sex: "男",
phone: "",
roleId: []
},
roles: [],
rules: {
account: [{
required: true,
message: '请输入账户名',
trigger: 'blur'
},
{
min: 3,
max: 5,
message: '长度在 3 到 5 个字符',
trigger: 'blur'
}
],
phone: [{
required: true,
message: '请输入手机号',
trigger: 'blur'
},
{
min: 11,
max:11,
message: '手机号限制11位',
trigger: 'blur'
}
],
roleId: [{
type: 'array',
required: true,
message: '请至少选择一个角色',
trigger: 'change'
}]
},
};
},
methods: {
save(form) {
var _this = this;
this.$refs[form].validate((valid) => {
if (valid) {
this.$http.post("admin/addAdmin", this.form).then(function(resp) {
if (resp.data.code === 200) {
_this.$message({
message: resp.data.msg,
type: 'success'
});
window.location.reload();
}
});
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
},
created() {
var _this = this;
this.$http.get("admin/roles").then(function(resp) {
_this.roles = resp.data.data;
})
}
};
</script>
<style>
</style>
注意这个组件要给个命名;
然后,需要在管理员列表组件AdminList.vue组件中打开这个对话框;那么 AdminList.vue组件 就是个父级组件;而新增管理员的Add.vue组件 就是子级组件;
注意;点击新增按钮时,调用子级组件Add.vue 中的属性;让对话框显示出现
AdminList.vue组件 代码
<template>
<el-card class="box-card" style="background-color: #E9EEF3;">
<div slot="header" class="clearfix">
<span>管理员列表</span>
<el-button style="float: right; padding: 10px 10px" type="success" @click="openAddAdmin()">新增</el-button>
</div>
<div class="text">
<!-- 查询条件框-->
<div class="clearfix" style="padding-bottom: 10px;">
<!-- 查询条件-->
<el-row :gutter="20">
<el-col :span="6">
<el-input placeholder="账号" v-model="query.account"></el-input>
</el-col>
<el-col :span="6">
<el-input placeholder="性别" v-model="query.sex"></el-input>
</el-col>
<el-col :span="6">
<el-button type="primary" icon="el-icon-search" @click="search()">搜索</el-button>
</el-col>
</el-row>
</div>
<!-- 数据表格位置-->
<el-table
v-loading="loading"
element-loading-text="拼命加载中"
element-loading-spinner="el-icon-loading"
element-loading-background="rgba(0, 0, 0, 0.8)"
:data="tableData" style="width: 100%" border max-height="450">
<el-table-column fixed type="index" label="编号" width="60">
</el-table-column>
<el-table-column prop="account" label="账号" width="100"></el-table-column>
<el-table-column prop="newFileName" label="头像" width="60">
<template slot-scope="scope">
<!-- 若没有头像,则显示默认头像 -->
<img v-bind:src="http+'default/admin.png'" width="30" height="30"
v-if="scope.row.newFileName === null " />
<!-- 否则显示管理员的头像 -->
<img v-bind:src="http+scope.row.account+'/'+scope.row.newFileName" width="30" height="30"
v-else />
</template>
</el-table-column>
<el-table-column prop="sex" label="性别" width="50"></el-table-column>
<el-table-column prop="phone" label="手机" width="120"></el-table-column>
<el-table-column prop="type" label="类型" width="120" :formatter="formatType"></el-table-column>
<el-table-column prop="roleList" label="角色" width="250" align="center">
<template slot-scope="scope">
<span v-for="(role,index) in scope.row.roleList" :key="index">{{role.name}}-</span>
</template>
</el-table-column>
<!-- 时间加上排序 -->
<el-table-column prop="operTime" label="时间" width="200" :formatter="formatTime" sortable>
</el-table-column>
<el-table-column fixed="right" label="操作" width="200">
<template slot-scope="scope">
<el-button size="mini" @click="toUpdate(scope.row.id)">编辑</el-button>
<el-button size="mini" type="danger" @click="toDelAdmin(scope.row.id,scope.row.account)">删除
</el-button>
</template>
</el-table-column>
</el-table>
<!-- 分页组件-->
<!--
current-page="1" 默认是第一页
page-sizes="[2, 4, 6, 8]" 生成下拉框
page-size="2" 默认的每页大小
layout="total, sizes, prev, pager, next, jumper" 布局
total="400" 总条数
@size-change="handleSizeChange" 当下拉框改变页数大小时触发
@current-change="handleCurrentChange" 当改变页码时触发
-->
<div class="block">
<el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
:page-sizes="[2, 4, 6, 8,10,15]" :page-size="8" layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
</div>
</div>
<!-- 添加管理员的组件显示视图位置 默认是隐藏的 -->
<AddDialog ref="AddDialog"></AddDialog>
<!-- 修改管理员的1组件显示位置;默认隐藏 -->
<UpdateDialog ref="UpdateDialog"></UpdateDialog>
</el-card>
</template>
<script>
import AddDialog from './Add.vue';
import UpdateDialog from './Update.vue';
export default {
components: {
AddDialog,
UpdateDialog
},
data: function() {
return {
tableData: [],
http: "http://127.0.0.1:5927/studyspringbootvue/",
query: {
account: '',
sex: '',
pageNum: 1,
pageSize: 8
},
total: 0,
loading:true
}
},
methods: {
formatType(row, column) {
return (row.type == 1 ? "普通管理员" : "超管");
},
formatTime(row, column) {
var date = new Date(row.operTime);
return date.toLocaleString();
},
getAdminList() {
var _this = this;
this.$http.post("admin/getAllAdmin", this.query).then(function(resp) {
_this.tableData = resp.data.data;
_this.total = resp.data.total;
_this.loading = false;
});
},
search() {
this.query.pageNum = 1;
this.getAdminList();
},
handleSizeChange(val) {
console.log(`每页 ${val} 条`);
this.query.pageSize = val;
this.getAdminList();
},
handleCurrentChange(val) {
console.log(`当前页: ${val}`);
this.query.pageNum = val;
this.getAdminList();
},
openAddAdmin() {
this.$refs.AddDialog.dialogVisible = true;
},
toUpdate(id) {
this.$refs.UpdateDialog.dialogVisible = true;
this.$refs.UpdateDialog.findAdminByID(id);
},
toDelAdmin(id, account) {
var _this = this;
this.$confirm('您确定删除管理员' + account + '吗?', '警告', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
this.$http.delete("admin/deleteAdmin/" + id).then(function(resp) {
if (resp.data.code === 200) {
_this.$message({
message: resp.data.msg,
type: 'success'
});
window.location.reload();
}
})
})
},
},
created() {
this.getAdminList();
}
}
</script>
<style>
body {
margin: 0;
}
</style>
修改管理员信息
点击编辑,同样是以对话框的形式打开; 显示管理员原来的信息;填充到表单; 实际需要分为三步; (1)首先在角色表查询到角色的信息;拼接生成复选框;
(2)然后再通过当前的管理员Id查询到管理员的信息;注意其中的关联查询; 然后把信息拼接到表单中;
注意提交时,这里按照ElementUI官网的表单验证案例试着编写了一下; 毕竟平时主要学习后端开发知识; 表单验证这方面的效果不是很好;
(3)提交数据后,我会首先把这里的管理员关联的角色关联关系 先删除; 然后再根据表单填写的角色内容 重新将关联关系存进 管理员与角色的关联表 ;
然后在管理员修改信息时;由于我上传头像那块是根据管理员的账户名作为头像的文件夹; 考虑到更改账户名之后,服务器上存图片的地址不对应了;所以利用了File类的renameTo 方法;将原文件夹重命名处理;
在点击编辑按钮时,会打开对话框,且为方法传入Id值;
修改管理员信息的Update.vue 组件代码
<template>
<!-- 在此组件中 制作一个对话框 -->
<el-dialog title="修改管理员" :visible.sync="dialogVisible" width="50%">
<!-- 修改管理员信息的表单-->
<el-form ref="form" :model="form" :rules="rules" label-width="100px" class="demo-ruleForm">
<!-- Id列隐藏 -->
<el-input v-model="form.id" v-if="false"></el-input>
<!-- 初始账号名隐藏 -->
<el-input v-model="form.account" v-if="false"></el-input>
<el-form-item label="账号" prop="account">
<el-input v-model="form.account"></el-input>
</el-form-item>
<el-form-item label="手机" prop="phone">
<el-input v-model="form.phone"></el-input>
</el-form-item>
<el-form-item label="性别">
<el-radio v-model="form.sex" label="男">男</el-radio>
<el-radio v-model="form.sex" label="女">女</el-radio>
</el-form-item>
<el-form-item label="角色" prop="roleId">
<el-checkbox-group v-model="form.roleId">
<el-checkbox v-for="role in roles" :label="role.id" :key="role.id">{{role.name}}</el-checkbox>
</el-checkbox-group>
</el-form-item>
</el-form>
<span slot="footer" class="dialog-footer">
<el-button @click="dialogVisible = false">取 消</el-button>
<el-button type="primary" @click="save('form')">保存</el-button>
</span>
</el-dialog>
</template>
<script>
export default {
name: "UpdateDialog",
data() {
return {
dialogVisible: false,
form: {
id: "",
initAccount:"",
account: "",
sex: "男",
phone: "",
roleId: [],
},
roles: [],
rules: {
account: [{
required: true,
message: '请输入账户名',
trigger: 'blur'
},
{
min: 2,
max: 5,
message: '长度在 2 到 5 个字符',
trigger: 'blur'
}
],
phone: [{
required: true,
message: '请输入手机号',
trigger: 'blur'
},
{
min: 11,
max: 11,
message: '手机号限制11位',
trigger: 'blur'
}
],
roleId: [{
type: 'array',
required: true,
message: '请至少选择一个角色',
trigger: 'change'
}]
},
};
},
methods: {
findAdminByID(id) {
var _this = this;
this.$http.get("admin/findAdmin/" + id).then(function(resp) {
_this.form.initAccount=resp.data.data.account;
_this.form.id = resp.data.data.id;
_this.form.account = resp.data.data.account;
_this.form.sex = resp.data.data.sex;
_this.form.phone = resp.data.data.phone;
_this.form.roleId = resp.data.data.roleId;
})
},
save(form) {
var _this = this;
this.$refs[form].validate((valid) => {
if (valid) {
this.$http.post("admin/updateAdmin", this.form).then(function(resp) {
if (resp.data.code === 200) {
_this.$message({
message: resp.data.msg,
type: 'success'
});
window.location.reload();
}
})
} else {
console.log('error submit!!');
return false;
}
});
},
},
created() {
var _this = this;
this.$http.get("admin/roles").then(function(resp) {
_this.roles = resp.data.data;
})
}
};
</script>
<style>
</style>
删除管理员
点击时,触发弹框即可;
这里后端到时候处理的时候,需要先删除这个管理员在管理角色关联表的数据 ;然后再删除管理员表的数据;
就在AdminLst.vue 组件页面;代码在上面;
为管理员上传头像
右上角设置中点击上传头像;
即可打开这个对话框;
ElementUI也是初步学习,刚开始还没搞懂这里面的内置函数和内置参数;文档看了一点;大概是了解到如何调用的了;
上传头像成功后,提示信息;然后图片会被回显到这里;如果不满意,
如果又觉得上传的头像不满意,没关系,点击图片还可以继续操作,上传头像;
- 在上传图片时,其实只要给参数
action :上传地址写好就行;因为这个管理员Id和账号account在token令牌 中就有,然后后端接收时,会从请求头中的token 中解析获取到管理员的Id和账号account;然后;根据账号名,使用工具类对头像文件名进行重命名;将图片存到对应的服务器地址; - 数据库存入对应Id的头像名称以及上传头像时的文件名即可;
当前案例学习时所用的图片暂存服务器; (关于为什么要这样单独开一个tomcat服务器放置管理员头像;在之前的笔记中有提到;—> 前后端分离学习笔记(4) —[路由嵌套, 查询表单显示]之 显示管理员的头像)
这个上传头像的组件页面需要内嵌到主框架 Main.vue 中
在上传头像之前,对文件进行了一个简单的限制; 格式和内存大小
上传头像的组件UpLodeImg.vue 代码
<template>
<!-- 居中的对话框 -->
<el-dialog
title="上传头像"
:visible.sync="centerDialogVisible"
width="40%"
center>
<span>
<el-upload
class="avatar-uploader"
action="http://127.0.0.1:5277/api/admin/upAdminAvatar"
:headers={token:headers}
:show-file-list="false"
:on-success="handleAvatarSuccess"
:before-upload="beforeAvatarUpload">
<img v-if="imageUrl" :src="imageUrl" class="avatar">
<i v-else class="el-icon-plus avatar-uploader-icon"></i>
</el-upload>
</span>
<span slot="footer" class="dialog-footer">
<el-button @click="centerDialogVisible = false" type="danger">取 消 上 传</el-button>
<!-- <el-button type="primary" @click="upLodeAvatar()">上传</el-button> -->
</span>
</el-dialog>
</template>
<script>
export default {
name:'UpLoadImgDialog',
data() {
return {
centerDialogVisible: false,
imageUrl: '',
headers:window.sessionStorage.getItem('token')
};
},
methods: {
handleAvatarSuccess(res, file) {
this.imageUrl = "http://127.0.0.1:5927/studyspringbootvue/"+res.data.account+"/"+res.data.newFileName;
this.$message({message:res.msg, showClose: true, type: 'success'});
},
beforeAvatarUpload(file) {
const isImg = file.type === 'image/png' || file.type == 'image/jpg' || file.type == 'image/jpeg';
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isImg) {
this.$message.error('上传头像图片限制 JPG 格式!PNG格式!JPEG格式!');
}
if (!isLt2M) {
this.$message.error('上传头像图片大小不能超过 2MB!');
}
return isImg && isLt2M;
},
},
};
</script>
<style>
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 178px;
height: 178px;
display: block;
}
</style>
主页面 Main.vue
<template>
<el-container style="height:100%">
<!-- 上面的一整条导航栏 -->
<el-header style="text-align: right; font-size: 12px">
<el-dropdown>
<i class="el-icon-setting" style="margin-right: 15px"></i>
<!-- 右上角个人中心的几个选项-->
<el-dropdown-menu slot="dropdown">
<el-dropdown-item @click.native="openUpPassWordDialog()">修改密码</el-dropdown-item>
<el-dropdown-item @click.native="openUpLoadImgDialog()">上传头像</el-dropdown-item>
<el-dropdown-item @click.native="exit()">退出登录</el-dropdown-item>
</el-dropdown-menu>
</el-dropdown>
<span>{{account}}</span>
</el-header>
<el-container>
<!-- 左侧的侧边栏-->
<el-aside width="200px">
<!-- :default-openeds菜单的默认打开数;这里需要加入路由router -->
<el-menu :default-openeds="['1', '0']" router="">
<el-submenu index="1">
<template slot="title"><i class="el-icon-setting"></i>操作</template>
<el-menu-item-group>
<!-- 这里的文字会绑定上菜单的路径地址,点击即可跳转 -->
<el-menu-item v-bind:index="menu.url" v-for="(menu,index) in menuList" :key="index">{{menu.name}}</el-menu-item>
<!-- <el-menu-item index="3-2">角色管理</el-menu-item> -->
</el-menu-item-group>
</el-submenu>
</el-menu>
</el-aside>
<el-container>
<!-- 中间的主信息页面 -->
<el-main>
<!-- 这里会显示路由跳转过来的视图-->
<router-view></router-view>
</el-main>
<!-- 底部栏的话本次案例练习暂时不用-->
<!-- <el-footer>Footer</el-footer> -->
</el-container>
</el-container>
<!-- 修改头像的对话框弹出 -->
<UpLoadImgDialog ref="UpLoadImgDialog"></UpLoadImgDialog>
<!-- 修改密码的对话框弹出-->
<UpdatePassWord ref="UpdatePassWord"></UpdatePassWord>
</el-container>
</template>
<script>
import UpLoadImgDialog from './UpLodeImg.vue';
import UpdatePassWord from './UpdatePassWord.vue';
export default{
components:{
UpLoadImgDialog,
UpdatePassWord
},
data:function(){
return{
account:"",
menuList:[],
}
},
methods:{
exit(){
this.$confirm('您确定退出吗?', '提示', {
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
window.sessionStorage.clear();
this.$router.push("/login");
})
},
openUpLoadImgDialog(){
this.$refs.UpLoadImgDialog.centerDialogVisible = true;
},
openUpPassWordDialog(){
this.$refs.UpdatePassWord.dialogVisible = true;
}
},
created(){
this.account = window.sessionStorage.getItem("account");
var _this = this;
this.$http.get("login/findMenuList").then(function(resp){
_this.menuList = resp.data.data;
});
}
}
</script>
<style>
.el-header {
background-color: #00FFFF;
color: #333;
text-align: center;
line-height: 60px;
}
.el-aside {
background-color: #67C23A;
color: #333;
}
.el-main {
background-color: #E9EEF3;
color: #333;
}
</style>
修改密码
有简单的密码验证
修改之后会清除浏览器的token 缓存;强制路由到登录页面;
修改密码的对话框组件也需要内嵌到主页面中;
UpdatePassWord.vue 修改密码的组件
<template>
<el-dialog title="修改密码" :visible.sync="dialogVisible" width="30%">
<span>
<el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px"
class="demo-ruleForm">
<el-form-item label="旧密码" prop="oldPass">
<el-input type="password" v-model="ruleForm.oldPass" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="新密码" prop="newPass">
<el-input type="password" v-model="ruleForm.newPass" autocomplete="off"></el-input>
</el-form-item>
<el-form-item label="确认密码" prop="checkPass">
<el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="submitForm('ruleForm')">修改</el-button>
<el-button @click="resetForm('ruleForm')">重置</el-button>
</el-form-item>
</el-form>
</span>
</el-dialog>
</template>
<script>
export default {
data() {
var validateoldPass = (rule, value, callback) => {
if (value === '') {
callback(new Error('请输入旧密码'));
} else if (value.length > 6) {
callback(new Error('密码长度不超过6位!'));
} else if (this.checkOldPassWord(value) == false) {
callback(new Error('旧密码输入错误'));
} else {
callback();
}
};
var validateneWPass = (rule, value, callback) => {
if (value === '') {
callback(new Error('请输入新密码'));
} else if (value.length > 6) {
callback(new Error('密码长度不超过6位!'));
} else {
if (this.ruleForm.checkPass !== '') {
this.$refs.ruleForm.validateField('checkPass');
}
callback();
}
};
var validatePass2 = (rule, value, callback) => {
if (value === '') {
callback(new Error('请再次输入密码'));
} else if (value.length > 6) {
callback(new Error('密码长度不超过6位!'));
} else if (value !== this.ruleForm.newPass) {
callback(new Error('两次输入密码不一致!'));
} else {
callback();
}
};
return {
dialogVisible: false,
ruleForm: {
oldPass: '',
newPass: '',
checkPass: '',
},
rules: {
oldPass: [{
validator: validateoldPass,
trigger: 'blur'
}],
newPass: [{
validator: validateneWPass,
trigger: 'blur'
}],
checkPass: [{
validator: validatePass2,
trigger: 'blur'
}],
},
};
},
methods: {
checkOldPassWord(oldPass) {
var result = this.$http.get("admin/checkAdminPass/" + oldPass).then(function(resp) {
return resp.data.data;
});
return result;
},
submitForm(formName) {
this.$refs[formName].validate((valid) => {
if (valid) {
var _this = this;
this.$http.put("admin/updatePassword/" + this.ruleForm.newPass).then(function(resp) {
_this.$message({
message: resp.data.msg,
type: 'success'
});
window.sessionStorage.removeItem("token");
_this.$router.replace("/login");
});
} else {
console.log('error submit!!');
return false;
}
});
},
resetForm(formName) {
this.$refs[formName].resetFields();
}
}
};
</script>
<style>
</style>
实际上,我这里的旧密码验证还是有点问题的; 本来想着要利用外部方法checkOldPassWord(oldPass) 开启async ;然后让里面的异步方法开启await 变为同步方法的,但是返回值为promise 对象;我需要取到其中[[PromiseValue]] 的值,试过了,虽然可以取到;但是在实际验证时,还是有问题的;
验证时调用方法;
2.后端处理
管理员控制层
AdminController
package com.xiaozhi.backserver.startspringboot.controller;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.PageInfo;
import com.xiaozhi.backserver.startspringboot.model.Admin;
import com.xiaozhi.backserver.startspringboot.model.Role;
import com.xiaozhi.backserver.startspringboot.service.AdminService;
import com.xiaozhi.backserver.startspringboot.util.CommonResult;
import com.xiaozhi.backserver.startspringboot.util.JWTUtil;
import com.xiaozhi.backserver.startspringboot.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
@RestController
@RequestMapping(value = "/api/admin")
public class AdminController {
CommonResult commonResult;
@Autowired
AdminService adminService;
@PostMapping(path = "/getAllAdmin")
public CommonResult getAllAdmin(@RequestBody Admin admin) {
try {
PageInfo<Admin> allAdmin = adminService.getAllAdmin(admin);
commonResult = new CommonResult(200, "查询管理员列表信息成功", allAdmin.getList(), allAdmin.getTotal());
} catch (Exception e) {
e.printStackTrace();
commonResult = new CommonResult(500, "服务器异常", null);
}
return commonResult;
}
@GetMapping(value = "/roles")
public CommonResult getRoleS() {
try {
List<Role> roleList = adminService.getRoleList();
if (!roleList.isEmpty()) {
commonResult = new CommonResult(200, "查询角色列表成功", roleList);
} else {
commonResult = new CommonResult(201, "角色列表查询失败", null);
}
} catch (Exception e) {
e.printStackTrace();
commonResult = new CommonResult(500, "服务器异常", null);
}
return commonResult;
}
@PostMapping(value = "/addAdmin")
public CommonResult addAdmin(@RequestBody Admin admin) {
try {
adminService.addAdminInfo(admin);
commonResult = new CommonResult(200, "添加管理员成功", null);
} catch (Exception e) {
e.printStackTrace();
commonResult = new CommonResult(500, "服务器异常", null);
}
return commonResult;
}
@GetMapping(value = "/findAdmin/{id}")
public CommonResult findAdmin(@PathVariable("id") Integer id) {
try {
Admin admin = adminService.findAdmin(id);
commonResult = new CommonResult(200, "查询管理员信息成功", admin);
} catch (Exception e) {
e.printStackTrace();
commonResult = new CommonResult(500, "服务器异常", null);
}
return commonResult;
}
@PostMapping(value = "/updateAdmin")
public CommonResult updateAdmin(@RequestBody Admin admin) {
try {
adminService.updateAdmin(admin);
commonResult = new CommonResult(200, "管理员信息修改成功", null);
} catch (Exception e) {
e.printStackTrace();
commonResult = new CommonResult(500, "服务器异常", null);
}
return commonResult;
}
@DeleteMapping(value = "/deleteAdmin/{id}")
public CommonResult deleteAdmin(@PathVariable("id") Integer id) {
try {
adminService.deleteAdmin(id);
commonResult = new CommonResult(200, "删除成功", null);
} catch (Exception e) {
e.printStackTrace();
commonResult = new CommonResult(500, "服务器异常", null);
}
return commonResult;
}
@PostMapping(value = "/upAdminAvatar")
public CommonResult upAdminAvatar(@RequestHeader("token") String token, @RequestParam("file") CommonsMultipartFile file) {
try {
DecodedJWT info = JWTUtil.getTokenInfo(token);
Integer id = info.getClaim("id").asInt();
String account = info.getClaim("account").asString();
File f0 = new File("D:\\项目图片服务器\\apache-tomcat-9.0.43\\webapps\\ROOT\\studyspringbootvue\\" + account);
if (!f0.exists()) {
f0.mkdir();
}
String newFileName = StringUtil.getNewFileName(file.getOriginalFilename());
File f1 = new File(f0, newFileName);
file.transferTo(f1);
adminService.insertAdminAvatar(id, newFileName, file.getOriginalFilename());
Admin admin = new Admin();
admin.setAccount(account);
admin.setNewFileName(newFileName);
commonResult = new CommonResult(200, "管理员头像上传成功", admin);
} catch (Exception e) {
e.printStackTrace();
commonResult = new CommonResult(500, "服务器异常", null);
}
return commonResult;
}
@GetMapping(value = "/checkAdminPass/{oldPass}")
public CommonResult checkAdminPass(@PathVariable("oldPass") String oldPass,@RequestHeader("token") String token) {
try {
Admin admin = adminService.checkAdminPass(token);
if (oldPass.equals(admin.getPassword())) {
commonResult = new CommonResult(200, "旧密码正确", true);
} else {
commonResult = new CommonResult(200, "旧密码错误", false);
}
} catch (Exception e) {
e.printStackTrace();
commonResult = new CommonResult(500, "服务器异常", null);
}
return commonResult;
}
@PutMapping(value = "/updatePassword/{newPass}")
public CommonResult updatePassword(@PathVariable("newPass") String password,@RequestHeader("token") String token){
try{
adminService.updatePassword(token,password);
commonResult = new CommonResult(200, "修改密码成功", null);
}catch (Exception e){
e.printStackTrace();
commonResult = new CommonResult(500, "服务器异常", null);
}
return commonResult;
}
}
调用的服务层
package com.xiaozhi.backserver.startspringboot.service;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaozhi.backserver.startspringboot.dao.AdminDao;
import com.xiaozhi.backserver.startspringboot.model.Admin;
import com.xiaozhi.backserver.startspringboot.model.Role;
import com.xiaozhi.backserver.startspringboot.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.util.List;
@Transactional
@Service
public class AdminService {
@Autowired
AdminDao adminDao;
public PageInfo<Admin> getAllAdmin(Admin admin) {
PageHelper.startPage(admin.getPageNum(), admin.getPageSize());
List<Admin> allAdmin = adminDao.getAllAdmin(admin);
PageInfo<Admin> info = new PageInfo<>(allAdmin);
return info;
}
public List<Role> getRoleList() {
return adminDao.getRoleList();
}
public void addAdminInfo(Admin admin){
admin.setPassword("123");
adminDao.addAdminInfo(admin);
if(admin.getRoleId()!=null){
for (Integer rId : admin.getRoleId()) {
adminDao.addAdminAndRoleId(admin.getId(),rId);
}
}
}
public Admin findAdmin(Integer id) {
Admin admin = adminDao.findAdmin(id);
Integer[] roleIds = new Integer[admin.getRoleList().size()];
for (int i = 0; i < admin.getRoleList().size(); i++) {
roleIds[i] = admin.getRoleList().get(i).getId();
}
admin.setRoleId(roleIds);
return admin;
}
public void updateAdmin(Admin admin) {
adminDao.updateAdmin(admin);
if(!admin.getInitAccount().equals(admin.getAccount())){
File f = new File("D:\\项目图片服务器\\apache-tomcat-9.0.43\\webapps\\ROOT\\studyspringbootvue\\"+admin.getInitAccount());
File f0 =new File("D:\\项目图片服务器\\apache-tomcat-9.0.43\\webapps\\ROOT\\studyspringbootvue\\"+admin.getAccount());
f.renameTo(f0);
}
adminDao.deleteAIdAndRId(admin.getId());
if(admin.getRoleId()!=null){
for (Integer rId : admin.getRoleId()) {
adminDao.addAdminAndRoleId(admin.getId(),rId);
}
}
}
public void deleteAdmin(Integer id) {
adminDao.deleteAIdAndRId(id);
adminDao.deleteAdmin(id);
}
public void insertAdminAvatar(Integer id, String newFileName,String oldFileName) {
Admin admin = new Admin();
admin.setId(id);
admin.setNewFileName(newFileName);
admin.setOldFileName(oldFileName);
adminDao.insertAdminAvatar(admin);
}
public Admin checkAdminPass(String token) {
DecodedJWT info = JWTUtil.getTokenInfo(token);
Integer id = info.getClaim("id").asInt();
return adminDao.checkAdminPass(id);
}
public void updatePassword(String token, String password) {
DecodedJWT info = JWTUtil.getTokenInfo(token);
Integer id = info.getClaim("id").asInt();
adminDao.updatePassword(id,password);
}
}
管理员服务层
package com.xiaozhi.backserver.startspringboot.service;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaozhi.backserver.startspringboot.dao.AdminDao;
import com.xiaozhi.backserver.startspringboot.model.Admin;
import com.xiaozhi.backserver.startspringboot.model.Role;
import com.xiaozhi.backserver.startspringboot.util.JWTUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.io.File;
import java.util.List;
@Transactional
@Service
public class AdminService {
@Autowired
AdminDao adminDao;
public PageInfo<Admin> getAllAdmin(Admin admin) {
PageHelper.startPage(admin.getPageNum(), admin.getPageSize());
List<Admin> allAdmin = adminDao.getAllAdmin(admin);
PageInfo<Admin> info = new PageInfo<>(allAdmin);
return info;
}
public List<Role> getRoleList() {
return adminDao.getRoleList();
}
public void addAdminInfo(Admin admin){
admin.setPassword("123");
adminDao.addAdminInfo(admin);
if(admin.getRoleId()!=null){
for (Integer rId : admin.getRoleId()) {
adminDao.addAdminAndRoleId(admin.getId(),rId);
}
}
}
public Admin findAdmin(Integer id) {
Admin admin = adminDao.findAdmin(id);
Integer[] roleIds = new Integer[admin.getRoleList().size()];
for (int i = 0; i < admin.getRoleList().size(); i++) {
roleIds[i] = admin.getRoleList().get(i).getId();
}
admin.setRoleId(roleIds);
return admin;
}
public void updateAdmin(Admin admin) {
adminDao.updateAdmin(admin);
if(!admin.getInitAccount().equals(admin.getAccount())){
File f = new File("D:\\项目图片服务器\\apache-tomcat-9.0.43\\webapps\\ROOT\\studyspringbootvue\\"+admin.getInitAccount());
File f0 =new File("D:\\项目图片服务器\\apache-tomcat-9.0.43\\webapps\\ROOT\\studyspringbootvue\\"+admin.getAccount());
f.renameTo(f0);
}
adminDao.deleteAIdAndRId(admin.getId());
if(admin.getRoleId()!=null){
for (Integer rId : admin.getRoleId()) {
adminDao.addAdminAndRoleId(admin.getId(),rId);
}
}
}
public void deleteAdmin(Integer id) {
adminDao.deleteAIdAndRId(id);
adminDao.deleteAdmin(id);
}
public void insertAdminAvatar(Integer id, String newFileName,String oldFileName) {
Admin admin = new Admin();
admin.setId(id);
admin.setNewFileName(newFileName);
admin.setOldFileName(oldFileName);
adminDao.insertAdminAvatar(admin);
}
public Admin checkAdminPass(String token) {
DecodedJWT info = JWTUtil.getTokenInfo(token);
Integer id = info.getClaim("id").asInt();
return adminDao.checkAdminPass(id);
}
public void updatePassword(String token, String password) {
DecodedJWT info = JWTUtil.getTokenInfo(token);
Integer id = info.getClaim("id").asInt();
adminDao.updatePassword(id,password);
}
}
管理员持久层
package com.xiaozhi.backserver.startspringboot.dao;
import com.xiaozhi.backserver.startspringboot.model.Admin;
import com.xiaozhi.backserver.startspringboot.model.Role;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@Repository
public interface AdminDao {
List<Admin> getAllAdmin(Admin admin);
List<Role> getRoleList();
Admin findAdmin(Integer id);
void addAdminInfo(Admin admin);
void addAdminAndRoleId(@Param("aId") Integer aId, @Param("rId") Integer rID);
void updateAdmin(Admin admin);
void deleteAIdAndRId(Integer id);
void deleteAdmin(Integer id);
void insertAdminAvatar(Admin admin);
Admin checkAdminPass(Integer id);
void updatePassword(Integer id, String password);
}
头像上传时的后端全局配置类
package com.xiaozhi.backserver.startspringboot.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
@Configuration
public class MultipartConfig {
@Bean
public CommonsMultipartResolver multipartConfigElement() {
CommonsMultipartResolver multipartresolver = new CommonsMultipartResolver();
multipartresolver.setMaxUploadSize(1024*1024*5);
return multipartresolver;
}
}
头像上传时重命名格式的工具类
package com.xiaozhi.backserver.startspringboot.util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class StringUtil {
public static String subFileType(String fileName){
if(fileName!=null){
return fileName.substring(fileName.lastIndexOf(".")+1);
}
return null;
}
public static String getNewFileName(String oldFileName) {
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
return sdf.format(date) + "." + subFileType(oldFileName);
}
}
管理员对应的映射SQl
<?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.xiaozhi.backserver.startspringboot.dao.AdminDao">
<resultMap id="adminmap" type="admin">
<id property="id" column="id"/>
<result property="account" column="account"/>
<result property="password" column="password"/>
<result property="sex" column="sex"/>
<result property="phone" column="phone"/>
<result property="newFileName" column="new_file_name"/>
<result property="operTime" column="oper_time"/>
<result property="type" column="type"/>
<collection property="roleList" javaType="list" ofType="role"
select="getRoleBYAdminId" column="id">
<result property="name" column="name"/>
<result property="id" column="role_id"/>
</collection>
</resultMap>
<select id="getAllAdmin" parameterType="admin" resultMap="adminmap">
SELECT
`id`,
`account`,
`sex`,
`phone`,
`new_file_name`,
`type`,
`oper_time`
FROM t_admin
WHERE `type` = 1
<if test="account!=''">
and `account` =#{account}
</if>
<if test="sex!=''">
and `sex` =#{sex}
</if>
</select>
<select id="getRoleBYAdminId" resultType="role">
select
r.name
from
t_admin_role ar
left join t_role r on ar.`role_id`=r.`id`
where ar.`admin_id` =#{id}
</select>
<select id="getRoleList" resultType="role">
select id,name,role_desc from t_role
</select>
<insert id="addAdminInfo" parameterType="admin" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
insert into t_admin(`account`,`sex`,`phone`,`password`,`oper_time`)
values (#{account},#{sex},#{phone},#{password},now())
</insert>
<insert id="addAdminAndRoleId">
insert into t_admin_role(admin_id,role_id)
values (#{aId},#{rId})
</insert>
<resultMap id="adminmap1" type="admin">
<id column="id" property="id"></id>
<result column="account" property="account"></result>
<result column="phone" property="phone"></result>
<result column="sex" property="sex"></result>
<collection property="roleList" javaType="list" ofType="role">
<result column="role_id" property="id"></result>
</collection>
</resultMap>
<select id="findAdmin" resultMap="adminmap1">
SELECT
a.`id`,
a.`account`,
a.`sex`,
a.`phone`,
ar.`role_id`
FROM t_admin a
LEFT JOIN t_admin_role ar ON ar.`admin_id`=a.`id`
WHERE id = #{id}
</select>
<update id="updateAdmin">
update t_admin set account=#{account},sex=#{sex},phone=#{phone},oper_time=now()
where id = #{id}
</update>
<delete id="deleteAIdAndRId">
delete from t_admin_role where admin_id= #{id}
</delete>
<delete id="deleteAdmin">
delete from t_admin where id= #{id}
</delete>
<insert id="insertAdminAvatar">
update t_admin set `new_file_name`=#{newFileName},`old_file_name`=#{oldFileName},oper_time=now()
where `id`=#{id}
</insert>
<select id="checkAdminPass" resultType="admin">
select `password` from t_admin where id= #{id}
</select>
<update id="updatePassword">
update t_admin set `password`= #{password} where id= #{id}
</update>
</mapper>
|