当前位置:主页 > 软件编程 > JAVA代码 >

SpringBoot发送短信验证码的实例

时间:2022-10-06 11:58:09 | 栏目:JAVA代码 | 点击:

1、注册短信通账号

网址:http://sms.webchinese.cn

在这里插入图片描述

在这里插入图片描述

2、导入依赖

		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>
		<!--短信验证依赖导入-->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.0.1</version>
        </dependency>

3、随机验证码的工具类

public class CodeUtil {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    
    /**
     * 随机生成6位验证码
     *
     */
    public String getRandomCode(Integer code){
        Random random = new Random();
        StringBuffer result= new StringBuffer();
        for (int i=0;i<code;i++){
            result.append(random.nextInt(10));
        }
        return result.toString();
    }
    
    //保存验证码和时间
    public Code saveCode(String code){
        Code code1=new Code();
        SimpleDateFormat sf = new SimpleDateFormat("yyyyMMddHHmmss");
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, 5);
        String currentTime = sf.format(c.getTime());// 生成5分钟后时间,用户校验是否过期
        //验证码加密
        String encode=passwordEncoder().encode(code);
        code1.setCode(encode);
        code1.setCurrentTime(currentTime);
        return code1;
    }
    
    /**
     * 解密处理
     * @param code 输入
     * @param code1 目标
     */
    public Boolean deciphering(String code,String code1){
        boolean matches = passwordEncoder().matches(code,code1);
        return matches;
    }


}

4、短信发送工具类

@Component
public class TelMessageUtil {
    private static final String SMS_Url = "http://sms.webchinese.cn/web_api/";

    /**
     * @param Uid SMS用户id
     * @param Key 接口秘钥:SMS登录可查(非登录密码)
     * @param sendPhoneNum 短信发送目标号码
     * @param desc 短信内容
     * @return Integer(1:成功码,其他失败,具体参见注释)
     */
    public static Integer send(String Uid,String Key,String sendPhoneNum,String desc){
    
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(SMS_Url);
        post.addRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=gbk");// 在头文件中设置转码
    
        //设置参数
        NameValuePair[] data = {
                new NameValuePair("Uid", Uid),
                new NameValuePair("Key", Key),//秘钥
                new NameValuePair("smsMob", sendPhoneNum),
                new NameValuePair("smsText", desc)
        };
    
        post.setRequestBody(data);
    
        try {
            client.executeMethod(post);
        } catch (Exception e) {  e.printStackTrace();  }


        Header[] headers = post.getResponseHeaders();
        int statusCode = post.getStatusCode();
        System.out.println("statusCode:" + statusCode);
        for (Header h : headers) {
            System.out.println(h.toString());
        }
    
        String result ="";
        try {
            result = new String(post.getResponseBodyAsString().getBytes("gbk"));
        } catch (Exception e) {  e.printStackTrace();  }
    
        post.releaseConnection();
    
        return Integer.parseInt(result);
    }
    /**
     *  -1  没有该用户账户
     -2     接口密钥不正确 [查看密钥]不是账户登陆密码
     -21    MD5接口密钥加密不正确
     -3     短信数量不足
     -11    该用户被禁用
     -14    短信内容出现非法字符
     -4     手机号格式不正确
     -41    手机号码为空
     -42    短信内容为空
     -51    短信签名格式不正确接口签名格式为:【签名内容】
     -6     IP限制
     大于0   短信发送数量
     以上作为补充
     */
    public static String getMessage(Integer code){
        String message;
        if(code > 0 ) {
            message = "SMS-f发送成功!短信量还有" + code + "条";
        }else if(code == -1){
            message = "SMS-没有该用户账户";
        }else if(code == -2){
            message = "SMS-接口密钥不正确";
        }else if(code == -21){
            message = "SMS-MD5接口密钥加密不正确";
        }else if(code == -3){
            message = "SMS-短信数量不足";
        }else if(code == -11){
            message = "SMS-该用户被禁用";
        }else if(code == -14){
            message = "SMS-短信内容出现非法字符";
        }else if(code == -4){
            message = "SMS-手机号格式不正确";
        }else if(code == -41){
            message = "SMS-手机号码为空";
        }else if(code == -42){
            message = "SMS-短信内容为空";
        }else if(code == -51){
            message = "SMS-短信签名格式不正确接口签名格式为:【签名内容】";
        }else if(code == -6){
            message = "SMS-IP限制";
        }else{
            message = "其他错误";
        }
        return message;
    }


}

5、测试

	//前台验证手机号
    @RequestMapping("/checkTel")
    public String checkTel(@RequestParam("tel") String tel,
                           HttpSession session,
                           Model model){
        Users users=new Users();
        users.setTel(tel);
        if (loginService.CheckOnly(users)) {
            model.addAttribute("msg","没有此用户,请注册!");
            return "register";
        }else {
            model.addAttribute("info","已向你的手机号为"+tel+"发送了验证码");
            Long id = loginService.findIdByTel(tel);
            session.setAttribute("user_id",id);
            //发送验证码
            CodeUtil codeUtil=new CodeUtil();
            //获取六位验证码
            String randomCode = codeUtil.getRandomCode(6);
            //先清除session域
            session.removeAttribute("checkCode");
            //加密验证码存放session域中
            session.setAttribute("checkCode",codeUtil.passwordEncoder().encode(randomCode));
            Integer resultCode = TelMessageUtil.send("****","************",tel,
                    "【高校志愿者平台】你的验证码为【"+randomCode+"】(若不是本人操作,可忽略该条邮件)"
            );
            System.out.println("日志信息"+resultCode);
            return "updatePwd";
        }
    }

您可能感兴趣的文章:

相关文章