传入size,获取随机位数的验证码 方法

发布时间 2023-11-28 15:51:43作者: 爱豆技术部

获取验证码

        /**
        * 获取size位数的随机验证码
        *
        * 0.12345;当要4位数的验证码,*10 的3次方 Math.pow(10,size-1)
        * Math.random()*9+1 防止永远 0 开始
         */
       double random = (Math.random()*9+1)*(Math.pow(10,size-1));
       int num = (int) random;
       System.out.println("num = " + num);

应用方法

 @GetMapping("numberCode/{size}")
   public String numberCode(@PathVariable("size") int size){
       System.out.println("size = " + size);

       /**
        * 获取size位数的随机验证码
        *
        * 0.12345;当要4位数的验证码,*10 的3次方 Math.pow(10,size-1)
        * Math.random()*9+1 防止永远 0 开始
         */
       double random = (Math.random()*9+1)*(Math.pow(10,size-1));
       int num = (int) random;
       System.out.println("num = " + num);

       JSONObject jsonObject = new JSONObject();
       jsonObject.put("code",1);
       jsonObject.put("message","Success");
       JSONObject date = new JSONObject();
       date.put("numberCode",num);
       jsonObject.put("date",date);
       return jsonObject.toString();

        /**
        * 此处的json解析使用pom 依赖
        *         <dependency>
        *             <groupId>net.sf.json-lib</groupId>
        *             <artifactId>json-lib</artifactId>
        *             <version>2.4</version>
        *             <classifier>jdk15</classifier>
        *         </dependency>
        */

  }