第五讲
拉取依赖
<dependency>
<groupId>com.zhenzikj</groupId>
<artifactId>zhenzisms</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
编写短信验证类
编写配置类
zhenzi:
apiUrl:
appId:
appSecret:
templateId:
invalidTimer: 1
编写config层
package demo.config;
import com.zhenzi.sms.ZhenziSmsClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
@Configuration
public class zhenziCode {
@Value("${zhenzi.apiUrl}")
private String apiUrl;
@Value("${zhenzi.appId}")
private String appId;
@Value("${zhenzi.appSecret}")
private String appSecret;
public String printRandom(){
//取随机产生的验证码(4位数字)
Random rnd = new Random();
int randNum = rnd.nextInt(8999) + 1000;
//将整型数字转化成字符串
String randStr = String.valueOf(randNum);
return randStr;
}
public String sendMessage(String randNum,String phoneNum) throws Exception {
ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
Map<String, Object> params = new HashMap<String, Object>();
params.put("number", phoneNum);
params.put("templateId","10097");
String[] templateParams = new String[2];
templateParams[0] = randNum;
templateParams[1] = "张志超很哇塞";
params.put("templateParams", templateParams);
String result = client.send(params);
return result;
}
}
编写controller类
package demo.controller;
import demo.config.zhenziCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* ┏┓ ┏┓
* ┏┛┻━━━┛┻┓
* ┃ ┃
* ┃ ━ ┃
* ┃ ┳┛ ┗┳ ┃
* ┃ ┃
* ┃ ┻ ┃
* ┃ ┃ @Auther: wangshenghui
* ┗━┓ ┏━┛ @Date: 2022/08/10/19:02
* ┃ ┃神兽保佑
* ┃ ┃代码无BUG!
* ┃ ┗━━━┓
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛
*
*/
@Controller
public class PhoneNumController {
@Autowired
private zhenziCode zhenziCode;
@ResponseBody
@RequestMapping(value= "/Phon",method = RequestMethod.POST)
public String toCode(HttpServletRequest request,String phoneNum) throws Exception{
HttpSession session = request.getSession(true);
String random = zhenziCode.printRandom();
session.setAttribute("randStr",random);
System.out.println("sendCode"+random);
System.out.println(phoneNum);
return zhenziCode.sendMessage(random,phoneNum);
}
}