Springboot学习笔记——Java实现短信登录验证功能--Servlet/SSM/SpringBoot都可以用
小白记录一下短信验证登入的实现,方便以后可以拿来直接用。
发短信平台:互亿无线 官网地址
登入注册啥的就不说了,新人注册会送十条短信验证,想要buy一些学习用的话 也很便宜,就不多说了
我们主要需要的就是这个APIID和APPKEY,到时候工具类需要用。
pom工程需要导入两个依赖:
<!--发送手机验证码--><dependency><groupId>dom4j</groupId><artifactId>dom4j</artifactId><version>1.6.1</version></dependency><dependency><groupId>commons-httpclient</groupId><artifactId>commons-httpclient</artifactId><version>3.1</version></dependency>
接下来贴上工具类代码:
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;import java.io.IOException;public class SendSMS {private static String Url = "http://106.ihuyi.cn/webservice/sms.php?method=Submit";public static int sendYzCode(String phone) {HttpClient client = new HttpClient();PostMethod method = new PostMethod(Url);client.getParams().setContentCharset("GBK");method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=GBK");int mobile_code = (int)((Math.random()*9+1)*100000);String content = new String("您的验证码是:" + mobile_code + "。请不要把验证码泄露给其他人。");NameValuePair[] data = {//提交短信new NameValuePair("account", "填你的APIID"), //查看用户名是登录用户中心->验证码短信->产品总览->APIIDnew NameValuePair("password", "填你的APPKEY"), //查看密码请登录用户中心->验证码短信->产品总览->APIKEY//new NameValuePair("password", util.StringUtil.MD5Encode("密码")),new NameValuePair("mobile", phone),new NameValuePair("content", content),};method.setRequestBody(data);try {client.executeMethod(method);String SubmitResult =method.getResponseBodyAsString();//System.out.println(SubmitResult);Document doc = DocumentHelper.parseText(SubmitResult);Element root = doc.getRootElement();String code = root.elementText("code");String msg = root.elementText("msg");String smsid = root.elementText("smsid");System.out.println(code);System.out.println(msg);System.out.println(smsid);if("2".equals(code)){System.out.println("短信提交成功");return mobile_code;}} catch (HttpException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (DocumentException e) {// TODO Auto-generated catch blocke.printStackTrace();}return 0;}
}
工具类只需要把APIID和APPKEY替换一下就可以用啦。
接下来贴前端代码
<div class="login-style"><dl><dd><input name="phone" type="text" id="phone" placeholder="您的手机号码"/></dd></dl><!--<dl id="yz-code" style="display: none;"><dd><input type="text" id="txtCode2" name="txtCode2" style="width: 133px; margin-right: 10px;" placeholder="验证码" /><img id="Img1" src="" width="90" height="34" title="点击换一个" style="vertical-align: middle; margin-top: -4px;" onclick="this.src='/ImgCode.aspx?t='+Math.random()*100" /></dd></dl> --><dl><dd><input type="text" id="code" name="code" onkeydown="enterHandler(event)" style="width: 133px;"placeholder="短信验证码"/><input type="button" id="zphone" class="btn_mfyzm"value="获取手机验证码" /></dd></dl><div class="remember"><input type="checkbox" id="issave1" checked/><label for="issave1">下次自动登录</label></div><div class="tishi"></div><button type="button" id="dynamicLogon" style="outline:none">登 录</button></div>
JS代码:
<script type="text/javascript">$(function () {$("#zphone").click(function () {//先判断是否输入手机号码,再判断手机号格式是否正确,最后判断是否是已经注册过的手机号var phone=$("#phone").val();if(phone==null||phone==""){// $("#msg").text("手机号不能为空").css("color","red");Tip('手机号不能为空!');$("#phone").focus();}else if(!(/^1[3456789]\d{9}$/.test(phone))){// $("#msg").text("手机号格式不正确").css("color","red");Tip('手机号格式不正确!');$("#phone").focus();}else{$.ajax({url:'user/checkPhone',type:'post',data:{"phone":phone},dataType:'json',success:function (data) {if(data){//发送验证码alert("通过啦!准备执行发送验证码方法");sendCode(phone);}else{Tip('手机号尚未注册,请注册后再登陆!')// $("#msg").html("<a href='login.html'>手机号尚未注册,请注册后再登陆</a>");}}});}})//登陆$("#dynamicLogon").click(function () {var phone=$("#phone").val();var code=$("#code").val();$.ajax({url:'toPhoneLogin',type:'post',data:{"code":code,"phone":phone},dataType:'json',success:function (data) {if(data){//登陆成功,网站首页window.location.href="home";}else{//失败Tip('登陆失败,请重试')// $("#msg").text("登陆失败,请重试").css("color","red");}}})});})function sendCode(phone) {$.ajax({url:'sendCode',type:'post',data:{"phone":phone},dataType:'json',success:function (data) {if(data){// $("#msg").text("验证码发送成功").css("color","green");Tip('验证码发送成功!');}else{// $("#msg").text("验证码发送失败,请重试").css("color","red");Tip('验证码发送失败,请重试!');}}})}
</script>
后台代码:
/*** 发送手机验证码*/@RequestMapping("/sendCode")public void sendCode(HttpServletRequest request, HttpServletResponse response) throws IOException {String phone = request.getParameter("phone");int code = SendSMS.sendYzCode(phone);if (code != 0) {session = request.getSession();session.setAttribute("yzcode", phone + "#" + code);//1227346764#8765response.getWriter().print(true);} else {response.getWriter().print(false); //没短信了}}@RequestMapping("/toPhoneLogin")public void toPhoneLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {String code = request.getParameter("code");String phone = request.getParameter("phone");String code1 = phone + "#" + code;//页面提交的String code2 = (String) session.getAttribute("yzcode");//session中获取到的if (code1.equals(code2)) {//登陆成功,将登陆的用户保存到session中//根据用户的电话获取登陆用户User loginUser = userService.getUserByPhone(phone);
// request.getSession()session.setAttribute("user", loginUser);response.getWriter().print(true);} else {response.getWriter().print(false);}}
最后贴上效果图
至此短信登录功能就搞定了