当前位置:首页 > VUE

springboot vue实现登录

2026-01-18 16:23:24VUE

Spring Boot 和 Vue 实现登录功能

后端(Spring Boot)

  1. 创建 Spring Boot 项目
    使用 Spring Initializr 创建一个项目,添加以下依赖:

    • Spring Web
    • Spring Security
    • Spring Data JPA
    • MySQL Driver
  2. 配置数据库
    application.propertiesapplication.yml 中配置数据库连接:

    spring.datasource.url=jdbc:mysql://localhost:3306/your_database
    spring.datasource.username=your_username
    spring.datasource.password=your_password
    spring.jpa.hibernate.ddl-auto=update
  3. 创建用户实体和 Repository
    定义用户实体类:

    @Entity
    @Table(name = "users")
    public class User {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String username;
        private String password;
        // Getters and Setters
    }

    创建 JPA Repository:

    public interface UserRepository extends JpaRepository<User, Long> {
        User findByUsername(String username);
    }
  4. 实现 Spring Security 配置
    创建安全配置类:

    @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();
        }
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder());
        }
    
        @Bean
        public PasswordEncoder passwordEncoder() {
            return new BCryptPasswordEncoder();
        }
    }
  5. 创建登录 API
    实现登录接口:

    @RestController
    @RequestMapping("/api/auth")
    public class AuthController {
        @Autowired
        private AuthenticationManager authenticationManager;
    
        @PostMapping("/login")
        public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
            try {
                Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsername(),
                        loginRequest.getPassword()
                    )
                );
                SecurityContextHolder.getContext().setAuthentication(authentication);
                return ResponseEntity.ok("Login successful");
            } catch (Exception e) {
                return ResponseEntity.status(401).body("Login failed");
            }
        }
    }

前端(Vue)

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

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

    npm install axios
  3. 创建登录页面
    src/views/Login.vue 中实现登录表单:

    <template>
      <div>
        <form @submit.prevent="login">
          <input v-model="username" placeholder="Username" />
          <input v-model="password" type="password" placeholder="Password" />
          <button type="submit">Login</button>
        </form>
      </div>
    </template>
    
    <script>
    import axios from 'axios';
    
    export default {
      data() {
        return {
          username: '',
          password: '',
        };
      },
      methods: {
        async login() {
          try {
            const response = await axios.post('http://localhost:8080/api/auth/login', {
              username: this.username,
              password: this.password,
            });
            alert(response.data);
          } catch (error) {
            alert('Login failed');
          }
        },
      },
    };
    </script>
  4. 配置路由
    src/router/index.js 中配置登录页路由:

    import Vue from 'vue';
    import Router from 'vue-router';
    import Login from '../views/Login.vue';
    
    Vue.use(Router);
    
    export default new Router({
      routes: [
        {
          path: '/login',
          name: 'Login',
          component: Login,
        },
      ],
    });
  5. 运行项目
    启动 Vue 项目:

    npm run serve

跨域问题解决

在 Spring Boot 中配置跨域支持:

springboot vue实现登录

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

测试登录功能

  1. 启动 Spring Boot 后端(默认端口 8080)。
  2. 启动 Vue 前端(默认端口 8081)。
  3. 访问 http://localhost:8081/login,输入用户名和密码测试登录功能。

标签: springbootvue
分享给朋友:

相关文章

vue架构实现

vue架构实现

Vue 架构实现核心方案 Vue.js 的架构实现通常围绕模块化、组件化和状态管理展开。以下为常见实现方案: 基于单文件组件(SFC)的模块化 通过 .vue 文件组织模板、脚本和样式: <…

vue实现接口

vue实现接口

在 Vue 中实现接口请求 Vue 本身不直接提供 HTTP 请求功能,通常需要借助第三方库如 axios 或 fetch 来实现接口请求。以下是几种常见方法: 使用 axios 发送请求 安装 a…

vue如何实现

vue如何实现

Vue 实现方法 在 Vue 中实现功能通常涉及组件化开发、状态管理和响应式数据绑定。以下是几种常见的实现方式: 组件化开发 使用 Vue 的单文件组件(.vue 文件)结构,将 UI 拆分为可复用…

vue实现hovuer

vue实现hovuer

Vue 实现 Hover 效果 在 Vue 中实现 hover 效果可以通过多种方式完成,以下是几种常见的方法: 使用 CSS 直接控制 通过 :hover 伪类实现,无需额外的 JavaScrip…

vue怎么实现 tab

vue怎么实现 tab

Vue 实现 Tab 的方法 使用动态组件和 v-if 通过动态组件或 v-if 指令切换不同 Tab 内容,结合点击事件改变当前激活的 Tab。 <template> &l…

vue实现部门树

vue实现部门树

Vue 实现部门树的方法 使用递归组件实现树形结构 递归组件是 Vue 中实现树形结构的常见方式。通过组件自身调用自身,可以轻松构建多层级的部门树。 <template> <d…