第二季SpringBoot+Vue前后端分离项目实战笔记
Posted 大菜007
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第二季SpringBoot+Vue前后端分离项目实战笔记相关的知识,希望对你有一定的参考价值。
配套视频在b站:【第二季】全网最简单但实用的SpringBoot+Vue前后端分离项目实战
SpringBoot+Vue项目实战 第二季
一、些许优化
刷新丢失其它标签页
-
缓存已打开标签页
tagsViewCache() window.addEventListener("beforeunload", () => let tabViews = this.visitedViews.map(item => return fullPath: item.fullPath, hash: item.hash, meta: ...item.meta , name: item.name, params: ...item.params , path: item.path, query: ...item.query , title: item.title ; ); sessionStorage.setItem("tabViews", JSON.stringify(tabViews)); ); let oldViews = JSON.parse(sessionStorage.getItem("tabViews")) || []; if (oldViews.length > 0) this.$store.state.tagsView.visitedViews = oldViews; ,
-
注销时删除所有tagview
// 注销时删除所有tagview await this.$store.dispatch('tagsView/delAllViews') sessionStorage.removeItem('tabViews')
二、Swagger整合
Swagger-UI可以动态地根据注解生成在线API文档。
常用注解
- @Api:用于修饰Controller类,生成Controller相关文档信息
- @ApiOperation:用于修饰Controller类中的方法,生成接口方法相关文档信息
- @ApiParam:用于修饰接口中的参数,生成接口参数相关文档信息
- @ApiModelProperty:用于修饰实体类的属性,当实体类是请求参数或返回结果时,直接生成相关文档信息
整合步骤:
-
添加依赖
<!--Swagger文档工具--> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-boot-starter</artifactId> <version>3.0.0</version> </dependency>
-
swagger配置类
@Configuration @EnableOpenApi @EnableWebMvc public class SwaggerConfig @Bean public Docket api() return new Docket(DocumentationType.OAS_30) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.lantu")) .paths(PathSelectors.any()) .build(); private ApiInfo apiInfo() return new ApiInfoBuilder() .title("神盾局特工管理系统接口文档") .description("全网最简单的SpringBoot+Vue前后端分离项目实战") .version("1.0") .contact(new Contact("qqcn", "http://www.qqcn.cn", "qqcn@aliyun.com")) .build();
-
控制器根据需要添加swagger注解
-
测试:http://localhost:9999/swagger-ui/index.html
三、Jwt整合
JSON Web Token (JWT)是一个开放标准(RFC 7519),它定义了一种紧凑的、自包含的方式,用于作为JSON对象在各方之间安全地传输信息。该信息可以被验证和信任,因为它是数字签名的。
jwt形式举例:
eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI5MjAzOThjZi1hYThiLTQzNWUtOTIxYS1iNGQ3MDNmYmZiZGQiLCJzdWIiOiJ7XCJwaG9uZVwiOlwiMTIzNDIzNFwiLFwidXNlcm5hbWVcIjpcInpoYW5nc2FuXCJ9IiwiaXNzIjoic3lzdGVtIiwiaWF0IjoxNjc3MTE4Njc2LCJleHAiOjE2NzcxMjA0NzZ9.acc7H6-6ACqcgNu5waqain7th7zJciP-41z-qgWeaSY
⑴ 整合步骤
-
pom
<dependency> <groupId>io.jsonwebtoken</groupId> <artifactId>jjwt</artifactId> <version>0.9.1</version> </dependency>
-
工具类
@Component public class JwtUtil // 有效期 private static final long JWT_EXPIRE = 30*60*1000L; //半小时 // 令牌秘钥 private static final String JWT_KEY = "123456"; public String createToken(Object data) // 当前时间 long currentTime = System.currentTimeMillis(); // 过期时间 long expTime = currentTime+JWT_EXPIRE; // 构建jwt JwtBuilder builder = Jwts.builder() .setId(UUID.randomUUID()+"") .setSubject(JSON.toJSONString(data)) .setIssuer("system") .setIssuedAt(new Date(currentTime)) .signWith(SignatureAlgorithm.HS256, encodeSecret(JWT_KEY)) .setExpiration(new Date(expTime)); return builder.compact(); private SecretKey encodeSecret(String key) byte[] encode = Base64.getEncoder().encode(key.getBytes()); SecretKeySpec aes = new SecretKeySpec(encode, 0, encode.length, "AES"); return aes; public Claims parseToken(String token) Claims body = Jwts.parser() .setSigningKey(encodeSecret(JWT_KEY)) .parseClaimsJws(token) .getBody(); return body; public <T> T parseToken(String token,Class<T> clazz) Claims body = Jwts.parser() .setSigningKey(encodeSecret(JWT_KEY)) .parseClaimsJws(token) .getBody(); return JSON.parseObject(body.getSubject(),clazz);
-
测试工具类
-
修改登录逻辑
-
测试登录
问题思考:
登录后续请求如何验证jwt ?
⑵ JWT验证拦截器
定义拦截器
@Component
@Slf4j
public class JwtValidateInterceptor implements HandlerInterceptor
@Autowired
private JwtUtil jwtUtil;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
String token = request.getHeader("X-Token");
System.out.println(request.getRequestURI() +" 待验证:"+token);
if(token != null)
try
jwtUtil.parseToken(token);
log.debug(request.getRequestURI() + " 放行...");
return true;
catch (Exception e)
e.printStackTrace();
log.debug(request.getRequestURI() + " 禁止访问...");
response.setContentType("application/json;charset=utf-8");
response.getWriter().write(JSON.toJSONString(Result.fail(20003,"jwt令牌无效,请重新登录")));
return false;
注册拦截器
@Configuration
public class MyWebConfig implements WebMvcConfigurer
@Autowired
private JwtValidateInterceptor jwtValidateInterceptor;
@Override
public void addInterceptors(InterceptorRegistry registry)
InterceptorRegistration registration = registry.addInterceptor(jwtValidateInterceptor);
registration.addPathPatterns("/**")
.excludePathPatterns(
"/user/login",
"/user/info",
"/user/logout",
"/error",
"/swagger-ui/**",
"/swagger-resources/**",
"/v3/**");
⑶ Swagger授权配置
@Configuration
@EnableOpenApi
@EnableWebMvc
public class SwaggerConfig
@Bean
public Docket api()
return new Docket(DocumentationType.OAS_30)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.lantu"))
.paths(PathSelectors.any())
.build()
.securitySchemes(Collections.singletonList(securityScheme()))
.securityContexts(Collections.singletonList(securityContext()));
private SecurityScheme securityScheme()
//return new ApiKey("Authorization", "Authorization", "header");
return new ApiKey("X-Token", "X-Token", "header");
private SecurityContext securityContext()
return SecurityContext.builder()
.securityReferences(defaultAuth())
.forPaths(PathSelectors.regex("^(?!auth).*$"))
.build();
private List<SecurityReference> defaultAuth()
AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
authorizationScopes[0] = authorizationScope;
return Collections.singletonList(
new SecurityReference("X-Token", authorizationScopes));
private ApiInfo apiInfo()
return new ApiInfoBuilder()
.title("神盾局特工管理系统接口文档")
.description("全网最简单的SpringBoot+Vue前后端分离项目实战")
.version("1.0")
.contact(new Contact("老蔡", "https://space.bilibili.com/431588578", "xxxx@aliyun.com"))
.build();
四、角色管理
1. 基本功能
⑴ 预览效果
⑵ 前端
role.vue
<template>
<div>
<!-- 搜索栏 -->
<el-card id="search">
<el-row>
<el-col :span="18">
<el-input placeholder="角色名" v-model="searchModel.roleName" clearable> </el-input>
<el-button @click="getRoleList" type="primary" icon="el-icon-search" round>查询</el-button>
</el-col>
<el-col :span="6" align="right">
<el-button @click="openEditUI(null)" type="primary" icon="el-icon-plus" circle></el-button>
</el-col>
</el-row>
</el-card>
<!-- 结果列表 -->
<el-card>
<el-table :data="roleList" stripe style="width: 100%">
<el-table-column label="#" width="80">
<template slot-scope="scope">
(searchModel.pageNo-1) * searchModel.pageSize + scope.$index + 1
</template>
</el-table-column>
<el-table-column prop="roleId" label="角色编号" width="180">
</el-table-column>
<el-table-column prop="roleName" label="角色名称" width="180">
</el-table-column>
<el-table-column prop="roleDesc" label="角色描述" >
</el-table-column>
<el-table-column label="操作" width="180">
<template slot-scope="scope">
<el-button @click="openEditUI(scope.row.roleId)" type="primary" icon="el-icon-edit" circle size="mini"></el-button>
<el-button @click="deleteRole(scope.row)" type="danger" icon="el-icon-delete" circle size="mini"></el-button>
</template>
</el-table-column>
</el-table>
</el-card>
<el-pagination
@size-change="handleSizeChange"
@current-change="handleCurrentChange"
:current-page="searchModel.pageNo"
:page-sizes="[5, 10, 20, 50]"
:page-size="searchModel.pageSize"
layout="total, sizes, prev, pager, next, jumper"
:total="total">
</el-pagination>
<!-- 对话框 -->
<el-dialog @close="clearForm" :title="title" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
<el-form :model="roleForm" ref="roleFormRef" :rules="rules">
<el-form-item prop="roleName" label="角色名称" :label-width="formLabelWidth">
<el-input v-model="roleForm.roleName" autocomplete="off"></el-input>
</el-form-item>
<el-form-item prop="roleDesc" label="角色描述" :label-width="formLabelWidth">
<el-input v-model="roleForm.roleDesc" autocomplete="off"></el-input>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button @click="dialogFormVisible = false">取 消</el-button>
<el-button type="primary" @click="saveRole">确 定</el-button>
</div>
</el-dialog>
</div>
</template>
<script>
import roleApi from '@/api/roleManage'
export default
data()
return
formLabelWidth: '130px',
roleForm: ,
dialogFormVisible: false,
title: '',
searchModel:
pageNo: 1,
pageSize: 10
,
roleList: [],
total: 0,
rules:
roleName: [
required: true, message: '请输入角色名称', trigger: 'blur' ,
min: 3, max: 50, message: '长度在 3 到 50 个字符', trigger: 'blur'
]
,
methods:
deleteRole(role)
this.$confirm(`您确定删除角色 $role.roleName ?`, '提示',
confirmButtonText: '确定',
cancelButtonText: '取消',
type: 'warning'
).then(() =>
roleApi.deleteRoleById(role.roleId).then(response =>
this.$message(
type: 'success',
message: response.message
);
this.dialogFormVisible = false;
this.getRoleList();
);
).catch(() =>
this.$message(
type: 'info',
message: '已取消删除'
);
);
,
saveRole()
// 触发表单验证
this.$refs.roleFormRef.validate((valid) =>
if (valid)
// 提交保存请求
roleApi.saveRole(this.roleForm).then(response =>
// 成功提示
this.$message(
message: response.message,
type: 'success'
);
// 关闭对话框
this.dialogFormVisible = false;
// 刷新表格数据
this.getRoleList();
);
else
console.log('error submit!!');
return false;
);
,
clearForm()
this.roleForm = ;
this.$refs.roleFormRef.clearValidate();
,
openEditUI(id)
if(id == null)
this.title = '新增角色';
else
this.title = '修改角色';
roleApi.getRoleById(id).then(response =>
this.roleForm = response.data;
);
this.dialogFormVisible = true;
,
handleSizeChange(pageSize)
this.searchModel.pageSize = pageSize;
this.getRoleList();
,
handleCurrentChange(pageNo)
this.searchModel.pageNo = pageNo;
this.getRoleList();
,
getRoleList()
roleApi.getRoleList(this.searchModel).then(response =>
this.roleList = response.data.rows;
this.total = response.data.total;
);
,
created()
this.getRoleList();
;
</script>
<style>
#search .el-input
width: 200px;
margin-right: 10px;
.el-dialog .el-input
width: 85%;
</style>
roleManage.js
import request from '@/utils/request'
export default
// 分页查询角色列表
getRoleList(searchModel)
return request(
url: '/role/list',
method: 'get',
params:
roleName: searchModel.roleName,
pageNo: searchModel.pageNo,
pageSize: searchModel.pageSize
);
,
// 新增
addRole(role)
return request(
url: '/role',
method: 'post',
data: role
);
,
// 修改
updateRole(role)
return request(
url: '/role',
method: 'put',
data: role
);
,
// 保存角色数据
saveRole(role)
if(role.roleId == null || role.roleId == undefined)
return this.addRole(role);
return this.updateRole(role);
,
// 根据id查询
getRoleById(id)
return request(
url: `/role/$id`,
method: 'get'
);
,
// 根据id删除
deleteRoleById(id)
return request(
url: `/role/$id`,
method: 'delete'
);
,
⑶ 后端
RoleController
@RestController
@RequestMapping("/role")
public class RoleController
@Autowired
private IRoleService roleService;
@GetMapping("/list")
public Result<Map<String,Object>> getUserList(@RequestParam(value = "roleName",required = false) String roleName,
编程指南针
作者简介:Java领域优质创作者、CSDN博客专家 、掘金特邀作者、多年架构师设计经验、腾讯课堂常驻讲师
主要内容:Java项目、毕业设计、简历模板、学习资料、面试题库、技术互助
文末获取源码
一,项目简介
系统是前后端分离的项目,直接启动Springboot应用程序类后,再启动前端工程访问即可。主要实现 了企业的人事管理功能,主要包含员工管理、薪资管理、职位管理、权限管理、网盘文件分享管理等模块。
系统亮点:使用REDIS进行数据缓存,优化查询性能;使用分布式文件系统进行文件存储服务;基于Springboot+vue实现前后端分离开发
二,环境介绍
语言环境:Java: jdk1.8
数据库:Mysql: mysql5.7
应用服务器:Tomcat: tomcat8.5.31
开发工具:IDEA或eclipse
开发技术:Element UI 、Vue、Axios、SpringBoot、MyBatis、MySQL、Redis、FastDFS(或OSS)、Tomcat8.5.31
三,系统展示
下面展示一下系统的基本功能:
用户登陆:
系统主界面:
员工管理:
高级搜索
员工奖惩管理
添加奖惩
工资套账(工资标准)管理
员工工资管理
系统管理—部门管理
系统管理--职位管理
系统管理—职称管理
文件管理:将文件存储在分布式文件服务Fastdfs或阿里云OSS上,可以在系统中自行配置
以上是本系统的基本功能功能展示,本系统所使用技术比较先进,功能比较完整,界面美观大方,适合毕业设计使用。
四,核心代码展示
package com.me.controller;
import com.me.pojo.Department;
import com.me.pojo.RespBean;
import com.me.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
public class DepartmentController
@Autowired
DepartmentService departmentService;
@GetMapping("/dep/deps")
public RespBean getAllDepartments()
List<Department> list = departmentService.getAllDepartments();
// for (Department department : list)
// System.out.println(department);
//
return RespBean.ok("AllDepartments", list);
@PostMapping("/dep/add")
public RespBean addDep(@RequestBody Department dep)
System.out.println(dep);
departmentService.addDep(dep);
if (dep.getResult() == 1)
return RespBean.ok("添加成功", dep);
return RespBean.error("添加失败");
@DeleteMapping("/dep/id")
public RespBean deleteDepById(@PathVariable Integer id)
Department dep = new Department();
dep.setId(id);
departmentService.deleteDepById(dep);
if (dep.getResult() == -2)
return RespBean.error("该部门下有子部门,删除失败");
else if (dep.getResult() == -1)
return RespBean.error("该部门下有员工,删除失败");
else if (dep.getResult() == 1)
return RespBean.ok("删除成功");
return RespBean.error("删除失败");
package com.me.controller;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.me.pojo.*;
import com.me.service.DepartmentService;
import com.me.service.EmployeeService;
import com.me.service.JobLevelService;
import com.me.service.PositionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;
@RestController
public class EmpController
@Autowired
EmployeeService employeeService;
@Autowired
PositionService positionService;
@GetMapping("/emp/query")
public RespPageBean getEmployeeByPage(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer size, Employee employee, Date[] beginDateScope)
// System.out.println(employee);
return employeeService.getEmployeeByPage(page, size, employee, beginDateScope);
@PostMapping("/emp/add")
public RespBean addEmp(@RequestBody Employee employee)
// System.out.println(employee);
if (employeeService.addEmp(employee) == 1)
return RespBean.ok("添加成功!");
return RespBean.error("添加失败!");
@PutMapping("/emp/update")
public RespBean updateEmp(@RequestBody Employee employee)
// System.out.println(employee);
if (employeeService.updateEmp(employee) == 1)
return RespBean.ok("更新成功!");
return RespBean.error("更新失败!");
@DeleteMapping("/emp/delete/id")
public RespBean deleteEmpByEid(@PathVariable Integer id)
if (employeeService.deleteEmpByEid(id) == 1)
return RespBean.ok("删除成功!");
return RespBean.error("删除失败!");
@GetMapping("/emp/getAllPositions")
public RespBean getAllPositions()
return RespBean.ok("positions-",positionService.getAllPositions()) ;
@GetMapping("/emp/nations")
public RespBean getAllNations()
return RespBean.ok("nations-",employeeService.getAllNations());
@GetMapping("/emp/politicsstatus")
public RespBean getAllPoliticsstatus()
return RespBean.ok("politicsss-",employeeService.getAllPoliticsstatus()) ;
@Autowired
private JobLevelService jobLevelService;
@GetMapping("/emp/joblevels")
public RespBean getAllJobLevels()
return RespBean.ok("joblevels-",jobLevelService.getAllJobLevels());
@Autowired
private DepartmentService departmentService;
@GetMapping("/emp/deps")
public RespBean getAllDepartments()
List<Department> list = departmentService.getAllDepartments();
// for (Department department : list)
// System.out.println(department);
//
return RespBean.ok("AllDepartments", list);
package com.me.controller;
import com.me.pojo.Employee;
import com.me.pojo.Employeeec;
import com.me.pojo.RespBean;
import com.me.pojo.RespPageBean;
import com.me.service.EmployeeecService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
@RestController
public class EmployeeecController
@Autowired
EmployeeecService employeeecService;
@GetMapping("/ec/keyword")
public RespBean selectByNameOrWorkId(@PathVariable String keyword)
System.out.println(keyword);
return RespBean.ok("获取到-",employeeecService.selectByNameOrWorkId(keyword));
@DeleteMapping("/ec/id")
public RespBean deleteById(@PathVariable int id)
System.out.println(id);
if(employeeecService.deleteById(id)==1)
return RespBean.ok("删除成功");
return RespBean.error("失败");
@PostMapping("/ec/add")
public RespBean add(@RequestBody Employeeec employeeec)
System.out.println(employeeec);
if(employeeecService.insertEc(employeeec)==1)
return RespBean.ok("添加成功");
return RespBean.error("失败");
@PutMapping("/ec/update")
public RespBean put(@RequestBody Employeeec employeeec)
System.out.println(employeeec);
if(employeeecService.updateEc(employeeec)==1)
return RespBean.ok("添加成功");
return RespBean.error("失败");
package com.me.controller;
import com.me.pojo.RespBean;
import com.me.service.FileService;
import com.me.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
@RestController
public class FileController
@Autowired
FileService fileService;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@PostMapping("/file/upload")
public RespBean updateFile(MultipartFile file,int id)
System.out.println(id);
System.out.println(MD5Util.getMultiFileMd5(file));
if(fileService.uploadFile(file,id))
return RespBean.ok("上传成功");
return RespBean.error("图片过大或者格式不对");
@DeleteMapping("/file/id")
public RespBean deleteById(@PathVariable int id)
// System.out.println(id);
if(fileService.deleteById(id))
return RespBean.ok("删除成功");
return RespBean.error("删除失败");
@GetMapping("/file/getAll/id")
public RespBean getAll(@PathVariable String id)
return RespBean.ok("files-",fileService.getAllHrFiles(id));
@GetMapping("/file/getLoginHrId")
public RespBean getHrId(HttpServletRequest request)
String token = request.getHeader("token");
String s = stringRedisTemplate.opsForValue().get("id"+token);
return RespBean.ok("获取到用户id",s);
package com.me.controller;
import com.me.pojo.Hr;
import com.me.pojo.RespBean;
import com.me.service.HrService;
import org.csource.fastdfs.StorageClient1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
@RestController
public class HrController
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Autowired
private HrService hrService;
@GetMapping("/hr/getLoginUser")
public RespBean getLoginUser(HttpServletRequest request)
String token = request.getHeader("token");
String s = stringRedisTemplate.opsForValue().get(token);
// System.out.println("getLoginUser"+s);
Hr hr = hrService.loadUserByUsername(s);
return RespBean.ok("获取到用户",hr);
@PutMapping("/hr/pass")
public RespBean updateHrPasswd(@RequestBody Map<String, Object> info,HttpServletRequest request)
String oldpass = (String) info.get("oldpass");
String pass = (String) info.get("pass");
Integer hrid = (Integer) info.get("hrid");
System.out.println(hrid+pass);
if (hrService.updateHrPasswd(oldpass, pass, hrid))
//修改密码后需要重新登录
String token = request.getHeader("token");
Boolean b = stringRedisTemplate.delete(token);
return RespBean.ok("更新成功!请重新登录!");
return RespBean.error("更新失败!");
@PutMapping("/hr/info")
public RespBean updateHr(@RequestBody Hr hr)
if (hrService.updateHr(hr) == 1)
return RespBean.ok("更新成功!");
return RespBean.error("更新失败!");
@PostMapping("/hr/userface")
public RespBean updateHrUserface(MultipartFile file, Integer id)
System.out.println("face "+id);
if(hrService.updateHrUserface(file,id))
return RespBean.ok("更新成功!");
return RespBean.error("图片过大或者格式不对");
五,项目总结
项目采用springboot+vue实现前后端分离的项目开发,功能简洁大方,另外使用了redis缓存数据库和oss分布式文件存储服务,是项目的一大亮点。
以上是关于第二季SpringBoot+Vue前后端分离项目实战笔记的主要内容,如果未能解决你的问题,请参考以下文章
短视频社交|电影点播平台Springboot+vue+ElementUI前后端分离
还不会做毕业设计?-学生信息管理系统(springboot+vue前后端分离实)详细设计和实现
免费开源的智能家居系统,SpringBoot+Vue前后端分离,WiFi智能设备接入,手把手开发安卓APP,建立QQ智能管家机器人!