本文介绍: 【代码】SpringBoot+Vue实现一个系统登录功能。

1. 创建一个Spring Boot项目,添加Web和Security依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

2. 创建一个User实体类,用于存储用户信息。

public class User {
    private String username;
    private String password;
    // getter和setter方法
}

3. 创建一个UserDetailsService接口的实现类,用于加载用户信息。

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 从数据库或其他数据源获取用户信息
        User user = userRepository.findByUsername(username);
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在");
        }
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(), new ArrayList<>());
    }
}

4. 创建一个WebSecurityConfig类,继承WebSecurityConfigurerAdapter,并重写configure方法,配置SpringSecurity。

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private UserDetailsService userDetailsService;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable()
            .authorizeRequests()
            .antMatchers("/login").permitAll()
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .loginPage("/login")
            .permitAll()
            .and()
            .logout()
            .permitAll();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(new BCryptPasswordEncoder());
    }
}

5. 在Vue项目中创建一个登录组件,包含用户名和密码输入框以及登录按钮。使用axios发送POST请求到SpringBoot后端的/login接口。

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

<script>
import axios from "axios";

export default {
  data() {
    return {
      username: "",
      password: "",
    };
  },
  methods: {
    async login() {
      try {
        const response = await axios.post("/login", {
          username: this.username,
          password: this.password,
        });
        if (response.data.success) {
          this.$router.push("/home");
        } else {
          alert("登录失败");
        }
      } catch (error) {
        console.error(error);
      }
    },
  },
};
</script>

6. 在Spring Boot后端的Controller中处理登录请求,验证用户名和密码是否正确,返回相应的响应。

@RestController
public class LoginController {
    @Autowired
    private UserRepository userRepository;

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

7. 运行Spring Boot项目和Vue项目,测试登录功能。

原文地址:https://blog.csdn.net/qq_41243828/article/details/135559164

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_55748.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注