springboot加vue实现登录
技术选型与准备
后端采用Spring Boot 2.x,提供RESTful API;前端使用Vue 3(Composition API) + Vite构建工具,配合Axios进行HTTP请求。需安装Node.js、JDK 8+及Maven环境。
后端实现(Spring Boot)
-
项目结构
创建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> -
用户实体与数据库
定义用户实体类并配置JPA或MyBatis:@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String username; private String password; // Getters & Setters } -
安全配置
自定义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(); } } -
登录API
创建控制器处理登录请求:@RestController @RequestMapping("/api") public class AuthController { @PostMapping("/login") public ResponseEntity<?> login(@RequestBody LoginRequest request) { // 验证逻辑,返回JWT或Session标识 return ResponseEntity.ok().body("登录成功"); } }
前端实现(Vue 3)
-
项目初始化
使用Vite创建Vue项目:npm create vite@latest vue-login --template vue cd vue-login npm install axios vue-router -
登录页面
创建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> -
路由配置
在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("*");
}
}
联调与测试
- 启动Spring Boot应用(默认端口8080)。
- 运行Vue开发服务器:
npm run dev(默认端口3000)。 - 访问
http://localhost:3000/login,输入凭证测试登录功能。
扩展建议
- 后端:集成JWT实现无状态认证,或使用Spring Session管理会话。
- 前端:添加Vuex/Pinia管理登录状态,结合路由守卫控制权限。







