消息模板占位符的使用

消息模板占位符的使用

一. 使用@占位符

说明:根据@占位符进去匹配占位
案例:“模板名称:@tplName@,发生了变更,变更描述:@tplName@的变更描述是:@descr@”;

1. 占位符解析
//解析占位符拼接消息模板
 public String getContent(MsgType msgType, Map<String, String> messageAttrMap) {
		//获取带占位符的消息模板
        String result = messageTypeRepo.getByCode(msgType.name()).getContentTemplate();
       //result = "模板名称:@tplName@,发生了变更,变更描述:@tplName@的变更描述是:@descr@";

        Pattern pattern = Pattern.compile("@(.*?)@");
        Matcher matcher = pattern.matcher(result);
        while (matcher.find()) {
            //占位符
            String placeholder = matcher.group();
            String key = placeholder.substring(1, placeholder.length() - 1);
            if (messageAttrMap.containsKey(key)) {
                String value = "null";
                if (Objects.nonNull(messageAttrMap.get(key))) {
                    value = messageAttrMap.get(key).trim();
                }
                result = StringUtils.replaceAll(result, placeholder, value);
               // System.out.println(result);
            }
        }
        return result;
    }
2. 占位符参数的赋值
  @ApiModelProperty(value = "消息模板类型",required = true)
    private MsgType msgType;
     @ApiModelProperty(value = "消息内容的属性",required = true)
    private Map<String, Object> msgAttrMap;//key可能有重复的属性字段,需要替换,value则为替换的字段的值,用于消息模板的占位

二 使用$占位符

    public String getMsgContent(Map<String, Object> varMap,String msgTemplate) {

        StandardELContext elContext = new StandardELContext(factory);
        for(Map.Entry<String,Object> en:varMap.entrySet()){
            if(en.getValue()!=null){
                elContext.getVariableMapper()
                        .setVariable(en.getKey(),factory.createValueExpression(en.getValue(),
                                en.getValue().getClass()));
            }
        }
        // String pl = "${name}";
        ValueExpression e = factory.createValueExpression(elContext, msgTemplate, String.class);
        return String.valueOf(e.getValue(elContext));
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值