Home > Java > Javagetting Started > Java implements the function of sending verification code SMS

Java implements the function of sending verification code SMS

王林
Release: 2021-01-20 09:52:53
forward
3054 people have browsed it

Java implements the function of sending verification code SMS

Functional requirements:

(Learning video sharing: java video tutorial)

1. Randomly generate 4 characters in the background

2. Only one verification code can be sent within 1 minute.

3. After more than 1 minute, but within 5 minutes, the verification code sent is still the verification code character generated for the first time.

4. After more than 5 minutes, a new verification code is generated

Regardless of what framework the front end uses

Dependency configuration

SMS dependency package redis configuration , because the verification code and mobile phone number are stored in redis

Network building sms used by the SMS platform, http://www.smschinese.cn/ You can use 5 tests for free

Note : The account name and key for configuring the interface are different for everyone, copy them and remember to change them

SMS dependency package

 <!--短信jar包-->
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>
Copy after login

redis jar package

<!--redis jar 包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
Copy after login

Before using redis, you must first Configure the connection and configure it in application.properties

# redis 属性信息
## redis数据库索引(默认为0)
spring.redis.database=0
## redis服务器地址
spring.redis.host=localhost
## redis服务器连接端口
spring.redis.port=6379
## redis服务器连接密码(默认为空)
## spring.redis.password=123456
## 连接池最大连接数(使用负值表示没有限制)
spring.redis.jedis.pool.max-active=8
## 连接池中的最大空闲连接
spring.redis.jedis.pool.max-idle=8
## 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.jedis.pool.max-wait=-1ms
## 连接池中的最小空闲连接
spring.redis.jedis.pool.min-idle=0
Copy after login

Create a tool class StrUtils.getComplexRandomString () // Get the number of random characters and enter it yourself

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

/**
 * @author yaohuaipeng
 * @date 2018/10/26-16:16
 */
public class StrUtils {
    /**
     * 把逗号分隔的字符串转换字符串数组
     *
     * @param str
     * @return
     */
    public static String[] splitStr2StrArr(String str,String split) {
        if (str != null && !str.equals("")) {
            return str.split(split);
        }
        return null;
    }


    /**
     * 把逗号分隔字符串转换List的Long
     *
     * @param str
     * @return
     */
    public static List<Long> splitStr2LongArr(String str) {
        String[] strings = splitStr2StrArr(str,",");
        if (strings == null) return null;

        List<Long> result = new ArrayList<>();
        for (String string : strings) {
            result.add(Long.parseLong(string));
        }

        return result;
    }
    /**
     * 把逗号分隔字符串转换List的Long
     *
     * @param str
     * @return
     */
    public static List<Long> splitStr2LongArr(String str,String split) {
        String[] strings = splitStr2StrArr(str,split);
        if (strings == null) return null;

        List<Long> result = new ArrayList<>();
        for (String string : strings) {
            result.add(Long.parseLong(string));
        }

        return result;
    }

    public static String getRandomString(int length) {
        String str = "0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(10);
            sb.append(str.charAt(number));
        }
        return sb.toString();

    }

    public static String getComplexRandomString(int length) {
        String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(62);
            sb.append(str.charAt(number));
        }
        return sb.toString();
    }

    public static String convertPropertiesToHtml(String properties){
        //1:容量:6:32GB_4:样式:12:塑料壳
        StringBuilder sBuilder = new StringBuilder();
        String[] propArr = properties.split("_");
        for (String props : propArr) {
            String[] valueArr = props.split(":");
            sBuilder.append(valueArr[1]).append(":").append(valueArr[3]).append("<br>");
        }
        return sBuilder.toString();
    }

}
Copy after login

Create a SMS sending class configuration interface and call it by other classes The send method of this class can pass in the mobile phone number and send the content

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.IOException;

public class SendMsgUtils {
    private static final String UID = "amazingwest";//这是建网SMS 上的登陆账号
    private static final String KEY = "d41d8cd98f00b204e980"; //这是密钥

    /**
     * 手机发送短信
     * @param phone  手机号码
     * @param context  发送短信内容
     */
    public static void send(String phone, String context) {

        PostMethod post = null;
        try {
            //创建Http客户端
            HttpClient client = new HttpClient();
            //创建一个post方法
            post = new PostMethod("http://utf8.api.smschinese.cn");
            //添加请求头信息
            post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf8");//在头文件中设置转码

            NameValuePair[] data = {new NameValuePair("Uid", UID),
                    new NameValuePair("Key", KEY),
                    new NameValuePair("smsMob", phone),
                    new NameValuePair("smsText", context)};
            //设置请求体
            post.setRequestBody(data);
            //执行post方法
            client.executeMethod(post);

            //获取响应头信息
            Header[] headers = post.getResponseHeaders();
            //获取状态码
            int statusCode = post.getStatusCode();
            System.out.println("statusCode:" + statusCode);
            //循环打印头信息
            for (Header h : headers) {
                System.out.println(h.toString());
            }
            //获取相应体
            String result = new String(post.getResponseBodyAsString().getBytes("utf8"));
            System.out.println(result); //打印返回消息状态

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (post != null) {
                //关闭资源
                post.releaseConnection();
            }
        }
    }


}
Copy after login

Create a registration constant class, which is mainly used to distinguish whether the verification code is used to register or log in or retrieve a password

/**
 * 验证码常量
 */
public class VerificationConstant {

    //用户注册常量
    public static final String USER_REG = "user_reg";
}
Copy after login

Front desk When clicking to send the verification code, you must first consider the simultaneous registration of multiple users. The key value cannot be hard-coded.

First, judge whether the value in redis exists based on the mobile phone number plus the registration identifier (KEY). If it does not exist, create a key. Key Add a registration mark to the mobile phone number.
To determine the time, when creating a redis key-value pair, a current timestamp will be added to the value. If the value is first created, the value will be divided. Subtract the current timestamp from the value. The specific time can be obtained from the timestamp of one creation.
The first time you create a key value, set the key’s survival time to 5 minutes and 300 seconds.
Send a verification code text message, and the mobile phone number is transmitted from the front end. Do business here. Logical judgment does not need to determine whether the mobile phone number is registered. This is a matter of other classes. To use redisTemplate, you must introduce the redis jar package
StrUtils.getComplexRandomString(4) This is a method in the tool class created above to create 4-digit characters. The random number,
StringUtils.isEmpty is import org.springframework.util.StringUtils Don’t get it wrong

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

@Service
public class VerificationCodeServiceImpl implements IVerificationCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送注册验证码
     * 验证码需求:
     *      1.后台随机产生4个字符
     *      2.1分钟以内只能发送1次验证码
     *      3.超过1分钟,但在5分钟以内,发送的验证码依然是第一次产生的验证码字符
     *      4.超过了5分钟以后,产生全新的验证码
     * @return
     */
    @Override
    public void sendRegisterVerificationCode(String phone) throws CustomException {
        //随机产生4个字符
        String value = StrUtils.getComplexRandomString(4);
        //在redis中通过key获取对应的值        value:时间戳
        String valueCode = (String) redisTemplate.opsForValue().get(phone + ":" + VerificationConstant.USER_REG);
        //如果不为空,就意味着验证码没有过期,依然是在5分钟以内
        if(!StringUtils.isEmpty(valueCode)){
            //开始时间戳
            String beginTimer = valueCode.split(":")[1];

            if(System.currentTimeMillis()-Long.valueOf(beginTimer)<=60*1000){
               //自定义异常,自己创建一个就可以了
                throw new CustomException("亲!一分钟以内不能发送多次验证码!!");
            }
            //证明是超过了1分钟,但依然在5分钟以内,还是用之前的验证码
            value = valueCode.split(":")[0];
        }
        //存储redis中,设置有效期是5分钟  k=phone:USER_REG  v= value:时间戳
//        RedisUtil.set(phone:USER_REG,  value:System.currentTimeMillis(),  5MIN);
        redisTemplate.opsForValue().set(phone + ":" + VerificationConstant.USER_REG,
                value + ":" + System.currentTimeMillis(), 5, TimeUnit.MINUTES);
        //发送手机验证码
        String context = "尊敬的用户,您的验证码为:" + value + ",请您在5分钟以内完成注册!!";
        //发送短信
//        SendMsgUtils.send(phone, context);
        System.out.println(context);


    }
}
Copy after login

Done.

Related recommendations: java introductory tutorial

The above is the detailed content of Java implements the function of sending verification code SMS. For more information, please follow other related articles on the PHP Chinese website!

source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template