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>
redis jar package
<!--redis jar 包--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
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
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(); } }
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(); } } } }
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"; }
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); } }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

The reasons why PHP is the preferred technology stack for many websites include its ease of use, strong community support, and widespread use. 1) Easy to learn and use, suitable for beginners. 2) Have a huge developer community and rich resources. 3) Widely used in WordPress, Drupal and other platforms. 4) Integrate tightly with web servers to simplify development deployment.
