当前位置:首页 > 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;
    });

部署注意事项

springboot加vue实现登录

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

标签: springbootvue
分享给朋友:

相关文章

vue 实现fadeout

vue 实现fadeout

Vue 实现淡出效果 在 Vue 中实现淡出(fade-out)效果可以通过 CSS 过渡或动画结合 Vue 的动态渲染功能完成。以下是几种常见方法: 使用 Vue 过渡(Transition)组件…

实现vue vm

实现vue vm

Vue VM 实现方法 Vue VM(ViewModel)是 Vue.js 的核心概念之一,负责连接视图(View)和数据模型(Model)。以下是实现 Vue VM 的几种方法: 使用 Vue 实…

vue实现天猫

vue实现天猫

Vue实现天猫首页功能 使用Vue.js实现类似天猫的电商首页需要结合多个技术点,包括组件化开发、路由管理、状态管理、API调用等。以下是关键实现步骤: 项目初始化 创建Vue项目并安装必要依赖:…

vue实现复制文本

vue实现复制文本

实现复制文本的方法 在Vue中实现复制文本功能可以通过以下几种方式实现,每种方法适用于不同的场景。 使用原生JavaScript的execCommand方法 虽然execCommand方法已逐渐被弃…

vue实现主页切换

vue实现主页切换

Vue 实现主页切换的方法 在 Vue 中实现主页切换通常涉及路由配置和组件切换。以下是几种常见的方法: 使用 Vue Router 安装 Vue Router: npm install vue-…

vue实现关闭页面

vue实现关闭页面

关闭当前页面的方法 在Vue中关闭当前页面可以通过JavaScript的window.close()方法实现。该方法会关闭当前浏览器窗口或标签页。 methods: { closePage()…