Jave Web阿里雲短信服務發送驗證碼

首先得在阿里雲根據流程開通短信服務,申請簽名和模版,具體看文檔html

由於這是個web項目,用到了thymeleaf模板,因此在pom.xml中加入以下依賴

<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>
		
        <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>

verifyCodeGenerator.java是生成驗證碼的工具類

public class verifyCodeGenerator {
//    生成驗證碼
public static String getVerifyCode()
{
    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());
    return  stringBuffer.toString();
}
}

MsUtil .java是發送驗證碼的工具類

public class MsUtil {
//    發送驗證碼及返回驗證碼字符串
    public static String send(String mobile)
    {
        //設置超時時間-可自行調整
        System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
        System.setProperty("sun.net.client.defaultReadTimeout", "10000");
//初始化ascClient須要的幾個參數
        final String product = "Dysmsapi";//短信API產品名稱(短信產品名固定,無需修改)
        final String domain = "dysmsapi.aliyuncs.com";//短信API產品域名(接口地址固定,無需修改)
//替換成你的AK
        final String accessKeyId = "yourAccessKeyId";//你的accessKeyId,參考本文檔步驟2
        final String accessKeySecret = "yourAccessKeySecret";//你的accessKeySecret,參考本文檔步驟2
//初始化ascClient,暫時不支持多region(請勿修改)
        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();
        //使用post提交
//        request.setMethod(MethodType.POST);//過時了
        request.setSysMethod(MethodType.POST);
        //必填:待發送手機號。支持以逗號分隔的形式進行批量調用,批量上限爲1000個手機號碼,批量調用相對於單條調用及時性稍有延遲,驗證碼類型的短信推薦使用單條調用的方式;發送國際/港澳臺消息時,接收號碼格式爲國際區號+號碼,如「85200000000」
        request.setPhoneNumbers(mobile);
        //必填:短信簽名-可在短信控制檯中找到
        request.setSignName("小生不才");
        //必填:短信模板-可在短信控制檯中找到,發送國際/港澳臺消息時,請使用國際/港澳臺短信模版
        request.setTemplateCode("SMS_162732775");
        //可選:模板中的變量替換JSON串,如模板內容爲"親愛的${name},您的驗證碼爲${code}"時,此處的值爲
        //友情提示:若是JSON中須要帶換行符,請參照標準的JSON協議對換行符的要求,好比短信內容中包含\r\n的狀況在JSON中須要表示成\\r\\n,不然會致使JSON在服務端解析失敗
        String verifyCode=verifyCodeGenerator.getVerifyCode();
        request.setTemplateParam("{\"code\":" + verifyCode + "}");
        //可選-上行短信擴展碼(擴展碼字段控制在7位或如下,無特殊需求用戶請忽略此字段)
        //request.setSmsUpExtendCode("90997");
        //可選:outId爲提供給業務方擴展字段,最終在短信回執消息中將此值帶回給調用者
        request.setOutId("yourOutId");
//請求失敗這裏會拋ClientException異常
        try {
            SendSmsResponse acsResponse = acsClient.getAcsResponse(request);
        } catch (ClientException e) {
           e.printStackTrace();
        }
//        if(sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK")) {
//            return verifyCode;
////請求成功
//        }
     return  verifyCode;
    }
}

application.properties的配置

#關閉thymeleaf緩存
spring.thymeleaf.cache=false
#ָ端口
server.port=8888
#模板的路徑
spring.freemarker.template-loader-path=classpath:/templates
#設置模板的字符編碼
spring.freemarker.charset=utf-8

thymeleaf模板頁面

sign_in.html 是發送和輸入驗證碼頁面
<!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">
    <!--<input type="text" placeholder="請輸入手機號碼"/>-->
    <input type="text" placeholder="請輸入驗證碼" name="yourCode">
    <input type="submit" value="肯定">
</form>
<div th:text="${code}"></div>
</body>
</html>
test.html 是驗證結果頁面
<!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>

UserController .java

@Controller
public class UserController {
    @Autowired
    private HttpServletRequest request; //自動注入request

@GetMapping(value = "/")
public String sign(Model model)
{
    String code= MsUtil.send("你接收驗證碼的手機號");
//    String verifyCode = verifyCodeGenerator.getVerifyCode();
    model.addAttribute("code","驗證碼是"+code);

    request.getSession().setAttribute("code",code);
//    attr.addFlashAttribute("code",code);
    return "sign_in.html";
}
//匹配輸入的驗證碼和發送的驗證碼是否一致
    @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("成功");
           model.addAttribute("result","成功");
        }else {
            System.out.println("失敗");
            model.addAttribute("result","失敗");
        }
        return "test";
    }
}

運行結果

參考文檔java

我的網站web

相關文章
相關標籤/搜索