2012-11-19 32 views
0

我使用Velocity 1.7来格式化字符串,并且我在使用默认值时遇到了一些麻烦。 Velocity本身在没有设置值的情况下没有特殊的语法,我们想使用另一个默认值。 通过速度的手段,它看起来像:DisplayTool的安装和使用

#if(!${name})Default John#else${name}#end 

这是unconveniant我的情况。 google搜索,我发现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(\“This is a long string。\”,10)“without changes,but should get

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

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

回答

1

在您调用Velocity之前,URL的构造发生在您的Java代码中,因此Velocity不会评估$display.alt(\"not null\",\"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; 

它可能会更好,不过,你DisplayTool方法直接从Velocity模板调用。这就是example usage中显示的内容。

+0

谢谢,但我正在寻找一些东西给我方便的工具来格式化字符串,而不使用模板。并且,当收到字符串时,我不知道确切位置将在什么位置引用以及它的默认值是什么。一切都应该通过特殊表达来设置。我认为显示工具提供了这个功能。可惜它没有。不管怎样,谢谢你。 – me1111

+0

@ me1111查看Apache Commons Lang中的[StringUtils](http://commons.apache.org/lang/StringUtils.html)类,特别是'defaultString '和'defaultEmpty'方法。 –

+0

谢谢,但如果我将使用java的标准方法,那么没有理由使用Velocity。我被告知研究什么更快,更舒适。找到另一个我认为可以代替Velocity - Freemarker的工具,默认情况下,它具有像unsafe_expr!default_expr一样的优势。感谢您的时间。 – me1111