java - 如何在 Spark Web 框架和 Velocity 模板框架中创建 for 循环?

标签 java loops frameworks velocity spark-java

这是我的 Main.java

public class Main {
    public static void main(String[] args) {

        // Create some students
        Student students[] = new Student[4];

        students[0] = new Student("Abe");
        students[1] = new Student("Bill");
        students[2] = new Student("Chris");
        students[3] = new Student("Darrel");

        staticFileLocation("/public");

        String layout = "templates/layout.vtl";

        get("/", (request, response) -> {
            HashMap model = new HashMap();
            model.put("template", "templates/home.vtl" );
            return new ModelAndView(model, layout);
        }, new VelocityTemplateEngine());

        get("/view_students", (request, response) -> {
            HashMap model = new HashMap();

            model.put("students", students );
            // model.put("student", new Student() );

            return new ModelAndView(model, "templates/view_students_layout.vtl");
        }, new VelocityTemplateEngine());

    }
}

这是 view_students_layout.vtl

<!DOCTYPE html>
<html>
  <head>
    <title>Hello Friend!</title>
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'>
  </head>
  <body>
    <div class="container">

    <h1>Students</h1>

    <ul>

      #foreach( $Student in $students )
        <li>${Student.name}</li>
      #end

    </ul>

    </div>
  </body>
</html>

当我运行 Spark 时,我得到以下内容

<!DOCTYPE html>
<html>
  <head>
    <title>Hello Friend!</title>
    <link rel='stylesheet' href='https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css'>
  </head>
  <body>
    <div class="container">

    <h1>Students</h1>

    <ul>

              <li>${Student.name}</li>
              <li>${Student.name}</li>
              <li>${Student.name}</li>
              <li>${Student.name}</li>

    </ul>

    </div>
  </body>
</html>

我遗漏或误解了什么?我是否以错误的方式将数组发送到框架?

谢谢。

最佳答案

Student 类必须具有 public String getName() 方法或 public String get(String key) 方法。您要么尝试直接访问 name 字段,要么忘记将其访问器公开。

如果您想直接向模板公开公共(public)字段,则需要 2.0.0-SNAPSHOT 版本(开发版本)。请参阅http://velocity.apache.org/engine/devel/developer-guide.html 可插入自省(introspection)部分。

关于java - 如何在 Spark Web 框架和 Velocity 模板框架中创建 for 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34280002/

相关文章:

java - SQL Server 存储过程和 jdbc

Java在上传到AWS云之前创建文件副本

java - 帮助使用 Spring 创建图像 servlet

swift - 将 Xcode MVC 项目导出到 .framework 文件

java - 在无状态 EJB 方法中使用 Timer 来使长时间运行的操作超时

java - 尝试使用循环来处理备用数组

loops - 在Pascal中“for i:= 0 to i”循环-为什么有效?

javascript - 使用 Jquery 遍历表单中的元素

javascript - 在 VueJs + SlimPHP 中输​​入图像文件

swift - 无法将属性声明为开放,因为其类型使用内部类型 (Typealias)