当前位置:首页 > VUE

springboot加vue实现登录

2026-01-23 04:34:58VUE

技术选型与准备

后端采用Spring Boot 2.x,提供RESTful API;前端使用Vue 3(Composition API) + Vite构建工具,配合Axios进行HTTP请求。需安装Node.js、JDK 8+及Maven环境。

后端实现(Spring Boot)

  1. 项目结构
    创建Spring Boot项目,添加依赖:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
  2. 用户实体与数据库
    定义用户实体类并配置JPA或MyBatis:

    @Entity
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String username;
        private String password;
        // Getters & Setters
    }
  3. 安全配置
    自定义UserDetailsService并配置Spring Security:

    @Configuration
    @EnableWebSecurity
    public class SecurityConfig extends WebSecurityConfigurerAdapter {
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/login").permitAll()
                .anyRequest().authenticated();
        }
    }
  4. 登录API
    创建控制器处理登录请求:

    @RestController
    @RequestMapping("/api")
    public class AuthController {
        @PostMapping("/login")
        public ResponseEntity<?> login(@RequestBody LoginRequest request) {
            // 验证逻辑,返回JWT或Session标识
            return ResponseEntity.ok().body("登录成功");
        }
    }

前端实现(Vue 3)

  1. 项目初始化
    使用Vite创建Vue项目:

    npm create vite@latest vue-login --template vue
    cd vue-login
    npm install axios vue-router
  2. 登录页面
    创建Login.vue组件:

    <template>
      <form @submit.prevent="handleLogin">
        <input v-model="form.username" placeholder="用户名" />
        <input v-model="form.password" type="password" placeholder="密码" />
        <button type="submit">登录</button>
      </form>
    </template>
    
    <script setup>
    import { ref } from 'vue';
    import axios from 'axios';
    
    const form = ref({ username: '', password: '' });
    const handleLogin = async () => {
      try {
        const res = await axios.post('http://localhost:8080/api/login', form.value);
        console.log(res.data);
      } catch (error) {
        console.error(error);
      }
    };
    </script>
  3. 路由配置
    router/index.js中配置路由:

    import { createRouter, createWebHistory } from 'vue-router';
    import Login from '../views/Login.vue';
    
    const routes = [{ path: '/login', component: Login }];
    const router = createRouter({ history: createWebHistory(), routes });
    export default router;

跨域处理

后端添加CORS配置:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/")
                .allowedOrigins("http://localhost:3000")
                .allowedMethods("*");
    }
}

联调与测试

  1. 启动Spring Boot应用(默认端口8080)。
  2. 运行Vue开发服务器:npm run dev(默认端口3000)。
  3. 访问http://localhost:3000/login,输入凭证测试登录功能。

扩展建议

  • 后端:集成JWT实现无状态认证,或使用Spring Session管理会话。
  • 前端:添加Vuex/Pinia管理登录状态,结合路由守卫控制权限。

springboot加vue实现登录

标签: springbootvue
分享给朋友:

相关文章

vue实现主题

vue实现主题

Vue 实现主题的方法 使用 CSS 变量动态切换主题 定义全局 CSS 变量,通过修改这些变量实现主题切换。在 Vue 的根组件或全局样式中定义变量: :root { --primary-co…

vue实现素材

vue实现素材

Vue 实现素材的方法 使用 Vue 组件管理素材 在 Vue 项目中,可以通过组件化的方式管理素材。创建一个专门的组件来加载和显示素材,例如图片、视频或音频文件。组件可以接收素材的路径或 URL 作…

vue轮询实现

vue轮询实现

Vue 轮询实现方法 在 Vue 中实现轮询可以通过以下几种方式: 使用 setInterval data() { return { pollInterval: null } }…

vue实现ppt

vue实现ppt

Vue 实现 PPT 的功能 Vue 可以结合第三方库或自定义组件实现类似 PPT 的演示效果。以下是几种常见的方法: 使用第三方库 reveal.js reveal.js 是一个流行的演示框架,支…

vue 菜单实现

vue 菜单实现

Vue 菜单实现方法 在Vue中实现菜单功能可以通过多种方式完成,以下是几种常见的实现方法: 使用v-for动态生成菜单 通过数据驱动的方式动态渲染菜单项,适合菜单内容可能变化的场景: <t…

vue nexttick 实现

vue nexttick 实现

Vue nextTick 实现原理 Vue 的 nextTick 是一个用于在下次 DOM 更新循环结束之后执行延迟回调的方法。它主要用于确保在 DOM 更新完成后执行某些操作。 核心实现机制 n…