SpringBoot+Vue实现一个系统登录功能

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

java 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

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

java 复制代码
public class User {
    private String username;
    private String password;
    // getter和setter方法
}

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

java 复制代码
@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。

java 复制代码
@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接口。

html 复制代码
<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中处理登录请求,验证用户名和密码是否正确,返回相应的响应。

java 复制代码
@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项目,测试登录功能。

相关推荐
mldong7 分钟前
一个 npm 包,九页审批中心:Vue3 项目接上工作流引擎
前端·javascript·vue.js
高频因子挖掘机12 分钟前
多股票 K 线如何用 Pandas 对齐?从收益率计算到横截面分析
后端·github·api
高级程序源8 小时前
django校园寻物通失物招领平台32261-计算机课程设计、毕业设计
vue.js·python·mysql·小程序·django·flask·课程设计
WeiXin_DZbishe8 小时前
基于springboot宠物领养系统-计算机毕设 附源码【课程设计】94217
vue.js·spring boot·python·django·php·课程设计
架构技术专栏9 小时前
Agent 工具调用:从工具声明到执行反馈
前端·人工智能·后端
vx_bisheyuange9 小时前
基于SpringBoot的体育商品推荐系统
spring boot·毕业设计
码事漫谈9 小时前
你让AI干的活,它可能只干了十分之一——而你根本看不出来
后端
Wx-bishekaifayuan10 小时前
express皖美特色农产品网售系统53118-计算机课程设计、毕业设计
人工智能·spring boot·后端·python·课程设计·express·旅游
Wx-bishekaifayuan10 小时前
springboot汉中旅游服务平台41442-计算机课程设计、毕业设计
spring boot·后端·python·django·课程设计·express·旅游
WeiXin_DZbishe11 小时前
基于springboot城市公交实时运营与调度系统-计算机毕设 附源码【课程设计】66173
java·vue.js·spring boot·后端·python·php·课程设计