java代码实现简单的短信验证码发送,给验证码设置五分钟有效期,一次发送后60秒内不能重复发送,并把验证码放到session中,判断输入的号码是否与刚才发送的一致

标题 java代码实现简单的短信验证码发送,并把验证码放到session中,判断输入的号码是否与刚才发送的一致

controller

package com.zl.controller;

import com.zl.service.IVerifyCodeService;
import com.zl.util.JSONResult;
import com.zl.bean.vo.SMSUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class VerifyCodeController {


    @Autowired
    private IVerifyCodeService verifyCodeService;


    @RequestMapping("sendVerifyCode")
    @ResponseBody
    public JSONResult sendVerifyCode(String phoneNumber){

        JSONResult json=new JSONResult();

        try{
            verifyCodeService.sendVerifyCode(phoneNumber);

        }catch (RuntimeException re){
            json.setMsg(re.getMessage());
            json.setSuccess(false);
        }
        return json;

    }



}

Serviceimpl

package com.zl.service.impl;

import java.util.Map;
import java.util.Date;
import java.util.HashMap;

import com.zl.bean.util.UserContext;
import com.zl.bean.vo.VerifyCodeVO;
import com.zl.service.IVerifyCodeService;
import com.zl.util.BidConst;
import com.zl.util.DateUtil;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import org.springframework.stereotype.Service;

@Service
public class VerifyCodeServiceimpl implements IVerifyCodeService {
	//对应你阿里云账户的 accessKeyId
	private String accessKeyId = "";
	//对应你阿里云账户的 accessKeySecret
	private String accessKeySecret = "";
	//对应签名名称
	private String signName = "";
	//对应模板代码
	private String templateCode = "";
	//随机生成6位数验证码(int)Math.round(Math.random()*(0-1000000)+1000000)

	/**
	 * 短信发送
	 *
	 * @param phoneNumber 发送的手机号
	 * @return ture发送短信成功,false失败
	 */
	public void sendVerifyCode(String phoneNumber) {
		VerifyCodeVO vc = UserContext.getCurrentVerifyCode();
		if (vc == null || DateUtil.secondsBetween(new Date(), vc.getLastSendTime()) > 60) {
			String verifyCode = Math.round(Math.random() * (0 - 1000000) + 1000000) + "";
			//初始化ascClient
			DefaultProfile profile = DefaultProfile.getProfile("default", accessKeyId, accessKeySecret);
			IAcsClient client = new DefaultAcsClient(profile);
			//创建发送短信请求
			CommonRequest request = new CommonRequest();
			//request.setProtocol(ProtocolType.HTTPS);使用POST请求
			request.setMethod(MethodType.POST);
			//阿里云对应发送短信的服务器地址(固定)
			request.setDomain("dysmsapi.aliyuncs.com");
			//对应的版本号(固定)
			request.setVersion("2017-05-25");
			//短信服务方式(固定)
			request.setAction("SendSms");
			//要发送的电话号码
			request.putQueryParameter("PhoneNumbers", phoneNumber);
			//签名名称
			request.putQueryParameter("SignName", signName);
			//模板代码
			request.putQueryParameter("TemplateCode", templateCode);
			//验证码
			request.putQueryParameter("TemplateParam", "{\"code\":" + verifyCode + "}");
			System.out.println("yzm_" + verifyCode);
			try {
				//发送短信,并获取响应流
				CommonResponse response = client.getCommonResponse(request);
				//输出回调信息(Json字符串)
				System.out.println(response.getData());
				//将Json字符串转换为Map对象
				Map<String, Object> map = getMapToJson(response.getData());
				//判断短信是否发送成功
				if (map.get("Code").equals("OK")) {
					//创建短信验证码对象
					VerifyCodeVO verifyCodeVO = new VerifyCodeVO();
					verifyCodeVO.setLastSendTime(new Date());
					verifyCodeVO.setPhoneNumber(phoneNumber);
					verifyCodeVO.setVerifyCode(verifyCode);
					//将短信验证码存入Session
	            /*HttpSession session = request.getSession();
	            UserContext.putVerifyCode(verifyCodeVO);*/

					//	session.setAttribute("verifyCodeVO",verifyCodeVO );
					UserContext.putVerifyCode(verifyCodeVO);
				} else {
					throw new RuntimeException();
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				throw new RuntimeException("短信发送失败");
			}

		} else {
			throw new RuntimeException("发送频繁");
		}
	}



	@Override
	public boolean verify(String phoneNumber, String verifyCode) {
		VerifyCodeVO vc=UserContext.getCurrentVerifyCode();
		if(vc!=null
				&&  vc.getPhoneNumber().equals(phoneNumber)
				&&  vc.getVerifyCode().equalsIgnoreCase(verifyCode)
				&&  DateUtil.secondsBetween(new Date(), vc.getLastSendTime())<=BidConst.VERIFYCODE_VAILDATE_SECOND){
			return true;
		}
		return false;
	}

	public  String getTemplatecode() {
		return templateCode;
	}

	/**
	 * 将Json字符转换为map对象
	 * @param json
	 * @return
	 */
	public static Map<String, Object> getMapToJson(String json) {
		JSONObject jsonObject = JSONObject.parseObject(json);
		Map<String, Object> valueMap = new HashMap<String, Object>();
		valueMap.putAll(jsonObject);
		return valueMap;
	}

}

VerifyCodeVO 封装验证码,手机号,最后发送时间到session中

package com.zl.bean.vo;

import java.util.Date;

import lombok.Getter;
import lombok.Setter;

/**
 * 存放验证码相关内容,这个对象是放在session中的
 * 
 * @author Administrator
 * 
 */
@Getter
@Setter
public class VerifyCodeVO {
	
	private String verifyCode;//验证码
	private String phoneNumber;//发送验证码的手机号
	private Date lastSendTime;//最近成功发送时间

}
把VerifyCodeVO放到session中
```java
package com.zl.bean.util;

import javax.servlet.http.HttpSession;

import com.zl.bean.Logininfo;
import com.zl.bean.vo.VerifyCodeVO;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 用于存放当前用户的上下文
 * 
 * @author Administrator
 * 
 */
public class UserContext {

	public static final String VERIFYCODE_IN_SESSION = "verifycode_in_session";

	/**
	 * 反向获取request的方法,请查看RequestContextListener.requestInitialized打包过程
	 * 
	 * @return
	 */
	private static HttpSession getSession() {
		return ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest().getSession();
	}

	
	public static void putVerifyCode(VerifyCodeVO vc) {
		getSession().setAttribute(VERIFYCODE_IN_SESSION, vc);
	}

	/**
	 * 得到当前的短信验证码
	 * 
	 * @return
	 */
	public static VerifyCodeVO getCurrentVerifyCode() {
		return (VerifyCodeVO) getSession().getAttribute(VERIFYCODE_IN_SESSION);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值