当前位置:首页 > VUE

vue springboot实现登陆

2026-02-23 23:33:32VUE

实现 Vue 和 Spring Boot 登录功能

前端 Vue 实现

创建登录页面 在 Vue 项目中创建一个登录组件,包含用户名和密码输入框以及提交按钮。使用 Vue 的双向数据绑定 v-model 来获取用户输入。

<template>
  <div>
    <input v-model="username" placeholder="用户名"/>
    <input v-model="password" type="password" placeholder="密码"/>
    <button @click="login">登录</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    login() {
      // 调用登录API
    }
  }
}
</script>

发送登录请求 使用 axios 发送 POST 请求到后端 Spring Boot 的登录接口,传递用户名和密码。

methods: {
  async login() {
    try {
      const response = await axios.post('http://localhost:8080/api/login', {
        username: this.username,
        password: this.password
      });
      // 处理登录成功
    } catch (error) {
      // 处理登录失败
    }
  }
}

后端 Spring Boot 实现

创建用户实体 定义一个用户实体类,包含用户名和密码字段。

@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String username;
    private String password;
    // getters and setters
}

创建登录接口 在 Spring Boot 中创建一个 REST 控制器处理登录请求。

@RestController
@RequestMapping("/api")
public class AuthController {

    @Autowired
    private UserRepository userRepository;

    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestBody LoginRequest loginRequest) {
        User user = userRepository.findByUsername(loginRequest.getUsername());
        if (user != null && user.getPassword().equals(loginRequest.getPassword())) {
            return ResponseEntity.ok().body("登录成功");
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
        }
    }
}

安全配置 配置 Spring Security 来保护接口,允许登录接口公开访问。

vue springboot实现登陆

@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();
    }
}

前后端联调

跨域问题解决 在 Spring Boot 中配置跨域支持,允许 Vue 前端访问后端接口。

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/")
            .allowedOrigins("http://localhost:8081") // Vue 开发服务器端口
            .allowedMethods("*");
    }
}

处理登录状态 在 Vue 中存储登录状态,可以使用 Vuex 或 localStorage 保存 token 或用户信息。

// 登录成功后保存 token
localStorage.setItem('token', response.data.token);
this.$router.push('/dashboard'); // 跳转到主页

错误处理 在 Vue 中显示后端返回的错误信息,增强用户体验。

vue springboot实现登陆

catch (error) {
  this.errorMessage = error.response.data.message;
}

安全性增强

密码加密 在后端使用 BCrypt 等加密算法存储密码,避免明文存储。

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

JWT 认证 实现 JWT 认证机制,替代简单的用户名密码验证。

// 生成 JWT token
String token = Jwts.builder()
    .setSubject(user.getUsername())
    .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
    .signWith(SignatureAlgorithm.HS512, SECRET.getBytes())
    .compact();

前端路由守卫 在 Vue 中实现路由守卫,保护需要认证的页面。

router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !localStorage.getItem('token')) {
    next('/login');
  } else {
    next();
  }
});

标签: vuespringboot
分享给朋友:

相关文章

vue实现用户信息表

vue实现用户信息表

Vue 实现用户信息表的方法 使用 Vue CLI 创建项目 安装 Vue CLI 并初始化项目: npm install -g @vue/cli vue create user-info-tabl…

vue实现文章锚点定位

vue实现文章锚点定位

实现文章锚点定位的方法 在Vue中实现文章锚点定位可以通过多种方式完成,以下是几种常见的方法: 使用原生HTML锚点 通过HTML的id属性和<a>标签的href属性实现锚点跳转。在Vu…

vue的实现

vue的实现

Vue 的实现原理 Vue 是一个渐进式 JavaScript 框架,其核心实现主要包括响应式系统、虚拟 DOM、模板编译和组件化机制。以下是 Vue 实现的主要技术细节。 响应式系统 Vue 的响…

vue实现hover

vue实现hover

Vue 实现 hover 效果的方法 在 Vue 中实现 hover 效果可以通过多种方式实现,包括使用 CSS、Vue 指令或事件监听。以下是几种常见的方法: 使用 CSS :hover 伪类 通…

vue实现frame

vue实现frame

Vue 中实现 iframe 的方法 在 Vue 中可以通过直接使用 <iframe> 标签或动态绑定 src 属性来实现 iframe 功能。 基本用法 <template&g…

vue实现长按

vue实现长按

Vue 实现长按功能的方法 在 Vue 中实现长按功能可以通过原生事件监听或自定义指令完成。以下是几种常见实现方式: 使用原生事件监听 通过 @mousedown 和 @mouseup 或 @tou…