在Velocity模板中使用InetAddress

时间:2017-05-24 09:07:08

标签: java velocity

我正在尝试在Velocity模板中显示当前机器的IP地址。我以为我可以通过包含行

来做到这一点
$java.net.InetAddress.getLocalHost().getAddress()

在模板中。

然而,该行未被评估并按原样显示;日志显示空引用:

  

空引用[template'login.vm',第43行,第11列]:$ java.net.InetAddress.getLocalHost()。getAddress()无法解析。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

根据documentation,应按以下方式完成:

1)在上下文中添加所需的类:

Template t = ve.getTemplate("q44153836.vm");    

VelocityContext context = new VelocityContext();
context.put("InetAddress", java.net.InetAddress.class);

StringWriter writer = new StringWriter();
t.merge(context, writer);

2)使用此名称在模板中检索其方法:

$InetAddress.getLocalHost()

另请注意,$InetAddress.getLocalHost().getAddress()将返回无法显示为ip地址的字节数组。它将显示数组的toString()值。最好使用$InetAddress.getLocalHost().getHostAddress()

相关问题