0


【第二季】【SpringBoot+Vue】前后端分离项目实战笔记

配套视频在b站:【第二季】全网最简单但实用的SpringBoot+Vue前后端分离项目实战

SpringBoot+Vue项目实战 第二季

一、些许优化

刷新丢失其它标签页

  1. 缓存已打开标签页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;}},

在这里插入图片描述

  1. 注销时删除所有tagview// 注销时删除所有tagviewawaitthis.$store.dispatch('tagsView/delAllViews')sessionStorage.removeItem('tabViews')

在这里插入图片描述

二、Swagger整合

Swagger-UI可以动态地根据注解生成在线API文档。

常用注解

  • @Api:用于修饰Controller类,生成Controller相关文档信息
  • @ApiOperation:用于修饰Controller类中的方法,生成接口方法相关文档信息
  • @ApiParam:用于修饰接口中的参数,生成接口参数相关文档信息
  • @ApiModelProperty:用于修饰实体类的属性,当实体类是请求参数或返回结果时,直接生成相关文档信息

整合步骤:

  1. 添加依赖<!--Swagger文档工具--><dependency><groupId>io.springfox</groupId><artifactId>springfox-boot-starter</artifactId><version>3.0.0</version></dependency>
  2. swagger配置类@Configuration@EnableOpenApi@EnableWebMvcpublicclassSwaggerConfig{@BeanpublicDocketapi(){returnnewDocket(DocumentationType.OAS_30).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.lantu")).paths(PathSelectors.any()).build();}privateApiInfoapiInfo(){returnnewApiInfoBuilder().title("神盾局特工管理系统接口文档").description("全网最简单的SpringBoot+Vue前后端分离项目实战").version("1.0").contact(newContact("qqcn","http://www.qqcn.cn","[email protected]")).build();}}
  3. 控制器根据需要添加swagger注解
  4. 测试:http://localhost:9999/swagger-ui/index.html

三、Jwt整合

JSON Web Token (JWT)是一个开放标准(RFC 7519),它定义了一种紧凑的、自包含的方式,用于作为JSON对象在各方之间安全地传输信息。该信息可以被验证和信任,因为它是数字签名的。

jwt形式举例:

eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI5MjAzOThjZi1hYThiLTQzNWUtOTIxYS1iNGQ3MDNmYmZiZGQiLCJzdWIiOiJ7XCJwaG9uZVwiOlwiMTIzNDIzNFwiLFwidXNlcm5hbWVcIjpcInpoYW5nc2FuXCJ9IiwiaXNzIjoic3lzdGVtIiwiaWF0IjoxNjc3MTE4Njc2LCJleHAiOjE2NzcxMjA0NzZ9.acc7H6-6ACqcgNu5waqain7th7zJciP-41z-qgWeaSY

⑴ 整合步骤

  1. pom<dependency><groupId>io.jsonwebtoken</groupId><artifactId>jjwt</artifactId><version>0.9.1</version></dependency>
  2. 工具类@ComponentpublicclassJwtUtil{// 有效期privatestaticfinallong JWT_EXPIRE =30*60*1000L;//半小时// 令牌秘钥privatestaticfinalString JWT_KEY ="123456";publicStringcreateToken(Object data){// 当前时间long currentTime =System.currentTimeMillis();// 过期时间long expTime = currentTime+JWT_EXPIRE;// 构建jwtJwtBuilder builder =Jwts.builder().setId(UUID.randomUUID()+"").setSubject(JSON.toJSONString(data)).setIssuer("system").setIssuedAt(newDate(currentTime)).signWith(SignatureAlgorithm.HS256,encodeSecret(JWT_KEY)).setExpiration(newDate(expTime));return builder.compact();}privateSecretKeyencodeSecret(String key){byte[] encode =Base64.getEncoder().encode(key.getBytes());SecretKeySpec aes =newSecretKeySpec(encode,0, encode.length,"AES");return aes;}publicClaimsparseToken(String token){Claims body =Jwts.parser().setSigningKey(encodeSecret(JWT_KEY)).parseClaimsJws(token).getBody();return body;}public<T>TparseToken(String token,Class<T> clazz){Claims body =Jwts.parser().setSigningKey(encodeSecret(JWT_KEY)).parseClaimsJws(token).getBody();return JSON.parseObject(body.getSubject(),clazz);}}
  3. 测试工具类
  4. 修改登录逻辑在这里插入图片描述在这里插入图片描述
  5. 测试登录

问题思考:

登录后续请求如何验证jwt ?

在这里插入图片描述

⑵ JWT验证拦截器

定义拦截器

@Component@Slf4jpublicclassJwtValidateInterceptorimplementsHandlerInterceptor{@AutowiredprivateJwtUtil jwtUtil;@OverridepublicbooleanpreHandle(HttpServletRequest request,HttpServletResponse response,Object handler)throwsException{String token = request.getHeader("X-Token");System.out.println(request.getRequestURI()+" 待验证:"+token);if(token !=null){try{
                jwtUtil.parseToken(token);
                log.debug(request.getRequestURI()+" 放行...");returntrue;}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令牌无效,请重新登录")));returnfalse;}}

注册拦截器

@ConfigurationpublicclassMyWebConfigimplementsWebMvcConfigurer{@AutowiredprivateJwtValidateInterceptor jwtValidateInterceptor;@OverridepublicvoidaddInterceptors(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@EnableWebMvcpublicclassSwaggerConfig{@BeanpublicDocketapi(){returnnewDocket(DocumentationType.OAS_30).apiInfo(apiInfo()).select().apis(RequestHandlerSelectors.basePackage("com.lantu")).paths(PathSelectors.any()).build().securitySchemes(Collections.singletonList(securityScheme())).securityContexts(Collections.singletonList(securityContext()));}privateSecuritySchemesecurityScheme(){//return new ApiKey("Authorization", "Authorization", "header");returnnewApiKey("X-Token","X-Token","header");}privateSecurityContextsecurityContext(){returnSecurityContext.builder().securityReferences(defaultAuth()).forPaths(PathSelectors.regex("^(?!auth).*$")).build();}privateList<SecurityReference>defaultAuth(){AuthorizationScope authorizationScope =newAuthorizationScope("global","accessEverything");AuthorizationScope[] authorizationScopes =newAuthorizationScope[1];
        authorizationScopes[0]= authorizationScope;returnCollections.singletonList(newSecurityReference("X-Token", authorizationScopes));}privateApiInfoapiInfo(){returnnewApiInfoBuilder().title("神盾局特工管理系统接口文档").description("全网最简单的SpringBoot+Vue前后端分离项目实战").version("1.0").contact(newContact("老蔡","https://space.bilibili.com/431588578","[email protected]")).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'exportdefault{// 分页查询角色列表getRoleList(searchModel){returnrequest({url:'/role/list',method:'get',params:{roleName: searchModel.roleName,pageNo: searchModel.pageNo,pageSize: searchModel.pageSize
      }});},// 新增addRole(role){returnrequest({url:'/role',method:'post',data: role
    });},// 修改updateRole(role){returnrequest({url:'/role',method:'put',data: role
    });},// 保存角色数据saveRole(role){if(role.roleId ==null|| role.roleId ==undefined){returnthis.addRole(role);}returnthis.updateRole(role);},// 根据id查询getRoleById(id){returnrequest({url:`/role/${id}`,method:'get'});},// 根据id删除deleteRoleById(id){returnrequest({url:`/role/${id}`,method:'delete'});},}

⑶ 后端

RoleController

@RestController@RequestMapping("/role")publicclassRoleController{@AutowiredprivateIRoleService roleService;@GetMapping("/list")publicResult<Map<String,Object>>getUserList(@RequestParam(value ="roleName",required =false)String roleName,@RequestParam(value ="pageNo")Long pageNo,@RequestParam(value ="pageSize")Long pageSize){LambdaQueryWrapper<Role> wrapper =newLambdaQueryWrapper<>();
        wrapper.eq(StringUtils.hasLength(roleName),Role::getRoleName,roleName);
        wrapper.orderByDesc(Role::getRoleId);Page<Role> page =newPage<>(pageNo,pageSize);
        roleService.page(page, wrapper);Map<String,Object> data =newHashMap<>();
        data.put("total",page.getTotal());
        data.put("rows",page.getRecords());returnResult.success(data);}@PostMappingpublicResult<?>addRole(@RequestBodyRole role){
        roleService.save(role);returnResult.success("新增角色成功");}@PutMappingpublicResult<?>updateRole(@RequestBodyRole role){
        roleService.updateById(role);returnResult.success("修改角色成功");}@GetMapping("/{id}")publicResult<Role>getRoleById(@PathVariable("id")Integer id){Role role = roleService.getById(id);returnResult.success(role);}@DeleteMapping("/{id}")publicResult<Role>deleteRoleById(@PathVariable("id")Integer id){
        roleService.removeById(id);returnResult.success("删除角色成功");}}

2. 角色权限设置显示

在这里插入图片描述

⑴ 前端

menuManage.js

import request from'@/utils/request'exportdefault{// 查询所有菜单数据getAllMenu(){returnrequest({url:'/menu',method:'get',});},}

role.vue

<el-form-itemprop="roleDesc"label="权限设置":label-width="formLabelWidth"><el-tree:data="menuList":props="menuProps"node-key="menuId"show-checkboxstyle="width:85%"default-expand-all></el-tree></el-form-item>

在这里插入图片描述
在这里插入图片描述

⑵ 数据库

x_menu表新增数据

deletefrom x_menu;insertinto`x_menu`(`menu_id`,`component`,`path`,`redirect`,`name`,`title`,`icon`,`parent_id`,`is_leaf`,`hidden`)values('1','Layout','/sys','/sys/user','sysManage','系统管理','userManage','0','N','0');insertinto`x_menu`(`menu_id`,`component`,`path`,`redirect`,`name`,`title`,`icon`,`parent_id`,`is_leaf`,`hidden`)values('2','sys/user','user',NULL,'userList','用户列表','user','1','Y','0');insertinto`x_menu`(`menu_id`,`component`,`path`,`redirect`,`name`,`title`,`icon`,`parent_id`,`is_leaf`,`hidden`)values('3','sys/role','role',NULL,'roleList','角色列表','roleManage','1','Y','0');insertinto`x_menu`(`menu_id`,`component`,`path`,`redirect`,`name`,`title`,`icon`,`parent_id`,`is_leaf`,`hidden`)values('4','Layout','/test','/test/test1','test','功能测试','form','0','N','0');insertinto`x_menu`(`menu_id`,`component`,`path`,`redirect`,`name`,`title`,`icon`,`parent_id`,`is_leaf`,`hidden`)values('5','test/test1','test1','','test1','测试点一','form','4','Y','0');insertinto`x_menu`(`menu_id`,`component`,`path`,`redirect`,`name`,`title`,`icon`,`parent_id`,`is_leaf`,`hidden`)values('6','test/test2','test2','','test2','测试点二','form','4','Y','0');insertinto`x_menu`(`menu_id`,`component`,`path`,`redirect`,`name`,`title`,`icon`,`parent_id`,`is_leaf`,`hidden`)values('7','test/test3','test3','','test3','测试点三','form','4','Y','0');

⑶ 后端

Menu类中新增

@TableField(exist =false)@JsonInclude(JsonInclude.Include.NON_EMPTY)privateList<Menu> children;@TableField(exist =false)privateMap<String,Object> meta =newHashMap<>();publicMap<String,Object>getMeta(){
    meta.put("title",this.title);
    meta.put("icon",this.icon);returnthis.meta;}

MenuController

@RestController@RequestMapping("/menu")publicclassMenuController{@AutowiredprivateIMenuService menuService;@GetMappingpublicResult<?>getAllMenu(){List<Menu> menuList =  menuService.getAllMenu();returnResult.success(menuList);}}

MenuSeviceImpl

@OverridepublicList<Menu>getAllMenu(){// 一级菜单LambdaQueryWrapper<Menu> wrapper =newLambdaQueryWrapper();
    wrapper.eq(Menu::getParentId,0);List<Menu> menuList =this.list(wrapper);// 子菜单setMenuChildren(menuList);return menuList;}privatevoidsetMenuChildren(List<Menu> menuList){if(menuList !=null){for(Menu menu:menuList){LambdaQueryWrapper<Menu> subWrapper =newLambdaQueryWrapper();
            subWrapper.eq(Menu::getParentId, menu.getMenuId());List<Menu> subMenuList =this.list(subWrapper);
            menu.setChildren(subMenuList);// 递归setMenuChildren(subMenuList);}}}

3. 角色权限新增提交

⑴ 前端

在这里插入图片描述

⑵ 后端

在这里插入图片描述

4. 角色权限回显

⑴ 前端

在这里插入图片描述

⑵ 后端

在这里插入图片描述

RoleMenuMapper.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPEmapperPUBLIC"-//mybatis.org//DTD Mapper 3.0//EN""http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mappernamespace="com.lantu.sys.mapper.RoleMenuMapper"><selectid="getMenuIdListByRoleId"parameterType="Integer"resultType="Integer">
        select
            a.`menu_id`
        from x_role_menu a, x_menu b
        where a.`menu_id` = b.`menu_id`
          and b.`is_leaf` = 'Y'
          and a.`role_id` = #{roleId}
    </select></mapper>

5. 角色权限修改提交

⑴ 后端

RoleServiceImpl新增

@Override@TransactionalpublicvoidupdateRole(Role role){// 更新role表this.updateById(role);// 清除原有权限LambdaQueryWrapper<RoleMenu> wrapper =newLambdaQueryWrapper<>();
    wrapper.eq(RoleMenu::getRoleId,role.getRoleId());
    roleMenuMapper.delete(wrapper);//新增权限for(Integer menuId : role.getMenuIdList()){
        roleMenuMapper.insert(newRoleMenu(null,role.getRoleId(),menuId));}}

6. 角色删除时删相关权限

⑴ 后端

在这里插入图片描述

五、用户角色设置

1. 角色展示

⑴ 前端

roleManage.js

// 查询所有角色列表getAllRole(){returnrequest({url:'/role/all',method:'get'});},

user.vue
在这里插入图片描述
在这里插入图片描述

⑵ 后端

RoleController

在这里插入图片描述

2. 新增用户时提交角色

⑴ 后端

在这里插入图片描述

UserServiceImpl
在这里插入图片描述

3. 角色回显

⑴ 后端

UserServiceImpl
在这里插入图片描述

4. 修改用户时提交角色

⑴ 后端

UserServiceImpl
在这里插入图片描述

5. 用户删除时删相关角色

⑴ 后端

UserServiceImpl
在这里插入图片描述

六、动态路由

1. 根据用户查询菜单

⑴ 后端

MenuMapper.xml

<selectid="getMenuListByUserId"resultType="Menu">
    SELECT *
    FROM x_menu a,
    x_role_menu b,
    x_user_role c
    WHERE a.`menu_id` = b.`menu_id`
    AND b.`role_id` = c.`role_id`
    AND a.`parent_id` = #{pid}
    AND c.`user_id` = #{userId}
</select>

yml

type-aliases-package: com.lantu.*.entity

MenuMapper.java

publicinterfaceMenuMapperextendsBaseMapper<Menu>{publicList<Menu>getMenuListByUserId(@Param("userId")Integer userId,@Param("pid")Integer pid);}

MenuServiceImpl

@OverridepublicList<Menu>getMenuListByUserId(Integer userId){// 一级菜单List<Menu> menuList =this.getBaseMapper().getMenuListByUserId(userId,0);// 子菜单setMenuChildrenByUserId(userId, menuList);return menuList;}privatevoidsetMenuChildrenByUserId(Integer userId,List<Menu> menuList){if(menuList !=null){for(Menu menu : menuList){List<Menu> subMenuList =this.getBaseMapper().getMenuListByUserId(userId, menu.getMenuId());
                menu.setChildren(subMenuList);// 递归setMenuChildrenByUserId(userId,subMenuList);}}}

通过user/info接口返回数据

UserServiceImpl

在这里插入图片描述

2. 前端动态路由处理

⑴ 修改原路由配置

src\router\index.js,保留基础路由,其它的删掉或注释

exportconst constantRoutes =[{path:'/login',component:()=>import('@/views/login/index'),hidden:true},{path:'/404',component:()=>import('@/views/404'),hidden:true},{path:'/',component: Layout,redirect:'/dashboard',children:[{path:'dashboard',name:'Dashboard',component:()=>import('@/views/dashboard/index'),meta:{title:'首页',icon:'dashboard',affix:true,noCache:false}}]},]

⑵ 获取菜单数据并保存至Vuex

src\store\modules\user.js

在这里插入图片描述

src\store\getters.js

在这里插入图片描述

⑶ 路由转换

修改src目录下的permission.js

在这里插入图片描述
在这里插入图片描述

import Layout from'@/layout'
// 路由转换let myRoutes =myFilterAsyncRoutes(store.getters.menuList);// 404
myRoutes.push({path:'*',redirect:'/404',hidden:true});// 动态添加路由
router.addRoutes(myRoutes);// 存至全局变量
global.myRoutes = myRoutes;next({...to,replace:true})// 防止刷新后页面空白
functionmyFilterAsyncRoutes(menuList){
  menuList.filter(menu=>{if(menu.component ==='Layout'){
      menu.component = Layout
      console.log(menu.component);}else{
      menu.component =require(`@/views/${menu.component}.vue`).default
    }// 递归处理子菜单if(menu.children && menu.children.length){
      menu.children =myFilterAsyncRoutes(menu.children)}returntrue})return menuList;}

⑷ 路由合并

src\layout\components\Sidebar\index.vue

在这里插入图片描述

测试预期结果,不同角色的用户登录后展示的菜单列表不一样。

至此,虽然实现动态菜单功能,但并没有解决安全问题,大家可以思考存在什么问题?

标签: vue.js spring boot java

本文转载自: https://blog.csdn.net/m0_37613503/article/details/129349710
版权归原作者 大菜007 所有, 如有侵权,请联系我们删除。

“【第二季】【SpringBoot+Vue】前后端分离项目实战笔记”的评论:

还没有评论