簡體   English   中英

如何在Spark Web Framework和Velocity Template Framework中進行for循環?

[英]How can I make a for loop in Spark Web Framework and the Velocity Template Framework?

這是我的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字段,或者忘記了公開其訪問器。

如果要直接向模板公開公共字段,則需要2.0.0-SNAPSHOT版本(開發版本)。 請參閱http://velocity.apache.org/engine/devel/developer-guide.html部分可插拔自省

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM