目录
关于短信发送可以看:使用阿里云实现短信发送服务(测试版)_QinYanan.的博客-CSDN博客
短信使用阿里云的短信功能,这里由于是个人,难以申请签名,只好先学着,使用测试短信。
具体可以看官方视频:Java SDK - 短信服务 - 阿里云
首先引入 maven 依赖
-
- <dependency>
- <groupId>com.aliyungroupId>
- <artifactId>aliyun-java-sdk-coreartifactId>
- <version>4.5.16version>
- dependency>
- <dependency>
- <groupId>com.aliyungroupId>
- <artifactId>aliyun-java-sdk-dysmsapiartifactId>
- <version>2.1.0version>
- dependency>
然后导入资料中的 SMSUtils 工具类

通过手机验证码登录时,涉及的表为user表,即用户表。结构如下:


发送验证码请求:

登录请求:



添加判断移动端登录状态的语句
- // 移动端
- if(request.getSession().getAttribute("user") != null){
- //Long id = Thread.currentThread().getId();
- //log.info("线程id为{}", id);
- //log.info("用户已登录,放行,用户id为{}", request.getSession().getAttribute("user"));
- Long userId = (Long) request.getSession().getAttribute("user");
- BaseContext.setCurrentId(userId);
-
- filterChain.doFilter(request, response);
- return;
- }
- package com.itheima.reggie.utils;
-
- import com.aliyuncs.DefaultAcsClient;
- import com.aliyuncs.IAcsClient;
- import com.aliyuncs.exceptions.ClientException;
- import com.aliyuncs.exceptions.ServerException;
- import com.aliyuncs.profile.DefaultProfile;
- import com.google.gson.Gson;
- import java.util.*;
- import com.aliyuncs.dysmsapi.model.v20170525.*;
- /*
- pom.xml
-
com.aliyun -
aliyun-java-sdk-core -
4.6.0 -
com.aliyun -
aliyun-java-sdk-dysmsapi -
2.2.1 - */
-
- public class SMSUtils {
-
- public static void sendMessage(String phone, String code) {
-
- DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "
" , "" ); - /** use STS Token
- DefaultProfile profile = DefaultProfile.getProfile(
- "
", // The region ID - "
", // The AccessKey ID of the RAM account - "
", // The AccessKey Secret of the RAM account - "
"); // STS Token - **/
-
- IAcsClient client = new DefaultAcsClient(profile);
-
- SendSmsRequest request = new SendSmsRequest();
- request.setSignName("阿里云短信测试");
- request.setTemplateCode("SMS_154950909");
- request.setPhoneNumbers(phone);
- request.setTemplateParam("{\"code\":\"" + code + "\"}");
-
- try {
- SendSmsResponse response = client.getAcsResponse(request);
- System.out.println(new Gson().toJson(response));
- } catch (ServerException e) {
- e.printStackTrace();
- } catch (ClientException e) {
- System.out.println("ErrCode:" + e.getErrCode());
- System.out.println("ErrMsg:" + e.getErrMsg());
- System.out.println("RequestId:" + e.getRequestId());
- }
-
- }
- }
在 UserController 中添加方法
- @RestController
- @RequestMapping("/user")
- @Slf4j
- public class UserController {
-
- @Autowired
- private UserService userService;
-
- /**
- * 发送手机验证码
- * @param user
- * @return
- */
- @PostMapping("/sendMsg")
- public R
sendMsg(@RequestBody User user, HttpSession session) throws ExecutionException, InterruptedException { - // 获取手机号
- String phone = user.getPhone();
- if(StringUtils.isNotEmpty(phone)) {
- // 生成随机的4为验证码
- String code = ValidateCodeUtils.generateValidateCode(4).toString();
- log.info("code={}", code);
-
- // 调用阿里云提供的短信服务API完成发送短信
- SMSUtils.sendMessage(phone, code);
-
- // 将验证码存储到Session中
- session.setAttribute(phone, code);
-
- return R.success("手机验证码发送成功");
- }
- return R.error("短信发送失败");
- }
-
- }
① 前端页面发送请求时没有携带验证码参数,需要修改前端页面
- this.loading = true
- // const res = await loginApi({phone:this.form.phone})
- const res = await loginApi(this.form)
- this.loading = false
② 在 UserController 中添加方法
- /**
- * 移动端用户登录
- * @param map
- * @param session
- * @return
- */
- @PostMapping("/login")
- public R
login(@RequestBody Map map, HttpSession session){ - // 获取手机号、验证码
- String phone = map.get("phone").toString();
- String code = map.get("code").toString();
-
- // 从session获取保存的验证码
- Object codeInSession = session.getAttribute(phone);
-
- // 验证码比对
- if(codeInSession != null && codeInSession.equals(code)){
- // 比对成功,登录成功
- // 判断当前手机号对应的用户是否为新用户,若是则自动完成注册
- LambdaQueryWrapper
queryWrapper = new LambdaQueryWrapper<>(); - queryWrapper.eq(User::getPhone, phone);
- User user = userService.getOne(queryWrapper);
- if(user == null){
- user = new User();
- user.setPhone(phone);
- user.setStatus(1);
- userService.save(user);
- }
- session.setAttribute("user", user.getId());
- return R.success(user);
- }
- return R.error("验证码错误,请重新输入");
- }