验证码发送、校验

使用 StringRedisTemplate 实现发送验证码功能

大体流程:

在这里插入图片描述

手机号发送
@Controller
@RequestMapping("/code")
public class SMSCodeApi {

	private static final Logger LOG = LoggerFactory.getLogger(SMSCodeApi.class);
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	@GetMapping(path="/send")
	@ResponseBody
	public Boolean send(@RequestParam("mobile") String mobile) {
		//步骤一
		if (StringUtils.isEmpty(mobile)) {
			LOG.info("手机信号不能为空");
			return false;
		}
		//生成四位数随机号
		String code = String.valueOf((int)(1000*(Math.random() * 9 + 1)));
		//步骤二:调用第三方发送服务
		Boolean sendResult = sendMobileCode(mobile, code);
		if (!sendResult) {
			LOG.info("发送验证码失败");
			return false;
		}
		//步骤三:将手机号对应的验证码存储到 redis 里
		stringRedisTemplate.opsForValue().set(mobile, code);
		return true;
	}

	/**
	阿里云调用服务
	*/
	private boolean sendMobileCode(String mobile, String code) {
		LOG.info("");
		return true;
	}
}
接下来使用 mail 来发送验证码

先参考 spring boot 集成 mail,30秒看完

@Controller
@RequestMapping("/email")
public class EmailCodeApi {

	private static final Logger LOG = LoggerFactory.getLogger(EmailCodeApi);
	
	//JavaMailSender是Spring Boot集成的方法
	@Autowired
	private JavaMailSender mailSender;

	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	//把配置文件中的配置项注入进来
	@Value("${sendEmailAddress}")
	private String sendEmailAddress;

	@GetMapping("/send")
	@ResponseBody 
	public SimpleMailMessage sendMail(@RequestParam String email) {
		if (StringUtils.isEmpty(email)) {
			LOG.info("邮箱不能为空");
			return null;
		}
		SimpleMailMessage message = new SimpleMailMessage();
		if (StringUtils.isEmpty(sendEmailAddress)) {
			LOG.info("发件人不能为空");
			return null;
		}
		//验证码
		String code = String.valueOf((int)(1000 * (Math.random() * 9 + 1)));
		message.setFrom(sendEmailAddress);
		message.setTo(email);
		message.setSubject("发送验证码");
		message.setText(code);
		mailSender(message);
		
		//将验证码存储在 redis 中
		stringRedisTemplate.opsForValue().set(email, code);
		return message;
	}
}

校验验证码的流程

大体流程

在这里插入图片描述

@GetMapping
@ResponseBody
public Boolean verificateCode(@RequestParam String email, @RequestParam String code) {
	if (StringUtils.isEmpty(email)) {
		LOG.info("邮箱不能为空");
		return false;
	}
	if (StringUtils.isEmpty(code)) {
		LOG.info("验证码不能为空");
		return false;
	}
	//从 redis 中取出之前存储的验证码数据,进行比较
	String existCode = stringRedisTemplate.opsForValue().get(email);
	if (!code.equals(existCode)) {
		LOG.info("手机验证码失败");
		return false;
	}
	return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值