Velocity不解析foreach循环中的变量

har*_*ode 5 java foreach velocity

我有非常简单的速度模板:

<html>
    <head>
        <title>Velocity template</title>
    </head>
    <body>      
        #foreach($p in $products)
            $p.name
        #end        
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

以及处理它的代码:

VelocityEngine engine = new VelocityEngine();
engine.init();
Template t = engine.getTemplate("./src/com/irbis/dms/velocity/template.html");
VelocityContext ctx = new VelocityContext();

Product p1 = new Product("fridge");
Product p2 = new Product("sofa");
Product p3 = new Product("table");
Product p4 = new Product("chair");

List<Product> products = new ArrayList<Product>();
products.add(p1);
products.add(p2);
products.add(p3);
products.add(p4);

ctx.put("products", products);
...

class Product implements Serializable {

    private String name;

    public Product() {
    }

    public Product(String name) {
        super();
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
Run Code Online (Sandbox Code Playgroud)

但执行后我有以下内容:

<html>
    <head>
        <title>Velocity template</title>
    </head>
    <body>      
                    $p.name
                    $p.name
                    $p.name
                    $p.name
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

如果我放入上下文字符串,整数等,它工作正常.错误在哪里?我用的是速度1.5.

Mar*_*erg 5

您必须将Product类声明为public,否则您将无法在模板中使用它。

public class Product implements Serializable {
Run Code Online (Sandbox Code Playgroud)