利用執行緒建立傳送手機驗證碼的工具類
1、生成驗證碼類
package com.util; import java.util.Timer; import java.util.TimerTask; /** * @description 手機發送驗證碼工具類 */ public class MessageCode extends TimerTask{ private Timer timer; /** * @description 簡訊驗證碼的內容 */ private String messageCode; /** * @description 毫秒,預設60秒後過期 */ private long maXtime = 180000; /** * @description 簡訊驗證碼長度 */ private int length = 6; /** * @description 簡訊驗證碼可取值 */ private final String charOfMessage = "0123456789"; //0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz @Override public void run() { this.messageCode = null;//過期後簡訊驗證碼資訊置為null this.timer.cancel(); } /** * @decription 使用預設值 */ public MessageCode() { super(); this.timer = new Timer(); genMessageCode(this.length); this.timer.schedule(this, this.maXtime); } /** * @description 自定義最大過期時間,驗證碼最大長度 * @param maXtime * @param length */ public MessageCode(long maXtime, int length) { super(); this.maXtime = maXtime; this.length = length; genMessageCode(this.length); this.timer.schedule(this, this.maXtime); } /** * @description 生成隨機驗證碼 * @param length * @return void 返回值型別 */ private final void genMessageCode(int length){ StringBuffer tempB = new StringBuffer(length); final int charOfMassegeLength = this.charOfMessage.length(); for(int i = 0; i < length; i++){ double d = Math.random(); int index = (int)(Math.floor(d * charOfMassegeLength) / 1); tempB.append(this.charOfMessage.charAt(index)); } this.messageCode = tempB.toString(); } /** * @description 獲取驗證碼資訊,如果為空表示驗證碼超時 * @return * @return String 返回值型別 */ public String getMessageCode() { return messageCode; } }
2、 MessageThread.java 執行緒類
package com.util; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; import org.apache.commons.lang.StringUtils; /** * @description 使用執行緒傳送訊息,以免主執行緒等待 */ public final class MessageThread implements Runnable{ /** * @description 傳送請求的URL */ private final static String url = "http:192.168.1.127/sms/send/smsSend.action?businessName=c1&isLong=3&appName=useraccount&smsKey=powsword"; private String msg; private String phonenumber; @Override public void run() { sendMessage(); } /** * @description * @return void 返回值型別 */ private void sendMessage(){ String phone = this.phonenumber; if(StringUtils.isBlank(this.phonenumber)){//手機號為空時,禁止訊息傳送 return; } String tempUrl = url; try { //經過兩次轉碼。短訊息顯示正常 msg = java.net.URLEncoder.encode(msg, "UTF-8"); tempUrl = (tempUrl + "&uuid=" + java.util.UUID.randomUUID().toString().replaceAll("-", "")); tempUrl = (tempUrl + "&phone=" + phone); tempUrl = (tempUrl + "&content=" + java.net.URLEncoder.encode(msg, "UTF-8")); URLConnection connection = new URL(tempUrl).openConnection(); connection.setConnectTimeout(2000); connection.setReadTimeout(2000); connection.connect(); BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream())); // String x = reader.readLine(); // System.out.println(x); reader.close(); } catch (Exception e) { e.printStackTrace(); } } /** * @decription 初始化傳送資訊執行緒資料 * @param msg * @param phonenumber */ public MessageThread(String msg, String phonenumber) { super(); this.msg = msg; this.phonenumber = phonenumber; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public String getPhonenumber() { return phonenumber; } public void setPhonenumber(String phonenumber) { this.phonenumber = phonenumber; } }
3、傳送訊息工具類
package com.util; /** * @description <p>傳送訊息工具類,具體的訊息傳送方法參見MessageThread.java</p> * <p>呼叫sendMessage方法 ,傳入訊息內容和手機號傳送訊息。</p> * <p>當手機號為空時,不傳送訊息</p> */ public final class MessageUtil { /** * @description 呼叫此方法傳送訊息內容 * @param msg 傳送訊息內容 * @param phone 傳送訊息的手機號。當手機號為空時,不傳送訊息 */ public final static void sendMessage (String msg, String phone){ new Thread(new MessageThread(msg, phone)).start(); } }
——————————————————————————————————————————————————————
——————————————————————————————————————————————————————
簡訊重置密碼類呼叫以上工具示例:
package com.ww.k.a.action;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ww.k.a.action.form.WwAc01UserForm;
import com.ww.k.a.action.form.WwkaForm;
import com.ww.k.a.manager.WwkaMng;
import com.ww.k.a.manager.dto.WwkaDto;
import com.ww.z.util.MessageCode;
import com.ww.z.util.MessageUtil;
import com.util.DtoUtil;
import com.JSONUtil;
import com.validate.CJobBeanValidator;
@Controller
@RequestMapping(value = "/k/a/")
public class WwkaAct {
@Autowired
private WwkaMng wwkaMng;
/**
*
* @Description: 找回密碼頁面入口
* @param request
* @param response
* @param model
*/
@RequestMapping(value = "wwka_cont.html")
public String cont(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
return "k/a/wwka_contnew";
}
/**
*
* @Description: 找回密碼 通過郵箱
* @param form
* @param find
* @param req
* @param resp
*/
@ResponseBody
@RequestMapping(value = "wwka_mail.html")
public String doFindBackMail(WwkaForm form,HttpServletRequest req, HttpServletResponse resp)throws IOException {
Map<String, String> result = new HashMap<String, String>();
if ("".equals(form.getAccount())
|| "".equals(form.getMail())
|| !(wwkaMng.hasuser(form.getAccount(), form.getMail()))) {
result.put("hasError", "2");//帳號或者郵箱不正確
} else {
result.put("hasError", "1");//帳號、郵箱正確
WwkaDto maildto = new WwkaDto();
DtoUtil.copyProperties(form, maildto);
wwkaMng.sentmail(req,maildto);//郵件找回密碼
}
JSONObject json = JSONObject.fromObject(result);
return json.toString();
}
/**
*
* @Description: 通過賬號名獲取Dto,從而獲取安全問題
* @param account
* @param req
* @param resp
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping(value = "wwka_findQ.html")
public String doFindQ(String account,HttpServletRequest req, HttpServletResponse resp)throws IOException {
Map<String, String> result = new HashMap<String, String>();
WwkaDto dtoQ = wwkaMng.findoutQ(account);
String question = dtoQ.getQuestion();
if("".equals(question)||question==null){
result.put("noQ", "1");
}else{
result.put("question", question);
}
JSONObject json = JSONObject.fromObject(result);
return json.toString();
}
/**
*
* @Description: 找回密碼 之 安全問題找回密碼
* @param form
* @param req
* @param resp
* @return
* @throws IOException
*/
@ResponseBody
@RequestMapping(value = "wwka_question.html")
public String doFindByQ(WwkaForm form,HttpServletRequest req, HttpServletResponse resp)throws IOException {
Map<String, String> result = new HashMap<String, String>();
if ("".equals(form.getAccount2())
|| form.getAccount2()==null
|| !(wwkaMng.hasQ(form.getAccount2(), form.getAnswer()))) {
result.put("hasError", "2");//帳號或者答案不正確
JSONObject json = JSONObject.fromObject(result);
return json.toString();
} else {
//生成6位隨機數作為找回的新密碼
Random rd = new Random();
int num = rd.nextInt(1000000);
while(num < 100000){
num = rd.nextInt(1000000);
}
String passwd = String.valueOf(num);
//獲得原來資料
WwkaDto dtopwd = wwkaMng.findoutQ(form.getAccount2());
dtopwd.setPassword(passwd);
//將新密碼同步到資料庫
wwkaMng.resetNewPwd(dtopwd);
//返回給使用者的新密碼
result.put("showMail", dtopwd.getMail());
result.put("showQ", dtopwd.getQuestion());
result.put("showLnum", dtopwd.getLoginNum()!=null?String.valueOf(dtopwd.getLoginNum()):"0");
result.put("showLtime", dtopwd.getLoginTime()!=null?String.valueOf(dtopwd.getLoginTime()):"無");
result.put("showRtime", String.valueOf(dtopwd.getRegisterTime()));
result.put("newPwd", passwd);
result.put("showaccount", form.getAccount2());
result.put("hasError", "1");//帳號、答案正確
}
JSONObject json = JSONObject.fromObject(result);
return json.toString();
}
/**
* @description 傳送手機驗證碼,校驗賬號是否存在,並且賬號的手機號碼與輸入的手機號碼是否一致
* @param request
* @param response
* @param phonenumber
* @param account
* @return void 返回值型別
*/
@ResponseBody
@RequestMapping("wwka_getcode.html")
public void getCode(HttpServletRequest request, HttpServletResponse response, String phonenumber, String account){
StringBuffer errerB = new StringBuffer();
if(StringUtils.isBlank(account)){
errerB.append("請輸入您的個人賬號。<br>");
}else if(!account.matches("^[1-9]{1}[0-9]{16}[0-9Xx]{1}$")){
errerB.append("您的個人賬號輸入錯誤。<br>");
}
if(StringUtils.isBlank(phonenumber)){
errerB.append("請輸入手機號碼。<br>");
}else if(!phonenumber.matches("^1[0-9]{10}$")){
errerB.append("您的手機號碼輸入錯誤。<br>");
}
if(errerB.toString().endsWith("<br>")){//如果以<br>結尾,去掉<br>
errerB.setLength(errerB.length() - 4);
}
Map<String, String> rs = new HashMap<String, String>();
//校驗不通過
if(errerB.length() != 0){
rs.put("msg", errerB.toString());
rs.put("status", "-1");
JSONUtil.write(response, rs);
return;
}
//校驗通過,判斷賬號是否存在
WwAc01UserForm form = wwkaMng.getUserInfo(account);
if(form == null){
rs.put("msg", "您輸入的賬號不存在。");
rs.put("status", "-1");
JSONUtil.write(response, rs);
return;
}else if(!phonenumber.equals(form.getPhonenumber())){//賬號存在,判斷手機號碼是否與系統一致
rs.put("msg", "您輸入的手機賬號與該賬號在系統中預留的手機號碼不一致。");
rs.put("status", "-1");
JSONUtil.write(response, rs);
return;
}
//以上都通過,傳送驗證碼
HttpSession session = request.getSession();
MessageCode code = new MessageCode();
String msg = code.getMessageCode();
session.setAttribute(session.getId() + "_resetpassword", code);
MessageUtil.sendMessage(msg, phonenumber);
rs.put("msg", "手機驗證碼已由系統發出,請您注意查收。");
rs.put("status", "1");
JSONUtil.write(response, rs);
}
/**
* @description 重置密碼。密碼傳送到系統中預留的手機號碼
* @param request
* @param response
* @param phonenumber
* @param account
* @param phonecode
* @return void 返回值型別
*/
@ResponseBody
@RequestMapping("wwka_resetpsw.html")
public void resetPassword(HttpServletRequest request, HttpServletResponse response, String phonenumber, String account, String phonecode){
//先取出驗證碼,以免校驗時過期
HttpSession session = request.getSession();
Map<String, String> rs = new HashMap<String, String>();
Object obj = session.getAttribute(session.getId() + "_resetpassword");
if(obj == null){
rs.put("msg", "請先獲取手機驗證碼。");
rs.put("status", "-1");
JSONUtil.write(response, rs);
return;
}else{
MessageCode code = (MessageCode)obj;
String codestr = code.getMessageCode();
if(StringUtils.isBlank(codestr)){
rs.put("msg", "您輸入手機驗證碼已過期,請重新獲取。");
rs.put("status", "-1");
JSONUtil.write(response, rs);
return;
}else{//再次校驗資訊是否合法
StringBuffer errerB = new StringBuffer();
if(StringUtils.isBlank(account)){
errerB.append("請輸入您的個人賬號。<br>");
}else if(!account.matches("^[1-9]{1}[0-9]{16}[0-9Xx]{1}$")){
errerB.append("您的個人賬號輸入錯誤。<br>");
}
if(StringUtils.isBlank(phonenumber)){
errerB.append("請輸入手機號碼。<br>");
}else if(!phonenumber.matches("^1[0-9]{10}$")){
errerB.append("您的手機號碼輸入錯誤。<br>");
}
if(StringUtils.isBlank(phonecode)){
errerB.append("請輸入手機接收到驗證碼。<br>");
}else if(!phonecode.matches("^[0-9]{6}$")){
errerB.append("您的手機驗證碼輸入格式不正確。<br>");
}
if(errerB.toString().endsWith("<br>")){//如果以<br>結尾,去掉<br>
errerB.setLength(errerB.length() - 4);
}
//校驗不通過
if(errerB.length() != 0){
rs.put("msg", errerB.toString());
rs.put("status", "-1");
JSONUtil.write(response, rs);
return;
}
//校驗通過,判斷賬號是否存在
WwAc01UserForm form = wwkaMng.getUserInfo(account);
if(form == null){
rs.put("msg", "您輸入的賬號不存在。");
rs.put("status", "-1");
JSONUtil.write(response, rs);
return;
}else if(!phonenumber.equals(form.getPhonenumber())){//賬號存在,判斷手機號碼是否與系統一致
rs.put("msg", "您輸入的手機賬號與該賬號在系統中預留的手機號碼不一致。");
rs.put("status", "-1");
JSONUtil.write(response, rs);
return;
}
//以上都通過
if(codestr.equals(phonecode)){//驗證碼正確重置密碼
//生成隨機驗證碼
String password = new MessageCode().getMessageCode();
WwkaDto dto = new WwkaDto();
dto.setAccount(account);
dto.setPassword(password);
//重置密碼
wwkaMng.resetNewPwd(dto);
String msg = "您的個人賬號密碼已重置為:" + password
+ ",請您及時使用重置的新密碼登陸並修改密碼。";
MessageUtil.sendMessage(msg, phonenumber);
session.removeAttribute(session.getId() + "_resetpassword");
rs.put("msg", "您個人賬號的密碼已傳送到您的手機。請您及時登陸並修改密碼。");
rs.put("status", "1");
JSONUtil.write(response, rs);
}else{
rs.put("msg", "您輸入的手機驗證碼不正確,請重新輸入。");
rs.put("status", "-1");
JSONUtil.write(response, rs);
}
}
}
}
}
前端頁面在此省略。
相關推薦
利用執行緒建立傳送手機驗證碼的工具類
1、生成驗證碼類 package com.util; import java.util.Timer; import java.util.TimerTask; /** * @description 手機發送驗證碼工具類 */ public class Message
Java 隨機生成手機驗證碼工具類
package cn.it.feizi.until; import java.util.HashSet; import java.util.Iterator; import java.util.Random; import java.util.Set; public class PhoneCod
【MarketAnalysis總結】6.0利用SMS的API實現傳送手機驗證碼
本專案的需求之一是對每一個下載的檔案,都進行了加密處理,故而產生另一個需求是要將使用者下載的檔案的密碼傳送到使用者的手機上。這裡的實現我採用了中國網建網SMS的一個API介面,下面來說明如何實現,其實很簡單~。傳送簡訊的流程圖如圖6.1,圖6.1 傳送簡訊的實現流程圖主要過程
c#實現傳送手機驗證碼
【.aspx.cs】 string shouji = ""; string templateid = "181ed0353b8341808620a1ed871793b5"; shouji = gelian.Value.Trim(); string yzm = IdentifyingCode.GenCod
使用JAVA+秒嘀傳送手機驗證碼
隨著阿里雲簡訊服務的改版,使用阿里雲簡訊服務的過程明顯比過去要麻煩的多。相信很多人或多或少大概都被困擾過,所以,選用另外的企業所推出的簡訊傳送或許會是個更好的選擇,所以,對於很多小白來說,秒嘀 http://www.miaodiyun.com/auth/login 無疑是一個不錯的選擇。 首
python利用第三方模組,傳送簡訊驗證碼
對於初學者,如何利用第三方python開發包傳送簡訊驗證碼,下面是具體的實現和記錄過程! 環境:虛擬機器上centos7平臺,python3.7版本; 首先,申請賬號的部分就省略了 1. 獲得appid和appSecret 在"我的應用"-&
註冊/找回密碼等功能中傳送手機驗證碼後倒計時效果的實現(基於vue)
註冊/找回密碼等功能中傳送手機驗證碼後倒計時效果的實現,基於vue、element-ui<template> <el-button size="small" type="prima
thinkphp實現傳送手機驗證碼功能!
php實現傳送手機驗證碼功能如下: //傳送手機驗證碼 public function sendPhoneCodeMessage(){ vendor('SendPhoneCode.SendCode','','.php
傳送手機驗證碼,驗證手機驗證碼,包括資料表的設計
/** * 驗證手機驗證碼 */ public function validateMobileCode($post) { $mc = new MobileCodeModel(); if(empty($po
java實現傳送手機驗證碼功能
2. 註冊好之後,點選 使用者中心 -> 賬戶管理,就會進入如下介面 (順便提一下,新註冊的使用者,平臺會免費贈送你10元,足夠大家學習和使用了,所以不用擔心需要充錢) 你需要做的就是獲取你自己的 ACCOUNT SID 和 AUTH TOKEN 3. 需要
使用者登入,實現傳送手機驗證碼。
傳送手機驗證碼,要求具有如下功能需求、業務邏輯: (1)、使用者輸入手機號,當輸入的手機號碼為空時,提示,並且要求使用者輸入手機號; (2)、傳送手機號碼後,button按鈕,自動變為不可點選,然後60秒倒計時; (3)、後臺成功傳送驗證碼給手機; (4)、使用者輸入
C# WinForm 使用SMS介面傳送手機驗證碼+圖形驗證碼+IP限制
https://blog.csdn.net/IT_xiao_guang_guang/article/details/104299983 前言 1.傳送手機驗證碼用的是網建的SMS介面(http://sms.webchinese.cn/) 2.手機驗證碼簡單的做了以下限制: ①傳送驗證碼1分鐘只
Java中執行緒建立的方式:繼承thread類與實現Runnable介面
Java中執行緒的建立有兩種方式: 1. 通過繼承Thread類,重寫Thread的run()方法,將執行緒執行的邏輯放在其中 2. 通過實現Runnable介面,例項化Thread類 在實際應用中,我們經常用到多執行緒,如車站的售票系統,車站的
java--(多執行緒建立的兩種方式Thread類和Runnable介面)
(一)繼承Thread類建立多執行緒----單執行緒下面的程式碼是一個死迴圈,但是不會執行main裡面的迴圈語句,而是run()裡面的語句,這是因為該程式是一個單執行緒程式,當呼叫MyThread類的run()方法時,遇到死迴圈,迴圈一直進行。因此,MyThread類的列印
生成4位隨機驗證碼工具類
urn build public har spa java dom 個人 ont keyUtil: package com.duocy.util; import java.util.Random; public class keyUtil {public Str
點選生成動態驗證碼(工具類)
1.頁面 <!--驗證碼--> <div class="col-sm-3"> <img id="vcode" src="/checkCode" style="cursor:pointer"> </div>
圖片驗證碼工具類
工具類 /** * Created by qd on 2015/11/12. */ import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.awt.image.BufferedImage
Java隨機生成圖片驗證碼工具類/** * ttf字型檔案 * @author dsna * */ public class ImgFontByte { public Font g
/** * ttf字型檔案 * @author dsna * */ public class ImgFontByte { public Font getFont(int fontHeight){ try { Font baseFont = Font.createFo
多執行緒學習筆記六之併發工具類CountDownLatch和CyclicBarrier
目錄 簡介 CountDownLatch 示例 實現分析 CountDownLatch與Thread.join() CyclicBarrier 實現分析 CountDownLatch和CyclicBarrier區別 簡介
JAVA短信驗證碼 工具類
有效時間 clas axis ack remove except equal return med MsgCodeUtil.java package com.hg.util; import com.soyea.enums.ResultEnum; import com.