以下是Spring Boot+Vue实现登录功能的具体代码和步骤:

后端(Spring Boot)

1. 添加依赖:在pom.xml中添加spring-boot-starter-security依赖用于安全和用户认证。

2. 创建实体类:创建User实体类,用于存储用户信息,包含用户名、密码等字段。

3. 实现UserDetailsService接口:创建UserDetailsServiceImpl类,实现UserDetailsService接口,重写loadUserByUsername方法,根据用户名从数据库中加载用户信息。

4. 配置Spring Security:创建WebSecurityConfig类,继承WebSecurityConfigurerAdapter,重写configure方法,配置Spring Security,指定哪些路径是受保护的,哪些是公开的。

5. 创建认证控制器:创建AuthController,处理登录请求。在登录方法中,使用AuthenticationManager进行用户认证,认证成功后将用户信息存入SecurityContextHolder。

前端(Vue)

1. 安装axios:在Vue项目中,通过npm install axios安装axios用于发送HTTP请求。

2. 创建登录组件:创建Login.vue组件,在模板中添加用户名和密码输入框以及登录按钮。在script部分,定义data中的username和password变量,用于存储用户输入的信息。通过axios发送POST请求到后端的/login接口,根据后端返回的响应判断登录是否成功,成功则跳转到首页,失败则提示错误信息。

以下是部分关键代码示例:

后端AuthController登录方法
@RestController
@RequestMapping("/api")
public class AuthController {

    private final AuthenticationManager authenticationManager;

    public AuthController(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }

    @PostMapping("/login")
    public ResponseEntity<String> login(@RequestBody User user) {
        try {
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword())
            );
            SecurityContextHolder.getContext().setAuthentication(authentication);
            return ResponseEntity.ok("登录成功");
        } catch (AuthenticationException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("用户名或密码错误");
        }
    }
}
前端Login.vue组件
<template>
  <div>
    <h1>登录</h1>
    <el-form ref="form" :model="form" label-width="80px">
      <el-form-item label="用户名">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="form.password" type="password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="login">登录</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import axios from 'axios';
import { useRouter } from 'vue-router';

export default {
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    };
  },
  methods: {
    async login() {
      try {
        const response = await axios.post('/api/login', this.form);
        if (response.data === '登录成功') {
          const router = useRouter();
          router.push('/home');
        } else {
          alert('登录失败,请检查用户名和密码');
        }
      } catch (error) {
        console.error('登录请求失败', error);
        alert('登录请求失败,请稍后重试');
      }
    },
    resetForm() {
      this.form.username = '';
      this.form.password = '';
    }
  }
};
</script>
以上代码实现了基本的登录功能,实际应用中还需要添加错误处理、表单验证、跨域资源共享(CORS)的配置,以及使用JWT或类似技术来处理用户会话等。

Logo

开源鸿蒙跨平台开发社区汇聚开发者与厂商,共建“一次开发,多端部署”的开源生态,致力于降低跨端开发门槛,推动万物智联创新。

更多推荐