Using threads to create a tool class to send a phone verification code

Source: Internet
Author: User

1. Generate Verification Code class

Package Com.util;import java.util.timer;import java.util.timertask;/** * @description phone to send Captcha tool classes */public class Messagecode extends Timertask{private Timer timer;/** * @description SMS Verification Code content */private String messagecode;/** * @descript Ion MS, expires after 60 seconds */private long maxtime = 180000;/** * @description SMS Verification Code length */private int length = 6;/** * @description SMS */private final String charofmessage = "0123456789";// 0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz@overridepublic void Run () {This.messageCode = null;/ /After expiration SMS Verification code information is set to Nullthis.timer.cancel ();} /** * @decription Use default value */public Messagecode () {super () This.timer = new timer (); Genmessagecode (this.length); This.timer.schedule (this, this.maxtime);} /** * @description Custom Maximum expiration time, maximum captcha length * @param maxtime * @param length */public messagecode (long maxtime, int length) {Supe R (); this.maxtime = Maxtime;this.length = Length;genmessagecode (this.length); This.timer.schedule (this, this.maxtime) ;} /** * @description Generate random Verification code * @param length * @return void return value type */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 ind ex = (int) (Math.floor (d * charofmassegelength)/1); Tempb.append (This.charOfMessage.charAt (index));} This.messagecode = Tempb.tostring ();} /** * @description Gets the CAPTCHA information, if NULL indicates that the Authenticode timed out * @return * @return string return value type */public string Getmessagecode () {return Messageco De;}}


2. Messagethread.java Thread class


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 Use threads to send messages so that the main thread waits for */public final Class Messagethread implements runnable{/** * @description send the requested URL */private final static String url = "http:192.168.1.12 7/sms/send/smssend.action?businessname=c1&islong=3&appname=useraccount&smskey=powsword ";p rivate String Msg;private string PhoneNumber; @Overridepublic void Run () {sendMessage ();} /** * @description * @return void return value type */private void SendMessage () {String phone = this.phonenumber;if (Stringutils.isblan K (This.phonenumber)) {//Phone number is empty, prohibit message send return;} String Tempurl = url;try {//has been transcoded two times. The short message shows normal 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.ne T.urlencoder.encode (MSG, "UTF-8")); URLConnection connection = new URL (tempurl). OpenConnection (); Connection.setconnecttimeout (2000); Connection.setreadtimeout (+); 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 Initialize send information thread data * @param msg * @param phonenumber */public messagethread (String msg, String phonenumber) {s Uper (); 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. Send Message Tool class

Package com.util;/** * @description <p> Send Message tool class, specific message sending method see Messagethread.java</p> * <p> Call the SendMessage method, the incoming message content and the phone number to send the message.  </p> * <p> do not send a message when the phone number is empty </p> */public final class Messageutil {/*** @description call this method to send message content * @param msg Send Message content * @param phone number for the message to be sent. When the phone number is empty, the message is not sent */public final static void SendMessage (String msg, string phone) {New Thread (new Messagethread (MSG, phone)). Start ();}}


——————————————————————————————————————————————————————
——————————————————————————————————————————————————————
SMS Reset Password class Call the tool example above:

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 {@Autowiredprivate wwkamng wwkamng;/** * * @Descriptio N: Retrieve Password page entry * @param request * @param response * @param model */@RequestMapping (value = "wwka_cont.html") public String con T (httpservletrequest request, httpservletresponse response, Modelmap model) {return "k/a/wwka_contnew";} /** * * @Description: Retrieve password via email * @param form * @param find * @param req * @param resp * * @ResponseBody @requestmapping (val UE = "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");//Incorrect account or mailbox} else {result.put ("Haserror", "1");//account number, mailbox correct wwkadto maildto = new Wwkadto ();D Toutil.copyproperties (form, maildto); Wwkamng.sentmail (req,maildto);//Mail retrieve password}jsonobject json = jsonobject.fromobject (result); return json.tostring ();} /** * * @Description: Get a DTO via account name for security issues * @param accounts * @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: Recover password Security issue recover password * @param form * @param req * @param resp * @return * @throws ioexception * * @Respons Ebody@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");//The account number or answer is incorrect jsonobject JSON = Jsonobject.fromobject (result); return json.tostring ();} else {//Generate a 6-bit random number as the new password to retrieve the Random rd = Neo random (), int num = Rd.nextint (1000000), while (num < 100000) {num = Rd.nextint (10 00000);} String passwd = string.valueof (num);//Get the original data wwkadto dtopwd = WWKAMNG.FINDOUTQ (Form.getaccount2 ());d Topwd.setpassword (passwd);//Synchronize the new password to the database wwkamng.resetnewpwd (DTOPWD);//Return to the user's new password 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 ()): "None"), Result.put ("Showrtime", String.valueof (Dtopwd.getregistertime ())); Result.put ("Newpwd", passwd), Result.put ("Showaccount", Form.getaccount2 ()), Result.put ("Haserror", "1");//account number, correct answer}Jsonobject JSON = jsonobject.fromobject (result); return json.tostring ();}  /** * @description send a mobile phone verification code, verify the existence of the account, and the account number and the mobile phone number of the input is consistent * @param request * @param response * @param phonenumber * @param Account * @return void return value type */@ResponseBody @requestmapping ("wwka_getcode.html") public void GetCode ( HttpServletRequest request, HttpServletResponse Response, String PhoneNumber, String account) {StringBuffer Errerb = new S Tringbuffer (); if (Stringutils.isblank) {errerb.append ("Please enter your personal account.") <br> ");} else if (!account.matches ("^[1-9]{1}[0-9]{16}[0-9xx]{1}$")) {errerb.append ("Your personal account entered an error. <br> ");} if (Stringutils.isblank (PhoneNumber)) {errerb.append ("Please enter your mobile phone number. <br> ");} else if (!phonenumber.matches ("^1[0-9]{10}$")) {errerb.append ("your phone number entered incorrectly. <br> ");} if (errerb.tostring (). EndsWith ("<br>")) {//If <br> ends, remove <br>errerb.setlength (Errerb.length ()-4) ;} Map<string, string> rs = new hashmap<string, string> ();//checksum does not pass if (errerb.length ()! = 0) {rs.put ("msg", Errerb.tostring ()); Rs.put ("Status", "1"); Jsonutil.write (response, RS); return;} Verify that the account exists wwac01userform form = Wwkamng.getuserinfo, if (form = = null) {Rs.put ("msg", "The account you entered does not exist.") "); Rs.put (" Status "," 1 "); Jsonutil.write (response, RS); return;} else if (!phonenumber.equals (Form.getphonenumber ())) {//account exists, determine if the mobile phone number is consistent with the system Rs.put ("MSG", " The mobile account you entered does not match the mobile phone number that is reserved in the system for that account. "); Rs.put (" Status "," 1 "); Jsonutil.write (response, RS); return;} Above all through, send verification code 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", "mobile phone verification code has been issued by the system, please pay attention to check.") "); Rs.put (" Status "," 1 "); Jsonutil.write (response, RS);} /** * @description Reset Password.  Password sent to the system reserved mobile phone number * @param request * @param response * @param phonenumber * @param account * @param phonecode * @return void return value type */@ResponseBody @requestmapping ("wwka_resetpsw.html") public void ResetPassword (HttpServletRequest request, HttpServletresponse response, String PhoneNumber, String account, String Phonecode) {//First remove verification code to avoid expiration of check time 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 "," Please get the phone verification code first. ") "); 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", "Your input phone code has expired, please re-get it.") "); Rs.put (" Status "," 1 "); Jsonutil.write (response, RS); return;} else{//Verify that the information is valid again StringBuffer Errerb = new StringBuffer (); if (Stringutils.isblank (account)) {Errerb.append (" Please enter your personal account number. <br> ");} else if (!account.matches ("^[1-9]{1}[0-9]{16}[0-9xx]{1}$")) {errerb.append ("Your personal account entered an error. <br> ");} if (Stringutils.isblank (PhoneNumber)) {errerb.append ("Please enter your mobile phone number. <br> ");} else if (!phonenumber.matches ("^1[0-9]{10}$")) {errerb.append ("your phone number entered incorrectly. <br> ");} if (Stringutils.isblank(Phonecode)) {errerb.append ("Please enter your phone to receive the verification code. <br> ");} else if (!phonecode.matches ("^[0-9]{6}$")) {errerb.append ("Your Phone verification code input format is incorrect. <br> ");} if (errerb.tostring (). EndsWith ("<br>")) {//If <br> ends, remove <br>errerb.setlength (Errerb.length ()-4) ;} The checksum does not pass through if (errerb.length ()! = 0) {rs.put ("msg", errerb.tostring ()); Rs.put ("Status", "1"); Jsonutil.write (response, RS); return;} Verify that the account exists wwac01userform form = Wwkamng.getuserinfo, if (form = = null) {Rs.put ("msg", "The account you entered does not exist.") "); Rs.put (" Status "," 1 "); Jsonutil.write (response, RS); return;} else if (!phonenumber.equals (Form.getphonenumber ())) {//account exists, determine if the mobile phone number is consistent with the system Rs.put ("MSG", " The mobile account you entered does not match the mobile phone number that is reserved in the system for that account. "); Rs.put (" Status "," 1 "); Jsonutil.write (response, RS); return;} All above are correctly reset by the IF (Codestr.equals (Phonecode)) {///CAPTCHA code//Generate random captcha string password = new Messagecode (). Getmessagecode (); Wwkadto dto = new Wwkadto ();d to.setaccount (account);d To.setpassword (password);//Reset Password wwkamng.resetnewpwd (DTO); String msg = "Your personal account password has been reset to:" + password+ ", please use the reset of the newCode to log in and change the password. "; Messageutil.sendmessage (MSG, PhoneNumber), Session.removeattribute (Session.getid () + "_resetpassword"), Rs.put ("msg "," The password for your personal account has been sent to your phone. Please login and change your password in time. "); Rs.put (" Status "," 1 "); Jsonutil.write (response, RS);} Else{rs.put ("msg", "you entered the phone verification code is not correct, please re-enter.") "); Rs.put (" Status "," 1 "); Jsonutil.write (response, RS);}}}}


The front-end page is omitted here.

Using threads to create a tool class to send a phone verification code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.