一、发送邮箱,使用hutool工具包
使用aliyun邮箱作为发件邮箱,需要在邮箱中开启代收功能
1、引入依赖
userController代码
@GetMapping("/sendCodeEmail")public Integer sendCodeEmail(String mel){return userService.sendCodeEmail(mel);}
userService代码
public Integer sendCodeEmail(String email){MailAccount account = new MailAccount();account.setHost("smtp.aliyun.com");account.setPort(25);account.setAuth(true);account.setFrom("这里填入发件邮箱地址。。。");account.setUser("这里填入发件邮箱地址。。。");account.setPass("lj297014");int code = RandomUtil.randomInt(1000, 9999);//使用hutool格式化工具String content = StrUtil.format("您的验证码是:<B>{}<B>", code);MailUtil.send(account, CollUtil.newArrayList(email), "测试邮件发送接口", content, true);return 0;}
二、发送手机验证码
使用aliyun的短信服务
进入阿里云短信服务官网
拿到appcode
UserController代码
@GetMapping("/sendCodeTel")public Integer sendCodeTel(String tel){return userService.sendCodeTel(tel);}
UserService代码
public Integer sendCodeTel(String tel){String host = "https://dfsns.market.alicloudapi.com/data/send_sms";int code = RandomUtil.randomInt(1111, 9999);String result = HttpRequest.post(host).header("Authorization", "APPCODE "+"填入你的appcode码").body(StrUtil.format("content=code:{}&template_id=TPL_0000&phone_number={}", code, tel)).execute().body();JSONObject resultJosn = JSONUtil.parseObj(result);if(resultJosn.get("status").equals("ok")){// mapCodes.put(tel,String.valueOf(code));return 0;}throw new BizException(509,"短信发送失败");}
三、在注册方法中进行验证
使用hutool中带有缓存时间的map数组<电话或邮箱,验证码>进行存储
设置一分钟清理下缓存
在注册方法中拿到mapCode里的验证码和前端传入的验证码进行判断
代码
UserController
@PostMapping("/rigister")public Integer rigister(@RequestBody UserRegisterDto userRegisterDto){return userService.rigister(userRegisterDto);}
UserService
public Integer rigister(UserRegisterDto userRegisterDto) {//使用邮箱验证验证码String email = userRegisterDto.getEmail();String code = userRegisterDto.getCode();String codeMap = mapCodes.get(email, false);if(!codeMap.equals(code)){throw new BizException(600,"邮箱验证码不正确");}
// //使用手机验证验证码
// String tel = userRegisterDto.getTel();
// String code = userRegisterDto.getCode();
// String codeMap = mapCodes.get(tel, false);
// if(!codeMap.equals(code)){
// throw new BizException(600,"邮箱验证码不正确");
// }boolean ismobile = Validator.isMobile(userRegisterDto.getTel());if(ismobile == false){throw new BizException(503,"请输入正确的手机号");}boolean isemail = Validator.isEmail(userRegisterDto.getEmail());if (isemail == false){throw new BizException(504,"请输入正确的邮箱");}boolean isMatch = ReUtil.isMatch("^\\d{6}$", userRegisterDto.getPassword());if (isMatch == false){throw new BizException(505,"请输入至少6位数字的密码");}User user1 = userDao.selectBytel(userRegisterDto.getTel());if (!ObjUtil.isEmpty(user1)){throw new BizException(506,"用户已经存在");}//插入到用户表userDao.insert(userRegisterDto);return 0;}
}
四、用到的技术,遇到的问题
2、hutool工具代替上面map集合,可设置保存时间
hutool工具对象转换
在查询语句中写上limit 1后,表示找到数据就不再扫描查询后面的表了
验证密码
使用hutool里面的校验工具
可以在网站中找:正则表达式在线测试 | 菜鸟工具 (jyshare.com)
我这里选用的是数字
在使用发短信时,appcode后面要加上个空格
在注册页面取验证码时,一定要加false,要不然会无限刷新
缓存(Hutool-cache) - 超时-TimedCache - 《Hutool v5.6.0 参考文档》 - 书栈网 · BookStack