First of all, we need to open SMS service in Ali Cloud according to the process, apply for signature and template, see the specific documents

Since this is a Web project and uses the Thymeleaf template, add the following dependencies to POM.xml

< the dependency > < groupId > com. Aliyun < / groupId > < artifactId > aliyun - Java - SDK - core < / artifactId > < version > 4.4.0 < / version > </dependency> <dependency> <groupId>com.aliyun</groupId> <artifactId>aliyun-java-sdk-dysmsapi</artifactId> < version > 1.1.0 < / version > < / dependency > < the dependency > < groupId > org. Springframework. Boot < / groupId > <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>Copy the code

Verifycodegenerator. Java is a utility class for generating captcha

Public class verifyCodeGenerator {// Generate a verification code public static StringgetVerifyCode()
{
    Random random=new Random();
StringBuffer stringBuffer=new StringBuffer();
for(int i=0; i<6; i++) { stringBuffer.append(String.valueOf(random.nextInt(10))); } System.out.println(stringBuffer.toString());returnstringBuffer.toString(); }}Copy the code

Msutil. Java is the utility class that sends the captcha

Public class MsUtil {public static String send(String mobile) {// Set timeout - optional system.setProperty ()"sun.net.client.defaultConnectTimeout"."10000");
        System.setProperty("sun.net.client.defaultReadTimeout"."10000"); Final String product = final String product ="Dysmsapi"; // SMS API product name (the SMS product name is fixed and does not need to be changed) Final String domain ="dysmsapi.aliyuncs.com"; // SMS API product domain name (fixed interface address, no need to change) // Replace with your AK final String accessKeyId ="yourAccessKeyId"; // For your accessKeyId, see Step 2 in this document for final String accessKeySecret ="yourAccessKeySecret"; / / your accessKeySecret, reference this document step 2 / / initialization ascClient, temporarily does not support multiple region (please do not modify) IClientProfile profile = DefaultProfile. GetProfile ("cn-hangzhou", accessKeyId,
                accessKeySecret);
        try {
            DefaultProfile.addEndpoint("cn-hangzhou"."cn-hangzhou", product, domain); } catch (ClientException e) { e.printStackTrace(); } IAcsClient acsClient = new DefaultAcsClient(profile); SendSmsRequest request = new SendSmsRequest(); // Request. SetMethod (methodtype.post); // Request.setsysMethod (methodtype.post) is out of date; // Required: Mobile phone number to be sent. The maximum number of mobile phone numbers in a batch can be 1000. The timeliness of batch invocation is slightly delayed compared with that of single invocation. For verification code SMS messages, single invocation is recommended. When sending international/Hong Kong/Macao/Taiwan messages, the recipient number format is international area code + phone number, for example, request.setPhonenumbers (mobile). // Required: SMS signature - Request.setSignName (can be found in the SMS console"I'm not a genius."); // Required: SMS template - Available in THE SMS console. When sending international/Hong Kong, Macao and Taiwan messages, please use the international/Hong Kong, Macao and Taiwan SMS template request.settemplatecode ("SMS_162732775"); // Optional: Replace the JSON string with variables in the template, for example, the template content is"Dear${name}, your verification code is${code}"Note: If a new line character is required in JSON, please refer to the requirements of the standard JSON protocol on the new line character. For example, if the TEXT message contains \r\n, it must be represented as \\r\ n in JSON. Otherwise, the JSON server fails to parse String verifyCode=verifyCodeGenerator.getVerifyCode(); request.setTemplateParam("{\"code\":" + verifyCode + "}"); / / optional - uplink SMS extension code (extended code field control in seven or below, please ignore this field has no special requirements for the user). / / request setSmsUpExtendCode ("90997"); // Optional :outId is the extended field provided to the business side, and the value is eventually returned to the caller request.setoutid ("yourOutId"); Try {SendSmsResponse acsResponse = acsclient.getacsResponse (request); } catch (ClientException e) { e.printStackTrace(); } / /if(sendSmsResponse.getCode() ! = null && sendSmsResponse.getCode().equals("OK")) {
//            returnverifyCode; //// Request successful //}returnverifyCode; }}Copy the code

Application. The properties of the configuration

# Turn off thymeleaf cache
spring.thymeleaf.cache=false
# ָ port
server.port=8888
The path to the template
spring.freemarker.template-loader-path=classpath:/templates
# set the character encoding of the template
spring.freemarker.charset=utf-8
        
Copy the code

Thymeleaf template page

Sign_in.html is the send and enter captcha page
<! DOCTYPE html> <html lang="en">
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="matchCode" method="post"> <! --<inputtype="text" placeholder="Please enter your mobile phone number."/>-->
    <input type="text" placeholder="Please enter the verification code." name="yourCode">
    <input type="submit" value="Sure">
</form>
<div th:text="${code}"></div>
</body>
</html>		
Copy the code
Test.html is the validation result page
<! DOCTYPE html> <html lang="en">
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">

<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div th:text="${result}"></div>
</body>
</html>
Copy the code

UserController .java

@Controller public class UserController { @Autowired private HttpServletRequest request; Request @getMapping (value ="/")
public String sign(Model model)
{
    String code= MsUtil.send("The phone number from which you received the captcha.");
//    String verifyCode = verifyCodeGenerator.getVerifyCode();
    model.addAttribute("code"."The captcha is"+code);

    request.getSession().setAttribute("code",code);
//    attr.addFlashAttribute("code",code);
    return "sign_in.html"; } // Check whether the entered and sent verification codes are the same. @postmapping (value ="matchCode")
    public String matchCode(@RequestParam String yourCode,Model model) {
        String code =(String) request.getSession().getAttribute("code");
        System.out.println("code===="+code);
        if (yourCode.equals(code)){
            System.out.println("Success");
           model.addAttribute("result"."Success");
        }else {
            System.out.println("Failure");
            model.addAttribute("result"."Failure");
        }
        return "test"; }}Copy the code

The results

Reference documentation

Personal website