当前位置:首页 > VUE

springboot加vue实现登录

2026-02-23 19:12:43VUE

实现SpringBoot与Vue登录功能

后端(SpringBoot)部分

  1. 创建SpringBoot项目
    使用Spring Initializr生成项目,添加依赖:

    • spring-boot-starter-web
    • spring-boot-starter-security
    • spring-boot-starter-data-jpa(如需数据库)
    • jjwt(用于JWT令牌生成)
  2. 配置Spring Security
    创建安全配置类,继承WebSecurityConfigurerAdapter

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/auth/").permitAll()
                .anyRequest().authenticated();
        }
    }
  3. 实现登录接口
    创建AuthController处理登录请求:

    @RestController
    @RequestMapping("/api/auth")
    public class AuthController {
        @PostMapping("/login")
        public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
            // 验证用户名密码
            // 生成JWT令牌
            return ResponseEntity.ok(new JwtResponse(jwtToken));
        }
    }

前端(Vue)部分

  1. 创建Vue项目
    使用Vue CLI创建项目:

    vue create vue-login-demo
  2. 安装axios
    用于发送HTTP请求:

    npm install axios
  3. 创建登录页面
    src/views下创建Login.vue

    <template>
      <form @submit.prevent="handleSubmit">
        <input v-model="username" placeholder="用户名">
        <input v-model="password" type="password" placeholder="密码">
        <button type="submit">登录</button>
      </form>
    </template>
    
    <script>
    import axios from 'axios';
    export default {
      data() {
        return {
          username: '',
          password: ''
        }
      },
      methods: {
        async handleSubmit() {
          try {
            const res = await axios.post('http://localhost:8080/api/auth/login', {
              username: this.username,
              password: this.password
            });
            localStorage.setItem('token', res.data.token);
            this.$router.push('/dashboard');
          } catch (error) {
            console.error(error);
          }
        }
      }
    }
    </script>
  4. 配置路由
    src/router/index.js中添加登录路由:

    import Login from '../views/Login.vue'
    const routes = [
      {
        path: '/login',
        name: 'Login',
        component: Login
      }
    ]

跨域处理

  1. 后端配置CORS
    在SpringBoot中添加配置类:

    @Configuration
    public class CorsConfig {
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurer() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/")
                        .allowedOrigins("http://localhost:8081")
                        .allowedMethods("*");
                }
            };
        }
    }
  2. 前端代理配置
    vue.config.js中配置代理:

    module.exports = {
      devServer: {
        proxy: {
          '/api': {
            target: 'http://localhost:8080',
            changeOrigin: true
          }
        }
      }
    }

JWT验证

  1. 后端JWT工具类
    创建JWT生成与验证工具:

    public class JwtUtils {
        private static final String SECRET_KEY = "your-secret-key";
    
        public static String generateToken(String username) {
            return Jwts.builder()
                .setSubject(username)
                .setIssuedAt(new Date())
                .setExpiration(new Date(System.currentTimeMillis() + 86400000))
                .signWith(SignatureAlgorithm.HS256, SECRET_KEY)
                .compact();
        }
    }
  2. 前端请求拦截
    main.js中配置axios拦截器:

    axios.interceptors.request.use(config => {
      const token = localStorage.getItem('token');
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
      return config;
    });

部署注意事项

  1. 生产环境需配置HTTPS
  2. 敏感信息应使用环境变量存储
  3. 前端打包后需配置Nginx反向代理

springboot加vue实现登录

标签: springbootvue
分享给朋友:

相关文章

vue实现前端分离

vue实现前端分离

Vue 实现前后端分离 前后端分离是一种架构模式,前端负责页面渲染和交互逻辑,后端提供数据接口。Vue.js 作为前端框架,非常适合实现前后端分离的开发模式。 核心实现步骤 创建 Vue 项目 使…

vue实现图库

vue实现图库

Vue 实现图库的基本方法 使用 Vue 实现图库功能可以通过多种方式完成,以下是一些常见的方法和实现步骤。 使用 Vue 和第三方库(如 Vue Gallery) 安装 vue-gallery 或…

jq 实现 vue

jq 实现 vue

jq 实现 Vue 的核心功能 jq 是一个轻量级的 JavaScript 库,主要用于 DOM 操作和事件处理。虽然它不能完全替代 Vue,但可以通过一些技巧模拟 Vue 的核心功能,如数据绑定、事…

vue菜单实现

vue菜单实现

Vue 菜单实现方法 使用 Element UI 的菜单组件 Element UI 提供了现成的菜单组件,适合快速实现导航菜单。安装 Element UI 后,可以直接使用 el-menu 相关组件。…

vue el 实现

vue el 实现

Vue 中使用 Element UI (el) 的实现方法 Element UI 是一个基于 Vue 的组件库,提供丰富的 UI 组件,常用于快速构建企业级中后台产品。以下介绍 Vue 项目中集成和使…

vue 实现流程

vue 实现流程

Vue 实现流程 Vue.js 是一个渐进式 JavaScript 框架,用于构建用户界面。以下是 Vue 实现的基本流程: 安装 Vue.js 通过 CDN 引入或使用 npm/yarn 安装:…