spring boot使用properties定义短信模板的方法教程
2018-01-14 09:24
656 查看
前言
通常我们做开发时候会遇到短信发送邮件发送之类的需求,发送内容往往会由客户提供一个模板,如果我们是在程序里拼接字符串来搞定这个模板,很明显是一种坑队友的做法。一般将模板放入properties文件中,使用的时候替换其中的一些变量即可。
本文我们使用springboot来实现根据模板发送短信验证码的功能,下面话不多说了,来一起看看详细的介绍吧。
tips:
1、正则表达式
2、springboot读取properties文件
模板定义
将需要定义的短信模板都定义在msg.properties文件,目录同application.properties,注意其中的【[code]】即为要替换的变量。
tem.msg.verify.code=验证码为:[code],请勿泄露给其他人。
读取properties
定义组件MSGConstants,指定需要加载的properties文件,用来读取定义的模板,使用spring的@Value注解
@PropertySource("classpath:msg.properties") @Component public class MSGConstatns { @Value("${tem.msg.verify.code}") private String sendCodeMsg; public String getSendCodeMsg() { return sendCodeMsg; } public void setSendCodeMsg(String sendCodeMsg) { this.sendCodeMsg = sendCodeMsg; } }
解析模板工具类
考虑到公用,将参数设置为Map,即需要替换的变量,正则表达式替换找到对应的key,我这里key的格式为:{key},可根据自己情况进行修改,同时修改正则。
public static String getContent(Map<String, String> params,String content) { String reg = "\\{\\w*}";// Pattern pattern = Pattern.compile(reg); Matcher matcher = pattern.matcher(content); while (matcher.find()) { String group = matcher.group();// String key = group.substring(1, group.length() - 1); if (!params.containsKey(key)) throw new NormalException("未找到需要替换的key:" + key); content = content.replace(group, params.get(key)); } return content; }
测试
一个很简单的ajax请求,返回获取到的短信内容
@RestController @RequestMapping("demo") public class DemoController { @Resource private MSGConstatns msgConstatns; @RequestMapping("msg") public String msgContent(){ String code = "123456";//正式开发中一般采用随机数 Map<String,String> params = new HashMap<>(); params.put("code",code); return SendCodeUtil.getContent(params,msgConstatns.getSendCodeMsg()); } }
结果
期望值:验证码为:123456,请勿泄露给其他人
实际效果:
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对脚本之家的支持。
您可能感兴趣的文章:
相关文章推荐
- wordpress教程:检测当前页面使用的哪个模板文件的方法
- 使用Spring替换properties文件定义属性的方法
- Python类的定义、继承及类对象使用方法简明教程
- wordpress教程:检测当前页面使用的哪个模板文件的方法
- python基础教程之类class定义使用方法
- spring boot使用i18n时properties文件中文乱码问题的解决方法
- spring boot使用thymeleaf模板的方法详解
- struts2教程:10、动态方法调用和使用通配符定义action
- python基础教程之类class定义使用方法
- Android开发教程之Fragment定义、创建与使用方法详解【包含Activity通讯,事务执行等】
- Python类的定义、继承及类对象使用方法简明教程
- 类模板的定义和使用方法
- android studio开发教程 ListActivity的2种使用方法:系统默认布局和自己定义布局
- JSP教程(三)--JSP中”预定义变量”的使用
- 使用J2SE API读取Properties文件的六种方法
- 使用J2SE API读取Properties文件的六种方法
- Win Vista使用教程之UAC详细使用方法
- 使用J2SE API读取Properties文件的六种方法
- 使用J2SE API读取Properties文件的六种方法(1)
- 在PHP世界中选择最合适的模板与使用方法第1/2页