思路:对于用户的注册,简易的实现大概分为三个过程,首先是账号,密码,验证密码的规范校验,其次就是对前端返回的密码进行加密,最后是将账号,密码存入数据库。以下是代码
package com.zb.usercenter.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zb.usercenter.mapper.UserMapper;
import com.zb.usercenter.modal.User;
import com.zb.usercenter.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* @author 86135
* @description 针对表【user】的数据库操作Service实现
* @createDate 2023-10-14 19:30:10
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService {
@Override
public long UserRegister(String userAccount, String userPassword, String checkPassword) {
if (StringUtils.isAnyBlank(userAccount,userPassword,checkPassword)){
return -1;
}
if (userAccount.length()<4){
return -1;
}
if(userPassword.length()<8){
return -1;
}
//使用正则表达式来判断userAccount当中是否有特殊字符
String regex = "^[a-zA-Z0-9@._-]*[^@._-][a-zA-Z0-9@._-]*$";
Matcher matcher = Pattern.compile(regex).matcher(userAccount);
//m.find:如果匹配到相同的字符就返回true,这里如果匹配到相同的字符,说明使用了特殊字符
if(matcher.find()){
return -1;
}
//验证密码和校验密码是否相同
if (!userPassword.equals(checkPassword)){
return -1;
}
//mybatis_plus当中的查询方法
QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//在数据库中userAccount字段中的值是userAccount的有多少条
queryWrapper.eq("userAccount",userAccount);
long count =this.count(queryWrapper);
if (count>0){
return -1;
}
//2.加密
final String SALT="zhuabao";//加盐
String encryptPassword = DigestUtils.md5DigestAsHex((SALT + userPassword).getBytes());//使用md5加密算法
//3.插入数据
User user = new User();
user.setUserAccount(userAccount);
user.setUserPassword(encryptPassword);
boolean saveResult = this.save(user);
//如果没有保存成功
if(!saveResult){
return -1;
}
return user.getId();
}
}
1.账号,密码,确认密码的确认与规范
值得说明的是在对账号特殊字符的验证时,用到了正则表达式来检验账号中是否有特殊字符。以及使用mybatis_puls的queryWrapper方法查询数据库当中对应值出现的次数,如果为1那就说明数据库当中已经存在当前账号
2.加密
使用“加盐”的方法使密码更加复杂,再使用md5进行算法加密
3.插入数据并保存