vue+springboot多角色登录

①前端编写

将Homeview修改为manager

Manager:

<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 :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" v-if="user.role === '管理员'">
            <template slot="title">
              <i class="el-icon-menu"></i>
              <span>信息管理</span>
            </template>
            <el-menu-item index="/user">用户信息</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: '/user' }">用户管理</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="@/assets/logo1.png" alt="" style="width: 40px; height: 40px; margin: 0 5px">
                <span>{{user.name}}</span>
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>个人信息</el-dropdown-item>
                <el-dropdown-item>修改密码</el-dropdown-item>
                <el-dropdown-item @click.native="logout">退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>

        </el-header>

        <!--        主体区域-->
        <el-main>
          <router-view></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',
      users: [],
      user:JSON.parse(localStorage.getItem('honey-user')||'{}'),
      url:'',
      urls:[]
    }
  },
  mounted() {
    // 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: {
    preview(url){
      window.open(url)
    },
    showUrls(){
      console.log(this.urls)
    },
    handleMutipleFileUpload(response,file,fileList){
      this.urls=fileList.map(v=>v.response?.data)
    },
    handleTableFileUpload(row,file,fileList){
      console.log(row,file,fileList)
      row.avatar=file.response.data
      // this.$set(row,'avatar',file.response.data)
      console.log(row)
      request.put('/user/update',row).then(res=>{
        if(res.code==='200'){
          this.$message.success('上传成功')
        }else{
          this.$message.error(res.msg)
        }
      })
    },
    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>

Home:

<template>
  <div>
    <div style="box-shadow: 0 0 10px rgba(0,0,0,.1); padding: 10px 20px; border-radius: 5px; margin-bottom: 10px">
      早安,{{user.name}},祝你开心每一天!
    </div>
    <div style="display: flex;">
      <el-card style="width: 100%;">
        <div slot="header" class="clearfix">
          <span>青哥哥带你做毕设2024</span>
        </div>
        <div>
          2024毕设正式开始了!青哥哥带你手把手敲出来!
          <div style="margin-top: 20px">
            <div style="margin: 10px 0"><strong>主题色</strong></div>
            <el-button type="primary">按钮</el-button>
            <el-button type="success">按钮</el-button>
            <el-button type="warning">按钮</el-button>
            <el-button type="danger">按钮</el-button>
            <el-button type="info">按钮</el-button>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script>
export default {
  name:'Home',
  data(){
    return{
      user:JSON.parse(localStorage.getItem('honey-user')||'{}')
    }
  }

}
</script>

<style scoped>

</style>

User:

<template>
  <div>
    <el-table :data="tableData" stripe>
      <el-table-column prop="id" label="ID"></el-table-column>
      <el-table-column prop="username" label="用户名"></el-table-column>
      <el-table-column prop="name" label="姓名"></el-table-column>
      <el-table-column prop="phone" label="手机号"></el-table-column>
      <el-table-column prop="email" label="邮箱"></el-table-column>
      <el-table-column prop="address" label="地址"></el-table-column>
      <el-table-column label="头像">
        <template v-slot="scope">
          <div style="display: flex;align-items: center">
            <el-image style="width: 50px;height: 50px;border-radius: 50%" v-if="scope.row.avatar" :src="scope.row.avatar" :preview-src-list="[scope.row.avatar]"></el-image>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="role" label="角色"></el-table-column>
      <el-table-column label="操作">
        <template v-slot="scope">
          <div style="display: flex">
            <el-button type="primary" plain size="mini">编辑</el-button>
            <el-button type="danger" plain size="mini">删除</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name:'User',
  data(){
    return{
      tableData:[]
    }
  },
  created() {
    this.load()
  },
  methods:{
    load(){
      this.$request.get('/user/selectall').then(res=>{
        this.tableData=res.data
      })
    }
  }
}
</script>

<style scoped>

</style>

router文件夹下的index.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Manager from '../views/Manager.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'manager',
    component: Manager,
    children:[
      {path:'home',name:'Home',component:()=>import('../views/manager/Home.vue')},
      {
        path:'user',name:'User',component:()=>import('../views/manager/User.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',
    component: ()=>import('../views/login.vue')
  },
  {
    path:'/register',
    name:'register',
    component: ()=>import('../views/register.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

export default router

②后端编写 

用navicate配置修改数据库:

Springboot修改:

User:

package com.example.springboot.entity;

import lombok.AllArgsConstructor;
import lombok.Data;

@Data
public class User {
    private Integer id;
    private String username;
    private String password;
    private String name;
    private String phone;
    private String email;
    private String address;
    private String avatar;
    private String token;
    private String role;
}

 ③编写路由守卫

修改如图部分:

修改vue中router文件夹下index.js:

import Vue from 'vue'
import VueRouter from 'vue-router'
import Manager from '../views/Manager.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'manager',
    component: Manager,
    children:[
      {path:'home',name:'Home',component:()=>import('../views/manager/Home.vue')},
      {
        path:'user',name:'User',component:()=>import('../views/manager/User.vue')
      },
      {
        path:'403',name:'Auth',component:()=>import('../views/Auth.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',
    component: ()=>import('../views/login.vue')
  },
  {
    path:'/register',
    name:'register',
    component: ()=>import('../views/register.vue')
  },
  {
    path:'*',
    name:'404',
    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

编写404和无权访问(403)页面:自行美化

404:

<template>
  <div>
    <div style="height: 100vh;display: flex;align-items: center;justify-content: center">
      <div style="font-size: 40px">    404 找不到页面
        <router-link to="/">返回首页</router-link>
      </div>
    </div>
  </div>
</template>

<script>
export default {

}
</script>

<style scoped>

</style>

Auth:

<template>
  <div>
    <div style="height: calc(100vh - 80px);display: flex;align-items: center;justify-content: center">
      <div style="font-size: 40px">
        无权访问
        <router-link to="/">返回首页</router-link>
      </div>
    </div>
  </div>
</template>

<script>
export default {

}
</script>

<style scoped>

</style>

注册页修改配置:

register:

<template>
  <div style="display: flex;align-items: center;justify-content: center;background-color: #669fefff;height: 100vh;">
    <div style="display: flex;width: 50%;background-color: white;border-radius: 5px;overflow: hidden;">
      <div style="flex: 1;">
        <img src="@/assets/register.png" alt="" style="width: 100%;">
      </div>
      <div style="flex: 1;display: flex;align-items: center;justify-content: center;">
        <el-form :model="user" style="width: 80%;" :rules="rules" ref="registerRef">
          <div style="font-weight: bold; font-size: 20px;margin-bottom: 20px;text-align: center;">
            欢迎注册后台管理系统
          </div>
          <el-form-item prop="username">
            <el-input placeholder="请输入用户名" v-model="user.username" prefix-icon="el-icon-user"></el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input placeholder="请输入密码" v-model="user.password" show-password prefix-icon="el-icon-lock"></el-input>
          </el-form-item>
          <el-form-item prop="confirmPass">
            <el-input placeholder="请确认密码" v-model="user.confirmPass"></el-input>
          </el-form-item>
          <el-form-item prop="role">
            <el-radio-group v-model="user.role">
              <el-radio label="用户">
              </el-radio>
              <el-radio label="商家">
              </el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" style="width: 100%;" @click="register">注册</el-button>
          </el-form-item>
          <div style="display: flex;">
            <div style="flex: 1;text-align: left">已没有账号?去<span style="color:aquamarine;cursor: pointer;" @click="$router.push('/login')">登录</span></div>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name:'register',
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码'));
      } else if(value !== this.user.password){
        callback(new Error('两次密码不一致'));
      } else {
        callback();
      }
    };
    return {
      code:'',
      user: {
        code:'',
        username: '',
        password: '',
        confirmPass:''
      },
      rules:{
        username:[{
          required:'true',message:'请输入账号',trigger:'blur'
        }],
        password:[{
          required:'true',message:'请输入密码',trigger:'blur'
        }],
        confirmPass:[{
          validator:validatePass,trigger:'blur'
        }],
        role:[
          {
            required:'true',message:'请选择角色',trigger:'blur'
          }
        ]
      },
    }
  },
  methods:{
    getCode(code){
      this.code=code.toLowerCase()
    },
    register(){
      this.$refs['registerRef'].validate((valid=>{
        if(valid){
          this.$request.post("/register",this.user).then(res=>{
            if(res.code === '200'){
              this.$router.push('/login')
              this.$message.success('注册成功')
            }else{
              this.$message.error(res.msg)
            }
            console.log(res);
          })
        }
      }))
    }
  }
}
</script>

<style scoped></style>

 修改springboot中的Mapper文件夹下的Usermapper:为insert数据库添加一个role属性

UserMapper:

package com.example.springboot.mapper;

import com.example.springboot.entity.User;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface UserMapper {
    @Insert("insert into `user` (username, password, name, phone, email, address, avatar, role) " +
            "values (#{username}, #{password}, #{name}, #{phone}, #{email}, #{address}, #{avatar},#{role})")
    void insert(User user);

    @Update("update `user` set username = #{username} , password = #{password} , name = #{name} , phone=#{phone} , email = #{email} , avatar=#{avatar} where id = #{id}")
    void updateUser(User user);

    @Delete("delete from `user` where id=#{id}")
    void deleteUser(Integer id);

    @Select("select * from `user` order by id desc")
    List<User> selectall();

    @Select("select * from `user` where id =#{id} order by id desc")
    User selectbyid(Integer id);

    @Select("select * from `user` where name = #{name} order by id desc")
    List<User> selectbyname(String name);
    @Select("select * from `user` where username = #{username} and name = #{name} order by id desc")
    List<User> selectbymore(@Param("username") String username,@Param("name") String name);

    @Select("select * from `user` where username like  concat('%',#{username},'%') or name like concat('%',#{name},'%') order by id desc")
    List<User> selectbymo(@Param("username") String username,@Param("name") String name);

    @Select("select * from `user` where username = #{username} order by id desc")
    User selectbyUsername(String username);

}

  • 12
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Spring Boot和Vue.js可以一起使用来实现多角色登录。在后端,可以使用Spring Security来实现身份验证和授权。在前端,可以使用Vue.js来构建用户界面和处理用户输入。可以使用JSON Web Token(JWT)来管理用户会话和授权。在登录时,用户可以选择不同的角色,每个角色有不同的权限和访问级别。在后端,可以使用Spring Security来管理角色和权限。在前端,可以使用Vue.js来显示不同的用户界面和控制用户访问。 ### 回答2: Spring Boot和Vue都是非常流行的技术,它们可以很好地结合在一起构建Web应用程序。多角色登录是一项很重要的功能,尤其是对于企业或管理系统,因为它可以让用户按照各自的权限访问不同的功能模块。下面将详细介绍如何使用Spring Boot和Vue构建多角色登录系统。 1. 后端实现 首先,我们需要在Spring Boot后端实现多角色登录功能。可以使用Spring Security框架来实现这一点。Spring Security框架提供了一些默认的登录页面和角色认证,同时也支持自定义登录页面和自定义角色认证。 在Spring Boot中使用Spring Security,需要添加以下依赖: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> ``` 在代码中,需要添加一个Security配置类,比如: ``` @Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private MyUserDetailsService userDetailsService; @Override protected void configure(HttpSecurity http) throws Exception { // 自定义登录页面 http.formLogin().loginPage("/login").permitAll() .and().authorizeRequests().anyRequest().authenticated() .and().csrf().disable(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { // 自定义角色认证 auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } } ``` 在这个配置类中,我们使用了自定义登录页面和自定义角色认证。在configure()方法中,我们定义了一个/form-login/的URL,当用户访问这个URL时,Spring Security会自动显示一个默认的登录页面。但是,我们可以使用自定义页面替换它。在configure(AuthenticationManagerBuilder auth)方法中,我们使用了一个自定义UserDetailsService来实现角色认证,这个UserDetailsService会从数据库中读取用户的角色信息,以及加密的密码。 2. 前端实现 在前端方面,我们可以使用Vue.jsVue Router来实现多角色登录Vue Router是Vue官方提供的路由插件,可以实现路由控制和页面导航等功能。 首先,在Vue中,我们需要定义一个App组件,用于显示整个Web应用程序的主界面。在这个App组件中,我们使用Vue Router来控制不同页面的跳转。 ``` <template> <div> <router-link to="/admin">管理员</router-link> <router-link to="/user">普通用户</router-link> <router-view></router-view> </div> </template> <script> import Admin from './Admin.vue'; import User from './User.vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); const routes = [ { path: '/admin', component: Admin }, { path: '/user', component: User } ]; const router = new VueRouter({ routes }); export default { router }; </script> ``` 在这个代码中,我们使用了<router-link>标签来实现页面跳转,当用户点击了这个标签时,Vue Router就会跳转到相应的页面。此外,我们还定义了两个子组件:Admin和User。这两个组件分别对应管理员和普通用户的功能模块。在Vue Router中,我们使用routes数组来定义路由,其中每个路由对象都包含一个path属性和一个component属性,表示路径和组件。 3. 多角色登录实现 最后,我们来看一下如何实现多角色登录。在前端中,可以使用axios或者fetch API从后端获取用户的角色信息,然后根据不同的角色跳转到不同的页面。 在Vue中,我们可以定义一个Login组件,用于显示登录页面。在这个组件中,我们使用axios或fetch API发送POST请求到后端,传递用户名和密码。后端会返回用户的角色信息和加密的密码(如果认证通过)。在前端中,我们可以将这些角色信息保存在sessionStorage中,然后使用Vue Router跳转到相应的页面。 ``` <template> <div> <h2>登录</h2> <input placeholder="用户名" v-model="username"> <input placeholder="密码" v-model="password"> <button @click="handleSubmit">登录</button> </div> </template> <script> import axios from 'axios'; export default { data() { return { username: '', password: '' }; }, methods: { handleSubmit() { axios.post('/login', { username: this.username, password: this.password }).then(response => { if (response.data.roles.includes('admin')) { sessionStorage.setItem('role', 'admin'); this.$router.push('/admin'); } else if (response.data.roles.includes('user')) { sessionStorage.setItem('role', 'user'); this.$router.push('/user'); } else { alert('登录失败'); } }).catch(error => { console.log(error); }); } } }; </script> ``` 在这个代码中,我们使用axios.post()方法发送POST请求到后端。当后端返回成功后,我们判断用户的角色信息并将它存储到sessionStorage中。之后,我们可以使用this.$router.push()方法来跳转到不同的页面。 综上所述,使用Spring Boot和Vue构建多角色登录系统并不复杂。只需要在后端中实现角色认证,然后在前端中根据不同的角色跳转到不同的页面即可。这种系统可以为企业或管理系统提供更灵活的权限管理和更高的安全保障。 ### 回答3: SpringBootVue是目前非常流行的后端框架和前端框架,它们可以非常好地协作来实现多角色登录的功能。 在实现多角色登录之前,我们需要先了解什么是角色,什么是权限。角色可以理解为用户的身份,而权限则是用户可以进行的操作。在多角色登录中,不同的角色可以拥有不同的权限。 在后端,我们可以使用Spring Security来实现多角色登录功能。它提供了丰富的API,使我们可以非常方便地实现身份验证和授权。 在前端,我们可以使用Vue和Element UI来实现多角色登录。Element UI提供了丰富的组件和样式,使我们可以非常方便地设计登录界面和权限管理界面。在Vue中,我们可以使用axios来与后端进行交互,获取用户信息和权限信息。 具体的实现步骤如下: 1. 在后端,我们需要创建对应的角色和权限表,并建立多对多的关系。 2. 配置Spring Security,实现身份验证和授权功能。 3. 在前端,设计登录界面,使用axios请求后端进行登录验证,获取用户信息和权限信息。 4. 根据不同的角色和权限,设计不同的页面和功能,使用Element UI实现权限管理。 最后,值得注意的是,多角色登录的实现并不是一次性完成的,需要通过不断迭代和优化来达到最佳效果。同时,在实现多角色登录过程中,我们也需要重视用户体验和安全性,保护用户的隐私和信息安全。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值