springboot+vue实现手机验证码功能

springboot+vue实现手机验证码功能

  1. 榛子云短信平台用户中心注册登录(有免费的一条消息,剩下的需要买)(阿里云个人得备案)
    springboot+vue实现手机验证码功能_第1张图片
    springboot+vue实现手机验证码功能_第2张图片

  2. 在springboot中加入依赖,用到了redis,阿里的fastjson,和短信的平台


		<dependency>
			<groupId>org.springframework.bootgroupId>
			<artifactId>spring-boot-starter-redisartifactId>
			<version>1.4.1.RELEASEversion>
		dependency>
		
		<dependency>
			<groupId>com.zhenzikjgroupId>
			<artifactId>zhenzismsartifactId>
			<version>2.0.2version>
		dependency>
		
		<dependency>
			<groupId>com.alibabagroupId>
			<artifactId>fastjsonartifactId>
			<version>1.2.49version>
		dependency>
  1. 然后直接编写controller层
import com.alibaba.fastjson.JSONObject;
import com.pro.back.util.RedisUtils;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Controller
public class CodeController {

    @Autowired
    RedisUtils redisUtils;
    //短信平台相关参数
    //这个不用改
    private String apiUrl = "https://sms_developer.zhenzikj.com";
    //榛子云系统上获取,六位数
    private String appId = "xxxxxx";
    private String appSecret = "xxxxxxxxxxxxxxxxxxx";

    @ResponseBody
    @GetMapping("/code")
    public boolean getCode(@RequestParam("memPhone") String memPhone, HttpSession httpSession){
        try {
            JSONObject json = null;
            //随机生成验证码
            String code = String.valueOf(new Random().nextInt(999999));
            //将验证码通过榛子云接口发送至手机
            ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("number", memPhone);
            //这个是短信模板的参数,从平台获取
            params.put("templateId", "8369");
            //这个参数就是短信模板上那两个参数
            String[] templateParams = new String[2];
            templateParams[0] = code;
            templateParams[1] = "2分钟";
            params.put("templateParams", templateParams);
            String result = client.send(params);
            json = JSONObject.parseObject(result);
            if (json.getIntValue("code")!=0){//发送短信失败
                return  false;
            }
            //将验证码存到redis中,同时存入创建时间(也可以传入session)
            //以json存放,这里使用的是阿里的fastjson
            json = new JSONObject();
            json.put("memPhone",memPhone);
            json.put("code",code);
            json.put("createTime",System.currentTimeMillis());
            // 将认证码存入redis,有效时长5分钟
            redisUtils.set("verifyCode"+memPhone,json,5L, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}

springboot+vue实现手机验证码功能_第3张图片
springboot+vue实现手机验证码功能_第4张图片

  1. 编写redisUtils,我用的网上的模板
    首先在配置文件写一下(我写的很简单,但是能用就行,redis密码默认没有就不写了)
    springboot+vue实现手机验证码功能_第5张图片
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
@Service
public class RedisUtils {
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 写入缓存
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 写入缓存设置时效时间
     *
     * @param key
     * @param value
     * @return
     */
    public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
        boolean result = false;
        try {
            ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
            operations.set(key, value);
            redisTemplate.expire(key, expireTime, timeUnit);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 批量删除对应的value
     *
     * @param keys
     */
    public void remove(final String... keys) {
        for (String key : keys) {
            remove(key);
        }
    }

    /**
     * 批量删除key
     *
     * @param pattern
     */
    public void removePattern(final String pattern) {
        Set<Serializable> keys = redisTemplate.keys(pattern);
        if (keys.size() > 0) {
            redisTemplate.delete(keys);
        }
    }

    /**
     * 删除对应的value
     *
     * @param key
     */
    public void remove(final String key) {
        if (exists(key)) {
            redisTemplate.delete(key);
        }
    }

    /**
     * 判断缓存中是否有对应的value
     *
     * @param key
     * @return
     */
    public boolean exists(final String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 读取缓存
     *
     * @param key
     * @return
     */
    public Object get(final String key) {
        Object result = null;
        ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
        result = operations.get(key);
        return result;
    }

    /**
     * 哈希 添加
     *
     * @param key
     * @param hashKey
     * @param value
     */
    public void hmSet(String key, Object hashKey, Object value) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        hash.put(key, hashKey, value);
    }

    /**
     * 哈希获取数据
     *
     * @param key
     * @param hashKey
     * @return
     */
    public Object hmGet(String key, Object hashKey) {
        HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
        return hash.get(key, hashKey);
    }

    /**
     * 列表添加
     *
     * @param k
     * @param v
     */
    public void lPush(String k, Object v) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        list.rightPush(k, v);
    }

    /**
     * 列表获取
     *
     * @param k
     * @param l
     * @param l1
     * @return
     */
    public List<Object> lRange(String k, long l, long l1) {
        ListOperations<String, Object> list = redisTemplate.opsForList();
        return list.range(k, l, l1);
    }

    /**
     * 集合添加
     *
     * @param key
     * @param value
     */
    public void add(String key, Object value) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        set.add(key, value);
    }

    /**
     * 集合获取
     *
     * @param key
     * @return
     */
    public Set<Object> setMembers(String key) {
        SetOperations<String, Object> set = redisTemplate.opsForSet();
        return set.members(key);
    }

    /**
     * 有序集合添加
     *
     * @param key
     * @param value
     * @param scoure
     */
    public void zAdd(String key, Object value, double scoure) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        zset.add(key, value, scoure);
    }

    /**
     * 有序集合获取
     *
     * @param key
     * @param scoure
     * @param scoure1
     * @return
     */
    public Set<Object> rangeByScore(String key, double scoure, double scoure1) {
        ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
        return zset.rangeByScore(key, scoure, scoure1);
    }
}
  1. 前端vue测试获取,随便把获取验证码60秒内不能重复获取做了
<template>
  <div>
    <el-form :model="loginForm">
      <el-form-item label="手机号">
        <el-input type="text" v-model="loginForm.username" style="width: 200px">el-input>
      el-form-item>
      <div class="login_box">
        <el-input type="text" v-model="loginForm.code" aria-placeholder="请输入验证码" style="width: 200px">el-input>
        <el-button  @click="postCode" :disabled="isClick">{{content}}el-button>
      div>
    el-form>
  div>
template>
<script>
//这是我封装的axios的方法,各位自己写即可
import {getCode, testCode} from "../api/admin/admin";

export default {
  name: "Login",
  data(){
    return{
      loginForm: {
        code:'',
        username:''
      },
      content: '发送验证码',  // 按钮里显示的内容
      totalTime: 60,      //记录具体倒计时时间
      isClick:false		//是否可以点击
    }
  },
  methods:{
  //发送验证码
    postCode(){
      getCode(this.loginForm.username).then(res =>{
        console.log(res)
      })
      //这是60秒倒计时
      this.countDown()
    },
    //这是60秒倒计时
    countDown () {
      this.content = this.totalTime + 's后重新发送' //这里解决60秒不见了的问题
      let clock = window.setInterval(() => {
        this.totalTime--
        this.content = this.totalTime + 's后重新发送'
        this.isClick=true
        if (this.totalTime < 0) {     //当倒计时小于0时清除定时器
          window.clearInterval(clock)
          this.content = '重新发送验证码'
          this.totalTime = 60
          this.isClick=false
        }
      },1000)
      console.log(111)
    }
  },
  computed:{
  }
}
script>
  1. 此时,验证码发送到了手机,并且存入到了redis
  2. 接下来验证,,还是在刚刚那个controller里面写,其实只要提取一下redis里面的数据即可,从前端传来的手机号,通过手机号获取刚刚存入redis的验证码,看看是否一样
@ResponseBody
    @PostMapping("/getCode")
    public JSONObject getCode(@RequestParam(value = "username") String username,String code){
        JSONObject Vcode = (JSONObject)redisUtils.get("verifyCode"+username);
        System.out.println("memPhone:"+username);
        System.out.println(Vcode);
        JSONObject verifyCode = (JSONObject)redisUtils.get("verifyCode"+username);
        System.out.println("传入的验证码是:"+code);
        if(verifyCode.get("code").equals(code)){
            System.out.println("验证码正确");
        }
        return Vcode;
    }

你可能感兴趣的:(vue,java,springboot)