diff --git a/alerter/src/main/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtil.java b/alerter/src/main/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtil.java index fc9ea8f054d..ba1c64eae3d 100644 --- a/alerter/src/main/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtil.java +++ b/alerter/src/main/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtil.java @@ -44,14 +44,14 @@ public static String render(String template, Map replaceData) { } try { Matcher matcher = PATTERN.matcher(template); - StringBuilder buffer = new StringBuilder(); + StringBuilder builder = new StringBuilder(); while (matcher.find()) { Object objectValue = replaceData.getOrDefault(matcher.group(1), "NullValue"); String value = objectValue.toString(); - matcher.appendReplacement(buffer, value); + matcher.appendReplacement(builder, Matcher.quoteReplacement(value)); } - matcher.appendTail(buffer); - return buffer.toString(); + matcher.appendTail(builder); + return builder.toString(); } catch (Exception e) { log.error(e.getMessage(), e); return template; diff --git a/alerter/src/test/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtilTest.java b/alerter/src/test/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtilTest.java index 76c5627934e..6a2cf642391 100644 --- a/alerter/src/test/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtilTest.java +++ b/alerter/src/test/java/org/dromara/hertzbeat/alert/util/AlertTemplateUtilTest.java @@ -62,4 +62,17 @@ void render() { template = "${key1} ${key2} ${key3}"; assertEquals(AlertTemplateUtil.render(template, param), "Just for testing"); } + + @Test + void renderSpecialCharacters() { + Map param = new HashMap<>(); + param.put("valueWithDollar", "$100"); + param.put("valueWithBackslash", "C:\\Users"); + + String template = "The price is ${valueWithDollar} and the path is ${valueWithBackslash}"; + + // Expected to handle the dollar sign and backslash correctly without throwing an exception + String expectedResult = "The price is $100 and the path is C:\\Users"; + assertEquals(expectedResult, AlertTemplateUtil.render(template, param)); + } } \ No newline at end of file