SSM框架通过榛子云短信接口实现发送短信验证码进行注册功能
程序员文章站
2022-06-04 16:22:31
...
SSM实现通过手机号接收验证码进行注册
1.安装SDK
下载地址 仔细阅读API让你事半功倍
2. 申请测试账号,获取appId、appSecret
注意:要实现发送短信需要短信模板,提交给官方审核通过才能使用。
由于官方给出的小demo使用的是servlet进行业务处理,并且未连接数据库,由于使用的是SSM框架,所以需进行转换。
目录结构:
@Controller
@RequestMapping("/register")
public class RegisterController {
private SqlSessionFactory sqlSessionFactory;
private Reader reader;
@RequestMapping("/exRegister")
public void exRegister(HttpServletRequest request, HttpServletResponse response, Model model, Student student) {
String number = request.getParameter("number");
String verifyCode = request.getParameter("verifyCode");
String error = SessionUtil.validate(request.getSession(), number, verifyCode);
if (!error.equals("")) {
renderData(response, error);
return;
}
//其他业务代码
renderData(response, "success");
try {
reader = Resources.getResourceAsReader("mybatis_config.xml");//连接数据库
sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);//创建会话工厂
SqlSession session = sqlSessionFactory.openSession();//打开会话
/*调用service进行数据库操作
*
* */
session.close();
} catch (IOException e) {
e.printStackTrace();
}
}
protected void renderData(HttpServletResponse response, String data) {
try {
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().write(data);
} catch (Exception e) {
e.printStackTrace();
}
}
@Controller
@RequestMapping("/message")
public class SendController {
/**
* 跳转发送验证码页面
*/
@RequestMapping("/send")
public String send() {
return "code";
}
/**
* 执行发送验证码操作
*/
@RequestMapping("/exSend")
public void exSend(HttpServletRequest request,HttpServletResponse response) {
try {
String number = request.getParameter("number");
String templateId = request.getParameter("templateId");
JSONObject json = null;
//生成6位验证码
String verifyCode = String.valueOf(new Random().nextInt(899999) + 100000);
System.out.print("验证码: " + verifyCode);
ZhenziSmsClient client = new ZhenziSmsClient(Config.apiUrl, Config.appId, Config.appSecret);
Map<String, Object> params = new HashMap<String, Object>();
params.put("number", number);
params.put("templateId", templateId);
String[] templateParams = {verifyCode, "5分钟内有效"};
params.put("templateParams", templateParams);
String result = client.send(params);
json = JSONObject.parseObject(result);
if (json.getIntValue("code") != 0) {//发送短信失败
renderData(response, "获取失败:" + json.getString("data"));
return;
}
//将验证码存到session中,同时存入创建时间
HttpSession session = request.getSession();
SessionUtil.save(session, number, verifyCode, 5 * 60);
renderData(response, "success");
return;
} catch (Exception e) {
e.printStackTrace();
}
}
protected void renderData(HttpServletResponse response, String data){
try {
response.setContentType("text/plain;charset=UTF-8");
response.getWriter().write(data);
} catch (Exception e) {
e.printStackTrace();
}
}
}
上一篇: Django中使用qrcode生成二维码
下一篇: 使用 python 生成二维码