Velocity templates not substituting methods

本小妞迷上赌 提交于 2020-01-02 03:16:14

问题


In the Velocity User's Guide it seems pretty straight forward to use methods in templates. I tried, but could not make it work. Can someone tell me what I did wrong?

Thanks.

This is my code

@Test
public void testVelocity() {
  Velocity.init();
  VelocityContext map = new VelocityContext();
  map.put("test", "Success");
  map.put("ok", "OK!");
  map.put("func", new Object() {public String test() {return "Yay!";}});
  map.put("func2", new Object() {public String test(String t) {return t+t;}});

  String template = "${func.test()} $test $func2.test($ok)";
  StringWriter writer = new StringWriter();
  Velocity.evaluate(map, writer, "", new StringReader(template));
  assertEquals("Yay! Success OK!OK!", writer.toString());
}

and this is the output:

org.junit.ComparisonFailure: 
Expected :Yay! Success OK!OK!
Actual   :${func.test()} Success $func2.test($ok)

Variable substitutions seems to work fine, but not method calls.

Please help.


回答1:


The problem is that for security reasons Velocity only allows calling public methods of public classes. An anonymous class is not public, thus the call is blocked.

It would work if you put a real object, an instance of a public class.

It would also work if you disable the secure uberspector, but that is not a good idea, since it opens up the system.



来源:https://stackoverflow.com/questions/18233883/velocity-templates-not-substituting-methods

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!