Maven 显示工具的安装和使用

Maven 显示工具的安装和使用,maven,velocity,Maven,Velocity,我使用Velocity 1.7格式化字符串,但在使用默认值时遇到了一些问题。Velocity本身并没有特殊的语法,用于未设置值的情况,我们希望使用另一个默认值。 通过速度,它看起来像: #if(!${name})Default John#else${name}#end 这对我的案子来说是不可信的。 谷歌搜索后,我发现DisplayTool,根据文档,它看起来像: $display.alt($name,"Default John") 所以我添加了maven依赖项,但不确定如何将DisplayT

我使用Velocity 1.7格式化字符串,但在使用默认值时遇到了一些问题。Velocity本身并没有特殊的语法,用于未设置值的情况,我们希望使用另一个默认值。 通过速度,它看起来像:

#if(!${name})Default John#else${name}#end
这对我的案子来说是不可信的。 谷歌搜索后,我发现DisplayTool,根据文档,它看起来像:

$display.alt($name,"Default John")
所以我添加了maven依赖项,但不确定如何将DisplayTool添加到我的方法中,很难找到相关说明。 也许有人可以提供建议或提供有用的链接

我的方法:

public String testVelocity(String url) throws Exception{

    Velocity.init();
    VelocityContext context = getVelocityContext();//gets simple VelocityContext object 
    Writer out = new StringWriter();
    Velocity.evaluate(context, out, "testing", url);

    logger.info("got first results "+out);

    return out.toString();
}
当我发送

String url = "http://www.test.com?withDefault=$display.alt(\"not null\",\"exampleDefaults\")&truncate=$display.truncate(\"This is a long string.\", 10)";
String result = testVelocity(url);
我得到“http://www.test.com?withDefault=$display.alt(\“not null\”,\“exampleDefaults\”)&truncate=$display.truncate(\“这是一个长字符串。\”,10)”没有更改,但应该得到

"http://www.test.com?withDefault=not null&truncate=This is...

请告诉我我错过了什么。谢谢。

URL的构造发生在您调用Velocity之前的Java代码中,因此Velocity不会计算
$display.alt(\“notnull\”,\“exampleDefaults\”)
。该语法仅在Velocity模板(通常具有
.vm
扩展名)中有效

在Java代码中,不需要使用
$
符号,您可以直接调用DisplayTool方法。我以前没有使用过
DisplayTool
,但可能是这样的:

DisplayTool display = new DisplayTool();
String withDefault = display.alt("not null","exampleDefaults");
String truncate = display.truncate("This is a long string.", 10);
String url = "http://www.test.com?" 
    + withDefault=" + withDefault 
    + "&truncate=" + truncate;

不过,最好直接从Velocity模板调用
DisplayTool
方法。这就是。

中显示的内容,谢谢,但我正在寻找一些东西,为我提供一个方便的工具,只格式化字符串,而不使用模板。当收到字符串时,我不知道引用的确切位置以及它的默认值。所有内容都应通过特殊表达式在字符串中设置。我认为显示工具提供了这一点。可惜没有。谢谢。@me1111看看Apache Commons Lang中的类,特别是
defaultString
defaultEmpty
方法。谢谢,但是如果我要使用java的标准方法,那么就没有理由使用Velocity了。我被告知要研究什么意味着更快、更舒适。找到了一个我认为可以替代Velocity-Freemarker的工具,默认情况下它有smth,比如不安全的expr!默认表达式。谢谢你抽出时间。