验证码登录简单实现

文章来自:https://blog.csdn.net/binggetong/article/details/78805992

       业务:

       手机端点击发送验证码,调用第三方平台(我们用的是“任信了”平台)的接口,去给手机发短信验证码。


  过程:   

                    


       代码:

           


 
 
  1. /**
  2. * 发送短信验证码
  3. * @param json 前台传入电话号码
  4. * @return 返回发送结果向前台
  5. */
  6. @RequestMapping( "/getTestCode")
  7. @ResponseBody
  8. public GetTestCodeResult sendTestCode(@RequestParam(value="phone",defaultValue="") String phoneNumber ){
  9. GetTestCodeResult result = new GetTestCodeResult();
  10. if(phoneNumber == null || phoneNumber.length()== 0 ){
  11. result.setState(Result.ERROR);
  12. result.setMessage( "手机号为空");
  13. return result;
  14. }
  15. String code =TestCode.getCode();
  16. if( code== null || code.length()== 0){
  17. result.setState(Result.ERROR);
  18. result.setMessage( "无效的验证码");
  19. return result;
  20. }
  21. try {
  22. SMS.batchsendsm(phoneNumber,code);
  23. } catch (Exception e) {
  24. result.setState(Result.ERROR);
  25. result.setMessage( "验证码发送失败");
  26. return result;
  27. }
  28. TestCodeInforVo testCodeInfor = new TestCodeInforVo();
  29. testCodeInfor.setCode(code);
  30. testCodeInfor.setPhone(phoneNumber);
  31. testCodeInfor.setDate(System.currentTimeMillis());
  32. testCodeInforMap.put(phoneNumber,testCodeInfor);
  33. result.setState(Result.SUCCESS);
  34. result.setMessage( "验证码发送成功");
  35. result.setData(code); //测试
  36. return result;
  37. }

        上面这个是发送验证码的方法,其中包括了2个工具类:


        No.1 生成5位随机数

        


 
 
  1. public class TestCode {
  2. private final static int codeLength = 5;
  3. /**
  4. * @see 产生随机验证码
  5. * @return 验证码字符串
  6. */
  7. public static String getCode(){
  8. Random rand = new Random();
  9. int a ;
  10. String result = "";
  11. for( int j = 0; j<codeLength; j++ ){
  12. a = Math.abs( rand.nextInt()% 9 );
  13. result += String.valueOf(a);
  14. }
  15. return result;
  16. }
  17. }

        No.2 调用第三方发送短信接口

        


 
 
  1. package com.cn.zhongcai.util.app.util;
  2. import java.io.BufferedReader;
  3. import java.io.IOException;
  4. import java.io.InputStreamReader;
  5. import java.io.OutputStreamWriter;
  6. import java.net.HttpURLConnection;
  7. import java.net.URL;
  8. import java.net.URLEncoder;
  9. import java.security.MessageDigest;
  10. import java.security.NoSuchAlgorithmException;
  11. public class SMS {
  12. //把接口地址和参数赋值,之后调用SMS3方法,参数photo是手机号,code是之前生成的验证码。
  13. public static void batchsendsm(String phone,String code)
  14. {
  15. try{
  16. String userid = URLEncoder.encode( "15732622061", "UTF-8"); //188
  17. String url = "http://apis.renxinl.com:8080/smsgate/varsend.do?";
  18. String para = "user="+userid+ "&pwd=9fa41ab9c5352bc29babd621a73d¶ms="+phone+ ","+code+ "&mid=15552";
  19. String str= "";
  20. str=SMS3(para,url);
  21. System.out.println(str);
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. }
  25. }
  26. //postData是上面拼接的参数值,postURL 是接口的地址。我觉得这个方法是能访问到第三方接口的方法。
  27. public static String SMS3(String postData,String postUrl){
  28. try{
  29. URL url = new URL(postUrl);
  30. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  31. conn.setRequestMethod( "POST");
  32. conn.setRequestProperty( "accept", "*/*");
  33. conn.setRequestProperty( "connection", "Keep-Alive");
  34. conn.setRequestProperty( "user-agent",
  35. "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
  36. conn.setRequestProperty( "Content-Type", "application/x-www-form-urlencoded");
  37. conn.setUseCaches( false);
  38. conn.setDoOutput( true);
  39. conn.setDoInput( true);
  40. OutputStreamWriter out= new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
  41. out.write(postData);
  42. out.flush();
  43. out.close();
  44. if(conn.getResponseCode()!=HttpURLConnection.HTTP_OK){
  45. System.out.println( "connect failed!");
  46. return "";
  47. }
  48. String line,result = "";
  49. BufferedReader in = new BufferedReader( new InputStreamReader(conn.getInputStream(), "utf-8"));
  50. while((line= in.readLine()) != null){
  51. result += line+ "\n";
  52. }
  53. in.close();
  54. return result;
  55. } catch(IOException e){
  56. e.printStackTrace(System.out);
  57. }
  58. return "";
  59. }
  60. }

        其中:

        1、我从第三方那要了一个demo,从中摘出来自己需要用的代码。

        2、短信接口有固定模板和变量模板, 这里我们用到的是变量模板,因为验证码是个变量。

           

         3、接口文档里给的很清楚:

            

            


         4、其中最后一步保存,该手机号的验证码和发送时间,用到了一个Map保存。

           

private final static Map<String, TestCodeInforVo> testCodeInforMap = new HashMap<String,TestCodeInforVo>();
 
 
  

          发送完验证码之后:

          

testCodeInforMap.put(phoneNumber,testCodeInfor);
 
 
         保存到了map里面,到时候找验证码和时间,也从这个map里面找,手机号是key,这个保存着验证码和时间的实体是value。


         短信验证码就到此告一段落。接下来看登陆的逻辑:

 


   登陆的过程:

                                      


          登陆代码:

           


 
 
  1. /**
  2. * 用户登录接口
  3. * @param json 登录参数
  4. * @return 登录成功返回用户信息
  5. */
  6. @RequestMapping( "/login")
  7. @ResponseBody
  8. public LoginResult login(@RequestParam(value="testCode",defaultValue="") String testCode,
  9. @RequestParam(value="identity",defaultValue="") String identity,
  10. @RequestParam(value="phone",defaultValue="") String phone, HttpServletRequest request){
  11. //String serverPath = request.getScheme() + "://"+ request.getServerName() + ":" +
  12. // request.getServerPort()+request.getContextPath() + "/";
  13. LoginResult result = new LoginResult();
  14. if( identity == null || identity.length() == 0 ){
  15. result.setState(Result.ERROR);
  16. result.setMessage( "证件号为空");
  17. return result;
  18. }
  19. if(phone== null || phone.length() == 0 ){
  20. result.setState(Result.ERROR);
  21. result.setMessage( "手机号为空");
  22. return result;
  23. }
  24. if( testCode == null || testCode.length() == 0 ){
  25. result.setState(Result.ERROR);
  26. result.setMessage( "验证码为空");
  27. return result;
  28. }
  29. TestCodeInforVo testCodeInfor = (TestCodeInforVo) testCodeInforMap.get(phone);
  30. if( testCodeInfor == null || testCodeInfor.getCode() == null || testCodeInfor.getCode().length()== 0 ){
  31. result.setState(Result.ERROR);
  32. result.setMessage( "验证码不存在");
  33. return result;
  34. }
  35. if(!testCode.equals(testCodeInfor.getCode())){
  36. result.setState(Result.ERROR);
  37. result.setMessage( "验证码错误");
  38. return result;
  39. }
  40. testCodeInforMap.remove(phone);
  41. //验证验证码是否过期
  42. if( System.currentTimeMillis()- testCodeInfor.getDate() > testCodeOutDate ){
  43. result.setState(Result.ERROR);
  44. result.setMessage( "验证码已过期");
  45. return result;
  46. }
  47. List<UserEntity> users = userService.getUserByPhoneIdentity(phone,identity);
  48. if( users.isEmpty()){
  49. result.setState(Result.ERROR);
  50. result.setMessage( "用户不存在");
  51. return result;
  52. }
  53. if( users.size() != 1){
  54. result.setState(Result.ERROR);
  55. result.setMessage( "认证用户不唯一");
  56. return result;
  57. }
  58. if( users.get( 0).getAccountStatus() != null && users.get( 0).getAccountStatus().equals( "0")){
  59. result.setState(Result.ERROR);
  60. result.setMessage( "该用户被冻结");
  61. return result;
  62. }
  63. UserEntity user = users.get( 0);
  64. user.setQrCode(user.getQrCode());
  65. user.setPersonalPhotos(user.getPersonalPhotos());
  66. user.setIdCardAvatarFace(user.getIdCardAvatarFace());
  67. user.setIdCardNationalEmblem(user.getIdCardNationalEmblem());
  68. String siteID= "";
  69. //根据user的role去判断该用户所在的站点ID
  70. if (user.getRole()== 0) {
  71. //0是管理员
  72. //根据用户的ID去站点表里查询站点的最早添加的哪一个站点Id
  73. siteID=userService.findSiteIDByTimeAdmin(user.getId());
  74. }
  75. if(user.getRole()== 2) //2是业主
  76. {
  77. //根据用户的ID去站点表里查询站点的最早添加的哪一个站点Id
  78. siteID=userService.findSiteIDByTimeOwner(user.getId());
  79. }
  80. if (user.getRole()== 1) { //1是营业员
  81. //营业员对应的,最早添加的哪一个站点Id
  82. siteID=userService.findSiteIDByTimeOwnerSale(user.getId());
  83. }
  84. user.setSiteID(siteID);
  85. result.setState(Result.SUCCESS);
  86. result.setMessage( "登录成功");
  87. AppLoginUser appUser= new AppLoginUser();
  88. HttpSession session=request.getSession();
  89. appUser.setUserID(user.getId());
  90. appUser.setUserName(user.getName());
  91. appUser.setUserNum(user.getUserNumber());
  92. OrgStructure org=orgService.getOrgByAccount(user.getName());
  93. //appUser.setOrgId(org.getOrgId());
  94. session.setAttribute( "appLoginUser", appUser);
  95. result.setData(user);
  96. return result;
  97. }


        其中:

        1、判断验证码是否正确:(从刚才那个map里面,根据手机号取值)

          

TestCodeInforVo testCodeInfor =  (TestCodeInforVo) testCodeInforMap.get(phone);
 
 

         从这个实体里面取出验证码和时间。


         2、验证码是否过期:

          过期时间:

          

private final static long testCodeOutDate = 5*60*1000;  //验证码过期时间
 
 



 
 
  1. //验证验证码是否过期
  2. if( System.currentTimeMillis()- testCodeInfor.getDate() > testCodeOutDate ){
  3. result.setState(Result.ERROR);
  4. result.setMessage( "验证码已过期");
  5. return result;
  6. }
 

            验证完之后删除他:

         

testCodeInforMap.remove(phone);
 
 
 

          3、当初想的是存到session里面会怎么写,还没想好,希望路过的大神指导。



 小结:

      发送验证码和登陆的逻辑之前觉得挺复杂的,当画图总结一遍之后,思路就清楚多了,还是要静下心来多总结。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值