Apache Freemarker:如何通过自定义指令校验处理accNo参数
实现方案
首先明确:可以通过自定义指令实现需求,以下是具体操作步骤:
1. 修改JSON模板
将原模板中的${accNo}替换为自定义指令调用,示例如下:
{ "Account_Number" : "<@validateAccount accNo=accNo />" }
2. 实现TemplateDirectiveModel自定义指令
编写Java类实现TemplateDirectiveModel接口,在execute方法中完成参数获取、校验与结果输出:
import freemarker.core.Environment; import freemarker.template.*; import java.io.IOException; import java.io.Writer; import java.util.Map; public class ValidateAccountDirective implements TemplateDirectiveModel { @Override public void execute(Environment env, Map params, TemplateModel[] loopVars, TemplateDirectiveBody body) throws TemplateException, IOException { // 获取传入的accNo参数 TemplateNumberModel accNoModel = (TemplateNumberModel) params.get("accNo"); if (accNoModel == null) { writeOutput(env.getOut(), "0000"); return; } // 转换数值并校验 long accNo = accNoModel.getAsNumber().longValue(); String result = accNo > 0 ? String.valueOf(accNo) : "0000"; // 输出处理结果 writeOutput(env.getOut(), result); } private void writeOutput(Writer writer, String content) throws IOException { writer.write(content); writer.flush(); } }
3. 注册自定义指令到FreeMarker配置
在初始化FreeMarker配置时,将自定义指令注册到全局变量中:
import freemarker.template.Configuration; import freemarker.template.TemplateExceptionHandler; import java.io.File; import java.io.IOException; public class FreemarkerConfig { public static Configuration getConfig() throws IOException { Configuration cfg = new Configuration(Configuration.VERSION_2_3_32); cfg.setDirectoryForTemplateLoading(new File("templates")); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); cfg.setLogTemplateExceptions(false); cfg.setWrapUncheckedExceptions(true); // 注册指令,名称需与模板中使用的一致 cfg.setSharedVariable("validateAccount", new ValidateAccountDirective()); return cfg; } }
补充说明
- 若
accNo是带前导零的字符串类型,需调整参数获取逻辑:将TemplateNumberModel替换为TemplateScalarModel,再尝试转为数值校验,避免类型转换异常。 - 也可选择更简洁的自定义方法(实现
TemplateMethodModelEx),模板中直接写成${validateAccount(accNo)},实现逻辑如下:
import freemarker.template.*; import java.util.List; public class ValidateAccountMethod implements TemplateMethodModelEx { @Override public Object exec(List args) throws TemplateModelException { if (args.isEmpty()) return "0000"; TemplateModel arg = (TemplateModel) args.get(0); long accNo = 0; if (arg instanceof TemplateNumberModel) { accNo = ((TemplateNumberModel) arg).getAsNumber().longValue(); } else if (arg instanceof TemplateScalarModel) { try { accNo = Long.parseLong(((TemplateScalarModel) arg).getAsString()); } catch (NumberFormatException e) { accNo = 0; } } return accNo > 0 ? String.valueOf(accNo) : "0000"; } }
注册时替换为cfg.setSharedVariable("validateAccount", new ValidateAccountMethod());即可。
内容的提问来源于stack exchange,提问作者Bhanu
相关产品推荐
相关产品推荐

