繁体   English   中英

java字符串表达式解析器

[英]java string expression parser

我被要求在一个字符串中包含数学表达式:“价格:$ {price},税:$ {price} * $ {tax)”

该字符串是在运行时给出的,并且Map值也是

我为此使用了Velocity:

行家:

    <properties>
        <velocity.version>1.6.2</velocity.version>
        <velocity.tools.version>2.0</velocity.tools.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity</artifactId>
            <version>${velocity.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.velocity</groupId>
            <artifactId>velocity-tools</artifactId>
            <version>${velocity.tools.version}</version>
        </dependency>
    </dependencies>

Java的:

public class VelocityUtils {
    public static String mergeTemplateIntoString(String template, Map<String,String> model)
    {
        try
        {
            final VelocityEngine ve = new VelocityEngine();
            ve.init();
            final VelocityContext context = new VelocityContext();
            context.put("math", new MathTool());
            context.put("number", new NumberTool());

            for (final Map.Entry<String, String> entry : model.entrySet())
            {
                final String macroName = entry.getKey();
               context.put(macroName, entry.getValue());
            }
            final StringWriter wr = new StringWriter();

            final String logStr = "";
            ve.evaluate(context, wr, logStr,template);

            return wr.toString();
        } catch(Exception e)
        {
            return "";
        }

    }
}

测试类别:

public class VelocityUtilsTest
{
    @Test
    public void testMergeTemplateIntoString() throws Exception
    {
        Map<String,String> model = new HashMap<>();
        model.put("price","100");
        model.put("tax","22");
        String parsedString = VelocityUtils.mergeTemplateIntoString("price: ${price} tax: ${tax}",model);
        assertEquals("price: 100 tax: 22",parsedString);

        String parsedStringWithMath = VelocityUtils.mergeTemplateIntoString("price: $number.integer($math.div($price,2))",model);
        assertEquals("price: 50",parsedStringWithMath);

    }
}

改用SPel会更好吗?

我同意这是一个题外话,但我认为仍然值得回答。

使用模板引擎的整个想法是,您需要在运行时访问模板。 如果是这样,那么可以肯定,Velocity是一个不错的选择。 然后,您可以提供HTML的新版本,并且假设您没有更改所使用的变量,则不必提供应用程序本身的新版本(重新编译)。

但是,如果您只是使用Velocity节省时间,那么这里并没有节省太多:您可以使用StringTokenizer在另外几行代码中完成此操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM