首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 整合第三方短信平台實現驗證碼發送與校驗(Spring MVC + MyBatis 實戰)

     編輯:Java 相關知識

業務流程設計

  1. 用戶輸入手機號請求驗證碼
  2. 後端生成 6 位隨機數,存入 Session(有效期 5 分鐘)
  3. 調用第三方 HTTP 接口發送短信
  4. 用戶提交驗證碼,後端從 Session 取出比對

第三方接口封裝 SendMsg_webchineseController

依賴:commons-httpclient-3.1.jar、commons-codec-1.4.jar、commons-logging-1.1.1.jar

public class SendMsg_webchineseController {
    public static HashMap<String, String> getMessageStatus(String phone) throws Exception {
        HashMap<String, String> result = new HashMap<>();
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("https://gbk.sms.webchinese.cn");
        post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=gbk");

        String code = VerifyingCodeGenerator.generate();  // 自定義 6 位隨機數生成器
        NameValuePair[] data = {
            new NameValuePair("Uid", "你的用戶名"),
            new NameValuePair("Key", "你的密鑰"),
            new NameValuePair("smsMob", phone),
            new NameValuePair("smsText", "您正在註冊本站會員,本次驗證碼為:" + code + " 無效時間為5分鐘")
        };
        result.put("code", code);
        post.setRequestBody(data);
        client.executeMethod(post);

        String resp = new String(post.getResponseBodyAsString().getBytes("gbk"));
        result.put("result", resp);  // "1" 表示成功,其他為失敗
        post.releaseConnection();
        return result;
    }
}

Controller 層 SendCheckMessage

@ResponseBody
@RequestMapping(value = UrlDefine.Register.CHECKMESSAGEWORK, method = RequestMethod.POST)
public Object SendCheckMessage(HttpServletRequest request, @RequestBody UserBean u) throws Exception {
    String phone = u.getTelephone();
    if (userService.getByPhone(phone) != null) {
        return new Response(Status.ERROR, "該手機號已被註冊");
    }

    HashMap<String, String> m = SendMsg_webchineseController.getMessageStatus(phone);
    if ("1".equals(m.get("result").trim())) {
        HttpSession session = request.getSession();
        session.setAttribute("code", m.get("code"));
        session.setMaxInactiveInterval(60 * 5);  // 5 分鐘
        return new Response(Status.SUCCESS, "發送成功");
    }
    return new Response(Status.ERROR, "短信發送失敗");
}

前端測試

使用 Postman POST JSON {"telephone":"13800000000"},返回 {"status":"SUCCESS","message":"發送成功"},手機端收到驗證碼短信。

安全與擴展建議

  • 防刷限流:同一 IP/手機號 60 秒內僅允許 1 次請求(Guava RateLimiter / Redis 計數器)
  • 驗證碼加密存儲:Session 中存 MD5(code + salt),校驗時比對摘要
  • 多通道降級:接入阿里云/騰訊云/網易云信等多家,主通道失敗自動切備
  • 異步發送:引入消息隊列(RabbitMQ/Kafka)削峰填谷,提高響應速度
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved