模板引擎实现通用简单规则校验

2020-03-12  本文已影响0人  晚歌歌
依赖:
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
        </dependency>

测试类:
@Test
    public void testCompare() throws Exception {
        String temp = "<#if (%s)>true<#else>false</#if>";
        String exp = "3.13 > 3.122";
        String realTemp = Strings.formatIfArgs(temp, exp);
        System.out.println(realTemp);
        Template template = new Template("temp", realTemp, new Configuration(Configuration.VERSION_2_3_28));
        System.out.println(FreeMarkerTemplateUtils.processTemplateIntoString(template, null));
        
    }

输出:
<#if (3.13 > 3.122)>true<#else>false</#if>
true

在规则校验中,"3.13 > 3.122" 可以视为请求参数加上两个变量。
数据库中简单设计三个字段:参数名、比较符、规则值
简单规则校验中:通过参数名反射获得参数值,连同比较符和规则值拼接成为一个判断表达式,利用模板引擎就可以实现一个通用的简单规则校验。
或者更简单一点直接保存好需要执行的表达式,留下一个参数位的占位符即可。

上一篇下一篇

猜你喜欢

热点阅读