再次优化注册逻辑,修复登录bug

lzt
哆哆咯哆哆咯 3 months ago
parent 095ae0ef4c
commit 147865213c

@ -7,4 +7,5 @@ public class User {
private Integer id; private Integer id;
private String username; private String username;
private String password; private String password;
private String confirmPassword;
} }

@ -0,0 +1,8 @@
package com.example.User.Exceptions;
//处理登陆失败异常
public class LoginFailedException extends Exception{
public LoginFailedException(String message){
super(message);
}
}

@ -18,35 +18,39 @@ public class UserService {
this.passwordEncoder = passwordEncoder; this.passwordEncoder = passwordEncoder;
} }
// 用户注册 //用户注册
public User register(User user) throws UserAlreadyExistException, InvalidInputException { public User register(User user) throws UserAlreadyExistException, InvalidInputException {
// 输入检测 //输入检测
if (user.getUsername() == null || user.getUsername().trim().isEmpty()) { if (user.getUsername() == null || user.getUsername().trim().isEmpty()) {
throw new InvalidInputException("用户名不能为空"); throw new InvalidInputException("用户名不能为空");
} }
if (user.getPassword() == null || user.getPassword().trim().isEmpty()) { if (user.getPassword() == null || user.getPassword().trim().isEmpty()) {
throw new InvalidInputException("密码不能为空"); throw new InvalidInputException("密码不能为空");
} }
//比较两次输入的密码
if (!user.getPassword().equals(user.getConfirmPassword())) {
throw new InvalidInputException("两次输入的密码不一致");
}
// 检测用户名是否存在 //检测用户名是否存在
User existUser = userMapper.selectByUsername(user.getUsername()); User existUser = userMapper.selectByUsername(user.getUsername());
if (existUser != null) { if (existUser != null) {
throw new UserAlreadyExistException("用户已存在"); throw new UserAlreadyExistException("用户已存在");
} }
// 密码加密 //密码加密
user.setPassword(passwordEncoder.encode(user.getPassword())); user.setPassword(passwordEncoder.encode(user.getPassword()));
// 插入用户 //插入用户
userMapper.insert(user); userMapper.insert(user);
return user; return user;
} }
//用户登录 //用户登录
public User login(String username, String password) throws Exception { public User login(String username, String password) throws LoginFailedException {
User user = userMapper.selectByUsername(username); User user = userMapper.selectByUsername(username);
if (user == null || !user.getPassword().equals(password)) { if (user == null || !passwordEncoder.matches(password, user.getPassword())) {
throw new Exception("登陆失败,账号或密码错误"); throw new LoginFailedException("登陆失败,账号或密码错误");
} }
return user; return user;
} }

Loading…
Cancel
Save