需求
- 输入手机号获取验证码,组织文档以短信形式发生给用户(页面模拟)
- 输入手机号和验证码验证结果
需求分析
- 提供controller,传入手机号,业务层通过手机号计算出独有的6位验证码数据,存入缓存返回此数据
- 提供controller,传入手机号和验证码,业务层通过手机号从缓存中读取验证码与输入验证码进行对比,返回对比结果
代码实现
pom:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
domain:
@Data
public class SMScode {
private String tele;
private String code;
}
SMSCodeService:
public interface SMSCodeService {
public String sendCodeToSMS(String tele);
public boolean checkCode(SMScode smScode);
}
SMSCodeServiceImpl:
@Service
public class SMSCodeServiceImpl implements SMSCodeService {
@Autowired
private CodeUtils codeUtils;
@Override
// @Cacheable(value = "SMScode",key = "#tele")
@CachePut(value = "SMScode",key = "#tele")
public String sendCodeToSMS(String tele) {
String code = codeUtils.generator(tele);
System.out.println(code);
return code;
}
@Override
public boolean checkCode(SMScode smscode) {
//取出缓存中的验证码与传递过来的验证码进行比对
String code = smscode.getCode();
System.out.println(code);
String cachecode = codeUtils.get(smscode.getTele());
System.out.println(cachecode);
return cachecode.equals(code);
}
}
CodeUtils:
@Component
public class CodeUtils {
private String[] patch = {"000000","00000","0000","000","00","0",""};
public String generator(String tele){
int hash = tele.hashCode();
int encryption = 20206666;
long result = hash ^ encryption;
long nowTime = System.currentTimeMillis();
result = result ^ nowTime;
long code = result % 1000000;
code= code < 0? -code : code;
String codeStr = code+"";
int len = codeStr.length();
return patch[len]+codeStr;
}
//取值
@Cacheable(value = "SMScode",key = "#tele")
public String get(String tele) {
return null;
}
}
SMSCodeController:
@RestController
@RequestMapping("/sms")
public class SMSCodeController {
@Autowired
private SMSCodeService smsCodeService;
@GetMapping
public String getCode(String tele){
String code = smsCodeService.sendCodeToSMS(tele);
return code;
}
@PostMapping
public boolean checkCode(String tele,String code){
System.out.println(tele);
System.out.println(code);
SMScode smScode = new SMScode();
smScode.setTele(tele);
smScode.setCode(code);
return smsCodeService.checkCode(smScode);
}
}