若依常用总结

无敌的宇宙
无敌的宇宙
擅长邻域:Java,HTML,JavaScript,MySQL,支付,退款,图片上传

分类: vue 专栏: vue 标签: 若依常用总结

2026-04-01 12:57:12 83浏览

若依常用总结

角色判断

 // 判断用户角色
        boolean isAdmin = "admin".equals(com.ruoyi.common.utils.SecurityUtils.getUsername()); // 是否为admin用户
        boolean isPurchaser = com.ruoyi.common.utils.SecurityUtils.hasRole("purchaser"); // 采购员
        boolean isSalesperson = com.ruoyi.common.utils.SecurityUtils.hasRole("salesperson");

后台过滤


目录ruoyi-framework
com.ruoyi.framework.config
SecurityConfig.java

protected SecurityFilterChain filterChain(HttpSecurity httpSecurity) throws Exception
    {
        return httpSecurity
            // CSRF禁用,因为不使用session
            .csrf(csrf -> csrf.disable())
            // 禁用HTTP响应标头
            .headers((headersCustomizer) -> {
                headersCustomizer.cacheControl(cache -> cache.disable()).frameOptions(options -> options.sameOrigin());
            })
            // 认证失败处理类
            .exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
            // 基于token,所以不需要session
            .sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            // 注解标记允许匿名访问的url
            .authorizeHttpRequests((requests) -> {
                permitAllUrl.getUrls().forEach(url -> requests.requestMatchers(url).permitAll());
                // 对于登录login 注册register 验证码captchaImage 允许匿名访问,这里添加/front/**
                requests.requestMatchers("/login", "/register", "/captchaImage", "/front/**").permitAll()
                    // 静态资源,可匿名访问
                    .requestMatchers(HttpMethod.GET, "/", "/*.html", "/**.html", "/**.css", "/**.js", "/profile/**").permitAll()
                    .requestMatchers("/swagger-ui.html", "/v3/api-docs/**", "/swagger-ui/**", "/druid/**").permitAll()
                    // 除上面外的所有请求全部需要鉴权认证
                    .anyRequest().authenticated();
            })
            // 添加Logout filter
            .logout(logout -> logout.logoutUrl("/logout").logoutSuccessHandler(logoutSuccessHandler))
            // 添加JWT filter
            .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class)
            // 添加CORS filter
            .addFilterBefore(corsFilter, JwtAuthenticationTokenFilter.class)
            .addFilterBefore(corsFilter, LogoutFilter.class)
            .build();
    }


前台过滤

ruoyi-ui/src/permission.js

import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isPathMatch } from '@/utils/validate'
import { isRelogin } from '@/utils/request'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register']

const isWhiteList = (path) => {
  return whiteList.some(pattern => isPathMatch(pattern, path))
}

router.beforeEach((to, from, next) => {
  if(to.path.indexOf("/front")>-1){
    next()
  }else{
    NProgress.start()
    if (getToken()) {
      to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
      /* has token*/
      if (to.path === '/login') {
        next({ path: '/' })
        NProgress.done()
      } else if (isWhiteList(to.path)) {
        next()
      } else {
        if (store.getters.roles.length === 0) {
          isRelogin.show = true
          // 判断当前用户是否已拉取完user_info信息
          store.dispatch('GetInfo').then(() => {
            isRelogin.show = false
            store.dispatch('GenerateRoutes').then(accessRoutes => {
              // 根据roles权限生成可访问的路由表
              router.addRoutes(accessRoutes) // 动态添加可访问路由表
              next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
            })
          }).catch(err => {
            store.dispatch('LogOut').then(() => {
              Message.error(err)
              next({ path: '/' })
            })
          })
        } else {
          next()
        }
      }
    } else {
      // 没有token
      if (isWhiteList(to.path)) {
        // 在免登录白名单,直接进入
        next()
      } else {
        next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
        NProgress.done()
      }
    }
  }

})

router.afterEach(() => {
  NProgress.done()
})


前台判断角色layout.vue

<template>
<div>
  <el-menu :default-active="activeIndex" class="el-menu-demo" mode="horizontal" @select="handleSelect">
    <el-menu-item index="1">首页</el-menu-item>
    <el-menu-item index="20">找工作</el-menu-item>
    <el-menu-item index="30">求贤才</el-menu-item>
    <el-menu-item index="70">找企业</el-menu-item>
    <el-menu-item index="80">网站公告</el-menu-item>


    <el-submenu index="40" style="float: right;"v-if="islogin==1">
      <template slot="title">
        <image-preview @click.native="goucenter" :src="lander.avatar" :width="40" :height="40"></image-preview>
        个人中心</template>

      <el-menu-item index="40-1"  v-if="ishr==1">发布职位</el-menu-item>
      <el-menu-item index="40-20" v-if="ishr==1">投递简历管理</el-menu-item>

      <el-menu-item index="40-30"   v-if="isstu==1">发布简历</el-menu-item>
      <el-menu-item index="40-40"  v-if="isstu==1">我投递的岗位</el-menu-item>

      <el-menu-item index="40-999">退出登录</el-menu-item>

    </el-submenu>
    <el-menu-item index="50"  style="float: right;" v-if="islogin==0">登录</el-menu-item>
    <el-menu-item index="60"  style="float: right;" v-if="islogin==0">注册</el-menu-item>
  </el-menu>
  <router-view>  </router-view>
  <el-footer></el-footer>
</div>
</template>
<script  >

import {getInfo} from "@/api/login";
import {isEmpty, isHttp} from "@/utils/validate";
import defAva from "@/assets/images/profile.jpg";
import {MessageBox} from "element-ui";
import router from "@/router";

export default {
  data() {
    return {
      activeIndex: '1',
      islogin:0,
      isstu:0,
      ishr:0,
      lander:'',
      roles:[],
    };
  },
  methods: {
    handleSelect(key, keyPath) {
      console.log(key, keyPath);
      if(key=='40-999')this.logout();
      if(key=='40-20')this.$router.push('/companyManage/wantjob')
      if(key=='40-40')this.$router.push('/findjobManage/mywantjob')
      if(key=='30')this.$router.push('/front/resume')
      if(key=='50')this.$router.push('/login')
      if(key=='60')this.$router.push('/register')
      if(key=='20')this.$router.push('/front/job')
      if(key=='70')this.$router.push('/front/company')
      if(key=='40-1')this.$router.push('/companyManage/givejob')
      if(key=='40-30')this.$router.push('/findjobManage/resume')
    },
    goucenter(){
        this.$router.push('/user/profile')
    },
    logout() {
      this.$confirm('确定注销并退出系统吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$store.dispatch('LogOut').then(() => {
          location.href = '/index'
        })
        localStorage.removeItem('login_uid')
      }).catch(() => {})
    },
    getUinfo(){

      getInfo().then(res => {
        this.lander=res.user;
        localStorage.lander=JSON.stringify(res.user)

        this.roles=res.roles
        localStorage.roles=JSON.stringify(res.roles)

        this.setRoles();

      }).catch(error => {

      })
    },
    setRoles(){
      if (this.roles && this.roles.length > 0) { // 验证返回的roles是否是一个非空数组
        for(let i=0;i<this.roles.length;i++){
          if(this.roles[i]=='admin'){
            this.isstu=1;
            this.ishr=1;

          }
          if(this.roles[i]=='findjober'){
            this.isstu=1;

          }
          if( this.roles[i]=='companyer'){
            this.ishr=1;

          }
        }
      }

    }

  },
  created() {
    if(this.$store.state.user.token ){
      this.islogin=1;
      this.getUinfo();
      try{
        this.lander=  JSON.parse( localStorage.lander)
        this.roles=  JSON.parse( localStorage.roles)
        this.setRoles()
      }catch (e) {

      }


    }
  }
}
</script>
<style scoped lang="scss">
.el-menu-demo{background-color: #fff200;}
</style>




子组件关闭

父组件代码
 <el-dialog title="投递简历" :visible.sync="tdOpen" width="800px" append-to-body  >
      <wantjob v-if="tdOpen" :job-id="currentJobId" @close="handleClose"/>
    </el-dialog>
handleClose(){
      this.tdOpen=false;
    },
    applyJob(item) {
       this.tdOpen=true;
       this.currentJobId=item.jobId;
    },


子组件代码
<script>

import {frontmylistResume} from '@/api/front/fresume'
import {addWantjob} from '@/api/front/fwantjob'
import ResumeDetail from "@/views/system/resume/detail.vue";

export default {
  name: "wantjobcomp",
  components: {ResumeDetail},
  props: {
    jobId: {
      type: [Number, String],
      required: true
    }
  },
  data() {
    return {
      detailOpen:false,
      currentResumeId:'',

      islogin:0,
      rli:[],
      msg:'',
      loading:false,
    };
  },
  methods: {
    tdHandle( row){
      addWantjob({jobId:this.jobId,resumeId:row.resumeId}).then(response => {
         this.$message.success("投递成功");
         this.$emit('close');//通知父组件关闭弹框
      })
    },
    detailHandle( row){
      this.detailOpen=true;
      this.currentResumeId=row.resumeId;
    },
      getrli(){
        this.loading=true;
        frontmylistResume({}).then(response => {
          this.rli = response.data
          this.loading=false;
        })
      }
  },
  created() {

  },
  watch: {
    jobId: {
      handler(newVal) {
        if (newVal) {
          if(this.$store.state.user.token ){
            this.getrli();
            this.msg=""
          }else{
            this.msg="登录后才可以投递 简历 哦"
          }

        }
      },
      immediate: true
    }
  }
}
</script>

navbar.vue添加返回首页的按钮

<router-link to="/front/index"><el-button type="warning" size="mini" style="margin: 10px;">返回招聘首页</el-button></router-link>

好博客就要一起分享哦!分享海报

此处可发布评论

评论(0展开评论

暂无评论,快来写一下吧

展开评论

您可能感兴趣的博客

客服QQ 1913284695