From 3f91690d5a8fc504c3517f6f02e6afe288b78ba0 Mon Sep 17 00:00:00 2001 From: whcrow Date: Tue, 25 Jun 2019 01:10:36 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B8=B2=E6=9F=93=E6=A8=A1=E6=9D=BF=E6=97=B6?= =?UTF-8?q?=E5=8E=BB=E9=99=A4=E6=A8=A1=E6=9D=BF=E4=B8=AD#if|#else|#elseif|?= =?UTF-8?q?#end|#foreach|#set=E5=89=8D=E7=9A=84=E7=A9=BA=E6=A0=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/com/sjhy/plugin/tool/VelocityUtils.java | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/src/main/java/com/sjhy/plugin/tool/VelocityUtils.java b/src/main/java/com/sjhy/plugin/tool/VelocityUtils.java index cd46e2e..46306c7 100644 --- a/src/main/java/com/sjhy/plugin/tool/VelocityUtils.java +++ b/src/main/java/com/sjhy/plugin/tool/VelocityUtils.java @@ -9,6 +9,8 @@ import java.io.PrintWriter; import java.io.StringWriter; import java.util.Map; import java.util.Properties; +import java.util.regex.Matcher; +import java.util.regex.Pattern; /** * Velocity工具类,主要用于代码生成 @@ -30,6 +32,8 @@ public class VelocityUtils { INIT_PROP.setProperty("runtime.log.logsystem.log4j.logger", "velocity"); } + private static final Pattern REMOVE_SPACES = Pattern.compile("[ ]*(#if|#else|#elseif|#end|#foreach|#set)"); + /** * 禁止创建实例对象 */ @@ -37,6 +41,14 @@ public class VelocityUtils { throw new UnsupportedOperationException(); } + /** + * 去除模板中#if|#else|#elseif|#end|#foreach|#set前的空格 + */ + private static String removeSpaces(String template) { + Matcher matcher = REMOVE_SPACES.matcher(template); + return matcher.replaceAll("$1"); + } + /** * 渲染模板 * @@ -59,7 +71,7 @@ public class VelocityUtils { velocityEngine.setProperty(VelocityEngine.OUTPUT_ENCODING, settings.getEncode()); try { // 生成代码 - velocityEngine.evaluate(velocityContext, stringWriter, "Velocity Code Generate", template); + velocityEngine.evaluate(velocityContext, stringWriter, "Velocity Code Generate", removeSpaces(template)); } catch (Exception e) { // 将异常全部捕获,直接返回,用于写入模板 StringBuilder builder = new StringBuilder("在生成代码时,模板发生了如下语法错误:\n"); -- Gitee