Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to realize the function of SMS CAPTCHA when registering and logging in a website by Java?

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains the "Java how to achieve the development of website registration, login often need to use SMS CAPTCHA function", the content of the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Java how to achieve the development of website registration, login often need to use SMS CAPTCHA function" bar!

Developers often need to use the SMS CAPTCHA function when registering and logging in to the development website. The following editor will explain in detail how to integrate this function.

Here's an example of using hazelnut cloud SMS:

1. First sign up for a hazelnut cloud account, registered address: http://sms_developer.zhenzikj.com/zhenzisms_user/register.html

two。 Enter through the personal login entry after registration, address: http://sms_developer.zhenzikj.com/zhenzisms_user/login.html

3. When you enter "Application Management", an application is automatically created by default to obtain AppId and AppSecret, which are used for development.

4. Download SDK, which I use for java development, so the following example also takes java as an example, http://smsow.zhenzikj.com/doc/sdk.html

You can download the jar package directly and import it into the project, or you can use maven

Com.zhenzikj

Zhenzisms

1.0.2

5. Refer to the development documentation and send SMS http://smsow.zhenzikj.com/doc/java_sdk_doc.html

AppId and AppSecret are the apiUrl parameters we just obtained from application management. Since I am a personal account, I always use https://sms_developer.zhenzikj.com.

Note: all those registered through themselves are personal accounts, and corporate accounts need to contact customer service separately to apply.

It's easy to initialize a ZhenziSmsClient object, and then call the send () method to send a text message.

6. A complete example

A complete example of java sending SMS CAPTCHA, this is an official use of demo, with 60-second countdown function.

Effect:

Source code

Implementation process of SMS CAPTCHA

1. Construct the mobile phone verification code to generate a 6-digit random number string.

2. Use the interface to send the mobile phone number and verification code to the SMS platform, and then the SMS platform sends the verification code to the established mobile phone number.

3. Store the mobile number verification code and operation time in Session for later verification

4. Receive the verification code, mobile phone number and other registration data filled in by the user

5. Compare whether the submitted verification code is consistent with the verification code in Session, and determine whether the submitted action is within the validity period.

6. If the CAPTCHA code is correct and within the validity period, the request is passed and the corresponding business is handled.

I am a java developer, using springMvc at the back end and jsp + jquery at the front end

Html

Verification code using demo function getBasePath () {return';} account: password: mobile number: verification code: get SMS verification code to submit

Js

(function () {/ / SMS verification code countdown var countdownHandler = function () {var $button = $(".sendVerifyCode"); var number = 60; var countdown = function () {if (number = = 0) {$button.attr ("disabled", false); $button.html ("send verification code"); number = 60 Return;} else {$button.attr ("disabled", true); $button.html (number + "resend in seconds"); number--;} setTimeout (countdown,1000);} setTimeout (countdown,1000) } / / send SMS verification code $(".sendVerifyCode"). On ("click", function () {var $mobile = $("input [name=mobile]"); var data = {}; data.mobile = $.trim ($mobile.val ()); if (data.mobile = =') {alert ('Please enter mobile phone number'); return } var reg = / ^ 1\ d {10} $/; if (! reg.test (data.mobile)) {alert ('Please enter a valid mobile phone number'); return } $.ajax ({url: getBasePath () + "/ sendSms", async: true, type: "post", dataType: "text", data: data, success: function (data) {if (data = = 'success') {countdownHandler () Return;} alert (data);}});}) / / submit $(".sub-btn") .on ("click", function () {var data = {}; data.userId = $.trim ($("input [name=userId]"). Val () Data.password = $.trim ($("input [name=password]"). Val ()); data.mobile = $.trim ($("input [name=mobile]"). Val ()); data.verifyCode = $.trim ($("input [name=verifyCode]"). Val ()); if (data.userId = =') {alert ("Please enter account"); return } if (data.password = ='') {alert ("Please enter password"); return;} if (data.mobile = ='') {alert ("Please enter Mobile number"); return;} if (data.verifyCode = ='') {alert ("Please enter CAPTCHA") Return } $.ajax ({url: getBasePath () + "/ register", async: true, type: "post", dataType: "text", data: data, success: function (data) {if (data = = 'success') {alert ("registered successfully") Return;} alert (data);});})}

All non-empty and mobile number format verification is omitted here

Process:

1) fill in the mobile phone number

2) obtain the mobile phone number and call the sendSms.html API to send SMS verification code to the mobile phone.

3) after the user's mobile phone receives the verification code, fill it in the "verification code" text box

Back-end code

Send SMS verification code

Package com.zhenzi.sms; import java.io.IOException;import java.util.Random; import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession; import com.alibaba.fastjson.JSONObject; / * get CAPTCHA * / public class SendSmsServlet extends HttpServlet {private static final long serialVersionUID = 1L / / SMS platform related parameters private String apiUrl = "https://sms_developer.zhenzikj.com"; private String appId =" 000000 "; private String appSecret =" c384b67bdsserev3343cdda4de5c8 "; public SendSmsServlet () {super ();} protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost (request, response) } / * SMS platform uses Hazelnut Cloud SMS (smsow.zhenzikj.com) * / protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {String mobile = request.getParameter ("mobile"); JSONObject json = null; / / generate 6-digit CAPTCHA String verifyCode = String.valueOf (new Random (). NextInt (899999) + 100000) / / send SMS ZhenziSmsClient client = new ZhenziSmsClient (apiUrl, appId, appSecret); String result = "{code:0}"; / / client.send (mobile, "your verification code is" + verifyCode + ", the code is valid for 5 minutes, and the code can only be used once!); json = JSONObject.parseObject (result) If (json.getIntValue ("code")! = 0) {/ / failed to send SMS message renderData (response, "fail"); return;} / / stores the verification code in session and the creation time / / as json. Ali's fastjson HttpSession session = request.getSession () is used here. Json = new JSONObject (); json.put ("mobile", mobile); json.put ("verifyCode", verifyCode); json.put ("createTime", System.currentTimeMillis ()); / / store the authentication code in SESSION request.getSession (). SetAttribute ("verifyCode", json); renderData (response, "success"); return } catch (Exception e) {e.printStackTrace ();} renderData (response, "fail");} protected void renderData (HttpServletResponse response, String data) {try {response.setContentType ("text/plain;charset=UTF-8"); response.getWriter (). Write (data);} catch (Exception e) {e.printStackTrace () }}}

The json tool uses Ali's fastjson.

Replace appId and appSecret with your own, which can be obtained after registration.

Registered address: http://sms_developer.zhenzikj.com/zhenzisms_user/register.html

Submit registration

Package com.zhenzi.sms; import java.io.IOException; import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse; import com.alibaba.fastjson.JSONObject; / * Registration * / public class RegisterServlet extends HttpServlet {private static final long serialVersionUID = 1L; public RegisterServlet () {super () } protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost (request, response);} protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String userId = request.getParameter ("userId"); String password = request.getParameter ("password"); String mobile = request.getParameter ("mobile"); String verifyCode = request.getParameter ("verifyCode") JSONObject json = (JSONObject) request.getSession (). GetAttribute ("verifyCode"); if (json = = null) {renderData (response, "CAPTCHA error"); return;} if (! json.getString ("mobile") .equals (mobile)) {renderData (response, "wrong mobile number"); return } if (! json.getString ("verifyCode") .equals (verifyCode)) {renderData (response, "CAPTCHA error"); return;} if ((System.currentTimeMillis ()-json.getLong ("createTime")) > 1000 * 60 * 5) {renderData (response, "CAPTCHA expired"); return } / / other business codes renderData (response, "success");} protected void renderData (HttpServletResponse response, String data) {try {response.setContentType ("text/plain;charset=UTF-8"); response.getWriter (). Write (data);} catch (Exception e) {e.printStackTrace ();}

Ok, it's done.

Thank you for your reading, the above is the "Java how to achieve the development of website registration, login often need to use SMS CAPTCHA function" content, after the study of this article, I believe you on how to achieve Java development website registration, login often need to use SMS CAPTCHA function of this problem has a deeper understanding, the specific use of the need for practical verification. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report