代码写在reggie_take_out5中了

从这里就到了移动端开发

1. 效果展示  5-12

手机验证码登录_java

2. 短信发送  5-13

2.1 短信服务介绍  5-13

目前市面.上有很多第三方提供的短信服务,这些第三方短信服务会和各个运营商(移动、联通、电信)对接,我们只需要注册成为会员并且按照提供的开发文档进行调用就可以发送短信。需要说明的是,这些短信服务一般都是收费服务。

常用短信服务:

●阿里云

●华为云

●腾讯云

●京东

●梦网

●乐信

2.1.1 阿里云短信服务   5-13

阿里云短信服务(Short Message Service)是广大企业客户快速触达手机用户所优选使用的通信能力。调用API或用群发助手,即可发送验证码、通知类和营销类短信;国内验证短信秒级触达,到达率最高可达99%;国际/港澳台短信覆盖200多个国家和地区,安全稳定,广受出海企业选用。

应用场景:

●验证码

●短信通知

●推广短信

手机验证码登录_验证码_02

阿里云官网: https://www.aliyun.com/

短信产品官网https://www.aliyun.com/product/sms?spm=5176.28055625.J_3207526240.149.255b154abo6DtO

2.2 短信发送  5-14

阿里云官网: https://www.aliyun.com/

点击官网首页注册按钮,跳转到如下注册页面:

手机验证码登录_User_03

手机验证码登录_验证码_04

手机验证码登录_验证码_05

类似于这样

手机验证码登录_User_06

2.3 阿里云短信服务-设置AccessKey   5-14

光标移动到用户头像上,在弹出的窗口中点击[AccessKey 管理] :

步骤

手机验证码登录_java_07

手机验证码登录_User_08

手机验证码登录_User_09

手机验证码登录_验证码_10

手机验证码登录_验证码_11

手机验证码登录_验证码_12

2.4 开发文档示例  5-15

使用阿里云短信服务发送短信,可以参照官方提供的文档即可。

具体开发步骤:

1、导入maven坐标

2、调用API

手机验证码登录_验证码_13

1、导入maven坐标

<!--阿里云短信服务  5-17-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.5.16</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>2.1.0</version>
        </dependency>

2、调用API

DefaultProfile profile = DefaultProfile. getProfile("cn-hangzhou", "<accessKeyId>", "<accessKeySecret>");
IAcsClient client = new DefaultAcsClient(profile);
SendSmsRequest request = new SendSmsRequest();
request. setSysRegionId( "cn-hangzhou");
request . setPhoneNumbers (phoneNumbers);//给那个手机号发送短信
request. setSignName(signName);//签名
request . setTemplateCode( templateCode);//模板code
request. setTemplateParam("{\"code\": \"+param+"\"}");//动态替换param 也就是验证码
try {
    SendSmsResponse response = client. getAcsResponse(request);
    System. out . print1n(”短信发送成功");
}catch (ClientException e) {
    e.printStackTrace();
}

3. 短信验证码功能开发  5-16

3.1 需求分析  5-16

为了方便用户登录,移动端通常都会提供通过手机验证码登录的功能。

手机验证码登录的优点:

●方便快捷,无需注册,直接登录

●使用短信验证码作为登录凭证,无需记忆密码

●安全

登录流程:

输入手机号>获取验证码>输入验证码>点击登录>登录成功

注意:通过手机验证码登录,手机号是区分不同用户的标识。

手机验证码登录_java_14

3.2 数据模型  5-16

user表

手机验证码登录_验证码_15

3.3 代码开发-梳理交互过程  5-17

在开发代码之前,需要梳理一下登录时前端页面和服务端的交互过程:

1、在登录页面(front/ page/login.html)输入手机号, 点击[获取验证码]按钮,页面发送ajax请求,在服务端调用短信服务API给指定手机号发送验证码短信

2、在登录页面输入验证码,点击[登录]按钮,发送ajax请求,在服务端处理登录请求开发手机验证码登录功能,其实就是在服务端编写代码去处理前端页面发送的这2次请求即可。

3.4 准备工作    5-17

手机验证码登录_java_16

短信登录 用户信息实体类User

package com.itheima.reggie.entity;

import lombok.Data;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.io.Serializable;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
/**
 * 短信登录 用户信息实体类  5-17
 */
@Data
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    private Long id;


    //姓名
    private String name;


    //手机号
    private String phone;


    //性别 0 女 1 男
    private String sex;


    //身份证号
    private String idNumber;


    //头像
    private String avatar;


    //状态 0:禁用,1:正常
    private Integer status;
}

短信登录持久层接口UserMapper

package com.itheima.reggie.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.itheima.reggie.entity.User;
import org.apache.ibatis.annotations.Mapper;

//短信登录持久层接口  5-17
@Mapper
public interface UserMapper extends BaseMapper<User>{
}

短信登录 业务层接口UserService

package com.itheima.reggie.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;

//短信登录 业务层接口  5-17
public interface UserService extends IService<User> {
}

短信登录 业务层接口实现类 UserServiceImpl

package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.mapper.UserMapper;
import com.itheima.reggie.service.UserService;
import org.springframework.stereotype.Service;

//短信登录 业务层接口实现类  5-17
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper,User> implements UserService{
}

短信登录 控制层UserController

package com.itheima.reggie.controller;

import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//短信登录 控制层  5-17
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;
    
}

工具类

SMSUtils

package com.itheima.reggie.utils;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;

/**
 * 短信发送工具类
 */
public class SMSUtils {

	/**
	 * 发送短信
	 * @param signName 签名
	 * @param templateCode 模板
	 * @param phoneNumbers 手机号
	 * @param param 参数
	 */
	public static void sendMessage(String signName, String templateCode,String phoneNumbers,String param){
		DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", "", "");
		IAcsClient client = new DefaultAcsClient(profile);

		SendSmsRequest request = new SendSmsRequest();
		request.setSysRegionId("cn-hangzhou");
		request.setPhoneNumbers(phoneNumbers);
		request.setSignName(signName);
		request.setTemplateCode(templateCode);
		request.setTemplateParam("{\"code\":\""+param+"\"}");
		try {
			SendSmsResponse response = client.getAcsResponse(request);
			System.out.println("短信发送成功");
		}catch (ClientException e) {
			e.printStackTrace();
		}
	}

}

ValidateCodeUtils

package com.itheima.reggie.utils;

import java.util.Random;

/**
 * 随机生成验证码工具类
 */
public class ValidateCodeUtils {
    /**
     * 随机生成验证码
     * @param length 长度为4位或者6位
     * @return
     */
    public static Integer generateValidateCode(int length){
        Integer code =null;
        if(length == 4){
            code = new Random().nextInt(9999);//生成随机数,最大为9999
            if(code < 1000){
                code = code + 1000;//保证随机数为4位数字
            }
        }else if(length == 6){
            code = new Random().nextInt(999999);//生成随机数,最大为999999
            if(code < 100000){
                code = code + 100000;//保证随机数为6位数字
            }
        }else{
            throw new RuntimeException("只能生成4位或6位数字验证码");
        }
        return code;
    }

    /**
     * 随机生成指定长度字符串验证码
     * @param length 长度
     * @return
     */
    public static String generateValidateCode4String(int length){
        Random rdm = new Random();
        String hash1 = Integer.toHexString(rdm.nextInt());
        String capstr = hash1.substring(0, length);
        return capstr;
    }
}

pom.xml

<!--阿里云短信服务  5-17-->
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-core</artifactId>
            <version>4.5.16</version>
        </dependency>
        <dependency>
            <groupId>com.aliyun</groupId>
            <artifactId>aliyun-java-sdk-dysmsapi</artifactId>
            <version>2.1.0</version>
        </dependency>

3.4 代码实现  5-17

首先访问移动端登录界面  http://localhost:8080/front/page/login.html  

可以看到我们的浏览器出现不适配状况,这是因为移动端使用的是html5开发的,所以我们需要切换手机模式来访问按F12

手机验证码登录_User_17

手机验证码登录_java_18

手机验证码登录_验证码_19

修改LoginCheckFilter   5-17

手机验证码登录_验证码_20

 //定义不需要处理的请求路径  2-3
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/common/**",   //4-4
                "/user/sendMsg",  //5-17
                "/user/login"   //5-17
        };

过滤器中添加移动端通过条件

手机验证码登录_User_21

//4-2、判断移动端登录状态,如果已登录,则直接放行   5-17
        if(request.getSession().getAttribute("user") != null){
            log.info("用户已登录,用户id为:{}",request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request,response);
            return;
        }

获取验证码功能开发  5-18

手机验证码登录_java_22

手机验证码登录_User_23

UserController

//获取手机验证码  5-18
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user,HttpSession session){

        //获取手机号
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){//手机号不为空
            //生成随机的4为验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);

            //调用阿里云提供的短信服务AP完成发送短信
            //SMSUtils.sendMessage("瑞吉外卖","",phone,code);
            //需要将验证码保存到session
            session.setAttribute(phone,code);
            return R.success("手机验证码发送成功");
        }

        return R.error("短信发送失败");
    }

这里我们不使用阿里云了,我们直接控制台输出即可,一样的效果

手机验证码登录_验证码_24

移动端用户登录功能  5-19

手机验证码登录_java_25

手机验证码登录_User_26

由上图可知,前端传来的参数由phone和code,是不能用user用户表来接收的,因为user表里只有phone属性并没有code属性,所以我们用map集合接收(因为类似于k-v键值对)

UserController

/**
     * 移动端用户登录  5-19
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());

        //获取手机号
        String phone = map.get("phone").toString();

        //获取验证码
        String code = map.get("code").toString();

        //从Session中获取保存的验证码
        Object codeInSession = session.getAttribute(phone);

        //进行验证码的比对(页面提交的验证码和Session中保存的验证码比对)
        if(codeInSession != null && codeInSession.equals(code)){
            //如果能够比对成功,说明登录成功

            //判断当前手机号对应的用户是否为新用户,如果是新用户就自动完成注册
            LambdaQueryWrapper<User> 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);
            }
            //将用户id放入session
            session.setAttribute("user",user.getId());

            return R.success(user);
        }
        return R.error("登录失败");
    }

测试登录成功

手机验证码登录_java_27

手机验证码登录_验证码_28