I'm trying to display the IP address of the current machine in a Velocity template. I assumed I could do this simply by including the line
$java.net.InetAddress.getLocalHost().getAddress()
in the template.
However, the line is not evaluated and is displayed as is; the log shows a null reference:
Null reference [template 'login.vm', line 43, column 11] : $java.net.InetAddress.getLocalHost().getAddress() cannot be resolved.
What did I do wrong?
According to the documentation it should be done in the following way:
1) add desired class to the context:
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) use this name for retrieving its methods in the template:
$InetAddress.getLocalHost()
Also note, that $InetAddress.getLocalHost().getAddress()
will return your byte array which can not be displayed as ip address. It will display array's toString()
value. Better to use $InetAddress.getLocalHost().getHostAddress()
.