注意: 通过手机验证码登录,手机号是区分不同用户的标识
1. 导入依赖
<dependency>
<groupId>com.aliyun</groupId>
<artifactId>dysmsapi20170525</artifactId>
<version>2.0.24</version>
</dependency>
public class SendMessage {
public static Result send(String phone, String code) {
try {
Client client = com.kfm.captcha.service.impl.SendMessage.createClient(
System.getenv("accessKeyId"),
System.getenv("accessKeySecret"));
SendSmsRequest sendSmsRequest = new SendSmsRequest()
.setPhoneNumbers(phone)
.setTemplateCode("SMS_18035xxxx")
.setSignName("签名名称") .setTemplateParam("{\"code\":\"" + code + "\"}");
SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, new RuntimeOptions());
System.out.println("短信发送成功");
} catch (TeaException error) {
// 如有需要,请打印 error
Common.assertAsString(error.message);
} catch (Exception _error) {
TeaException error = new TeaException(_error.getMessage(), _error);
// 如有需要,请打印 error
Common.assertAsString(error.message);
}
return new Result(200,"发送成功",null);
}
public static Client createClient(String accessKeyId, String accessKeySecret) {
Config config = new Config()
.setAccessKeyId(accessKeyId)
.setAccessKeySecret(accessKeySecret);
// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
config.endpoint = "dysmsapi.aliyuncs.com";
try {
return new Client(config);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
public class Validation {
//生成随机6位数
public static String generateCode() {
int code = (int) (Math.random() * 900000) + 100000;
return String.valueOf(code);
}
}
@Data
public class Result implements Serializable {
private int code;
private String msg;
private Object data;
}
@PostMapping("/captcha")
public Result getCaptcha(@RequestParam("cellphone") String cellphone, HttpSession session) {
if (cellphone == null) {
return new Result(400, "phone is null",null);
}
//1. 生成验证码
String code = Validation.generateCode();
//2. 将生成的验证码保存到 session 或者 redis ,这里演示存储在session中
session.setAttribute(cellphone, code);
try {
return SendMessage.send(cellphone, code); // 发送验证码
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// 传过来的phone:xxxx,code:xxx 也可以用map集合接收
@PostMapping("/login")
@ResponseBody
public Result login(@RequestParam("phone") String phone, @RequestParam("code") String code, HttpSession session) {
// 1. 从Session中获取保存的验证码
Object codeInSession = session.getAttribute(phone);
// 2. 进行验证码比对(页面提交的验证码和Session中保存的验证码比对)
if (codeInSession != null && codeInSession.equals(code)) {
//3.对比成功,说明登录成功
//4. 在数据库根据手机号查找相关信息并返回
return new Result(200, "登录成功",null);
}
return new Result(400, "登录失败",null);
}
基于layui
util.on('lay-on', {
// 获取验证码
'reg-get-vercode': function(othis){
var isvalid = form.validate('#reg-cellphone'); // 主动触发验证,v2.7.0 新增
// 验证通过
if(isvalid){
layer.msg('手机号规则验证通过');
// 此处可继续书写「发送验证码」等后续逻辑
.ajax({
url: '/captcha',
type: 'POST',
data: {
cellphone:('#reg-cellphone').val()
},
dataType: 'json',
success: function (res) {
if (res.code === 200) {
layer.msg('验证码已发送,请注意查收');
} else {
layer.msg(res.msg);
}
}
});
}
}
});
// 提交事件
form.on('submit(demo-reg)', function(data){
var field = data.field; // 获取表单字段值
// 此处可执行 Ajax 等操作
$.ajax({
url: '/login',
type: 'POST',
data: {
phone: field.cellphone,
code: field.vercode
},
dataType: 'json',
success: function (res) {
if (res.code === 200) {
layer.msg('登录成功');
} else {
layer.msg(res.msg);
}
}
});
return false; // 阻止默认 form 跳转
});
powered by kaifamiao