1、使用Post异步发送请求(发送短信),离焦事件触发时判断
<script src="layer/layer.js"></script><!--离焦事件--><script type="text/javascript" th:inline="javascript">$("#username").blur(function(){//判断用户名谁否符合手机号的格式,正则if(/^1([358][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/.test($("#username").val())){//如果符合,发短信,$.post (ajax)var telephone = $("#username").val()$.post(//url 给/sendSMS权限放行[[@{~/sendSMS}]],//参数{"telephone":telephone},//回调函数function(data){alert("success")},//数据格式"json")}else{//不符合,给出提示信息layer.msg("手机号格式有误!!")}})$("#repassword").blur(function(){alert("repassword")})$("#SMS").blur(function(){alert("SMS")})</script>
package com.zzz.blog.controller;import ...@Controller
public class VisitorController {//ajax@RequestMapping("/sendSMS")@ResponseBody public String sendSMS(String telephone) {//给手机号发信息System.out.println(telephone);return "";}}
2、发送手机验证码(使用腾讯云短信服务,注册方法搜索之前文章)
复制qcloudsms-1.0.5.jar到工程bin文件夹下,并build path一下。
修改sendSMS方法
//ajax 给手机号发信息@RequestMapping("/sendSMS")@ResponseBody public String sendSMS(String telephone,HttpSession session) {//appid appkeyint appid = xxx;String appkey = "xxx";//短信模板idint templateId = xxx;//签名的名字String smsSign = "玄尺软件编程公众号";//给谁发String phoneNumber = telephone;//验证码String[] params = new String[1];Random r = new Random();String code = "";for(int i=0;i<4;i++) {code += r.nextInt(10);}//放入session域中session.setAttribute("SMS", code);params[0] = code;SmsSingleSender sender = new SmsSingleSender(appid, appkey);//地区、电话、模板id、验证码、签名SmsSingleSenderResult result;try {result = sender.sendWithParam("86", phoneNumber, templateId, params, smsSign, "", "");System.out.println(result);} catch (HTTPException | JSONException | IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}return "";}
3、判断手机号是否已存在
@Controller
public class VisitorController {@Autowiredprivate VisitorService visitorService;//ajax 给手机号发信息@RequestMapping("/sendSMS")@ResponseBody public String sendSMS(String telephone,HttpSession session) {//判断数据库是否存在该手机号//存在,不发送短信String json = null;if (visitorService.findVisitorByUsername(telephone) != null) {json = "{\"message\":"+false+"}";} //不存在,发送短信else {json = "{\"message\":"+true+"}";SMS(telephone, session);}return json;}public void SMS(String telephone,HttpSession session) {//appid appkeyint appid = xxx;String appkey = "xxx";//短信模板idint templateId = xxx;//签名的名字String smsSign = "玄尺软件编程公众号";//给谁发String phoneNumber = telephone;//验证码String[] params = new String[1];Random r = new Random();String code = "";for(int i=0;i<4;i++) {code += r.nextInt(10);}//放入session域中session.setAttribute("SMS", code);params[0] = code;SmsSingleSender sender = new SmsSingleSender(appid, appkey);//地区、电话、模板id、验证码、签名SmsSingleSenderResult result;try {result = sender.sendWithParam("86", phoneNumber, templateId, params, smsSign, "", "");System.out.println(result);} catch (HTTPException | JSONException | IOException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
package com.zzz.blog.service;import ...
@Service
public interface VisitorService {Visitor saveVisitory(Visitor visitor);Visitor findVisitorByUsername(String telephone);}
package com.zzz.blog.service;import ...@Component
public class VisitorServiceImpl implements VisitorService{@Autowiredprivate VisitorRepository visitorRepository;@Overridepublic Visitor saveVisitory(Visitor visitor) {return visitorRepository.save(visitor);}@Overridepublic Visitor findVisitorByUsername(String telephone) {return visitorRepository.findVisitorByUsername(telephone);}}
package com.zzz.blog.repository;import ...public interface VisitorRepository extends CrudRepository<Visitor, Long>{@Query(value = "select * from visitor where username = ?1",nativeQuery = true)Visitor findVisitorByUsername(String telephone);}
<script type="text/javascript" th:inline="javascript">$("#errorMessage").hide();...//回调函数function(data){if(data.message){$("#errorMessage").hide();layer.msg("手机验证码已发送,请注意查收!!")}else{$("#errorMessage").show(); //在前面先调用先隐藏错误信息$("#errorMessage").html("该手机号已经被注册!!");}},...
4、测试发送短信以及用户名是否重复
测试发送短信成功以后,把验证码发送代码注释掉(因为发送短信需要收费)
System.out.println(code);// SmsSingleSender sender = new SmsSingleSender(appid, appkey);
// //地区、电话、模板id、验证码、签名
// SmsSingleSenderResult result;
// try {
// result = sender.sendWithParam("86", phoneNumber, templateId, params, smsSign, "", "");
// System.out.println(result);
// } catch (HTTPException | JSONException | IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
在visitor表中插入一条手机号用户数据,测试用户重复情况下的提示信息,测试通过。
5、判断两次密码是否一致
$("#repassword").blur(function(){//判断两次密码是否一致if($("#password").val() != $("#repassword").val()){$("#errorMessage").show();$("#errorMessage").html("两次密码输入不一致!!");}else{$("#errorMessage").hide();}})
6、测试判断手机验证码的正确性
$("#SMS").blur(function(){var sms = $("#SMS").val();$.post(//url 在securityconfig中给权限放行[[@{~/judgeSMS}]],//传参{"smsCode":sms},//回调参数function(data){if(data.message){$("#errorMessage").hide();layer.msg("验证码正确!!")}else{$("#errorMessage").show();$("#errorMessage").html("验证码错误!!");}},//数据格式"json")})
//在VisitorController中添加判断方法@RequestMapping("/judgeSMS")@ResponseBodypublic String judgeSMS(String smsCode,HttpSession session) {String codeInSession = (String)session.getAttribute("SMS");String json = null;if (smsCode.equals(codeInSession)) {json = "{\"message\":"+true+"}";} else {json = "{\"message\":"+false+"}";}return json;}
7、防止皮的用户注册提交错误的表单
...
<form id="visitorRegisterForm" th:action="@{~/registerVisitor}" class="login100-form validate-form">
...
<button onclick="submitButton()" type="button" class="login100-form-btn">注 册</button>
...<!--离焦事件--><script type="text/javascript" th:inline="javascript">$("#errorMessage").hide();var isOkUsername,isOkPassword,isOkSMS; //在每个离焦事件中第一句赋初值为false,在判断正确的逻辑里改值为true...function submitButton(){//防止皮的用户在输入有错误内容的时候注册if(isOkUsername==false){$("#errorMessage").show();$("#errorMessage").html("用户名重复或格式错误!!");}else if(isOkPassword==false){$("#errorMessage").show();$("#errorMessage").html("两次密码输入不一致!!");}else if(isOkSMS==false){$("#errorMessage").show();$("#errorMessage").html("验证码错误!!");}else{$("#visitorRegisterForm").submit()}} </script>
...
8、完成注册功能
@RequestMapping("/registerVisitor") //权限放行public String registerVisitor(Visitor visitor) {Random r = new Random();int random = r.nextInt(8) + 1;visitor.setImage("/images/1-"+random+".jpg");visitorService.saveVisitory(visitor);return "redirect:/visitorLogin";}
测试:输入内容,点击注册按钮,数据库中正确添加数据即可。