2015-12-15 40 views
0

這裏是我的Main.java如何在Spark Web Framework和Velocity Template Framework中創建for循環?

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> 

當我運行的火花,我得到以下

<!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> 

我在想什麼或誤解?我是否以錯誤的方式將數組發送到框架?

謝謝。

回答

1

學生類必須有public String getName()方法或public String get(String key)方法。您要麼嘗試直接訪問name字段,要麼您忘記將其訪問者公開。

如果您想直接向公共字段公開模板,那麼您將需要2.0.0-SNAPSHOT版本(開發版本)。請參閱http://velocity.apache.org/engine/devel/developer-guide.html插入式自檢

+0

非常感謝!我試着看着你鏈接的相同的指南,無法找到任何關於我的問題。 – Ergosphere