2017-04-06 64 views
2

我想用Spring MVC在瀏覽器中顯示來自數據庫的數據。除了每個循環的Thymeleaf模板之外,一切都很好。那裏有什麼不對。如何顯示Thymeleaf中每個循環的對象集合?

如何顯示在IDid數據和名稱name數據通過對象集合迭代與每個循環?

的源代碼:

<!DOCTYPE HTML> 
<html xmlns:th="http://www.thymeleaf.org"> 
<head> 
    <title>Getting Started: Serving Web Content</title> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> 
</head> 
<body> 
    <table border="1"> 
     <tr style="font-size: 13"> 
      <td>ID</td> 
      <td>Name</td> 
     </tr> 
     <tr th:each="count : ${id}"> 
      <td><p th:text="${count}" /></td>  
      <td><p th:text="${name}" /></td>   

     </tr> 
    </table> 
</body> 
</html> 

回答

6

你的問題不是很清楚,因爲你沒有指定count對象,並沒有表現出你的控制器。

那麼假設你有一些實體Count與領域idname,其中您在數據庫中的相應表堅持下去,並且要在Thymeleaf模板來顯示。

若要從數據庫中檢索數據,你需要一些服務類,應該有方法,返回你的實體的List這種服務方法listAll()的,例如:

public List<Count> listAll() { 
    List<Count> counts = new ArrayList<>(); 
    countRepository.findAll().forEach(counts::add); 
    return counts; 
} 

然後你您需要在您的控制器中設置請求映射,並在該方法中將一個屬性添加到model對象,這將是執行listAll()方法的結果。它可以這樣做,如:

@RequestMapping("/list") 
public String countsList(Model model) { 
    model.addAttribute("counts", countService.listAll()); 
    return "list"; 
} 

最後回答你的問題,你的list.html模板應包含塊:

<div th:if="${not #lists.isEmpty(counts)}"> 
    <h2>Counts List</h2> 
    <table class="table table-striped"> 
     <tr> 
      <th>Id</th> 
      <th>Name</th> 
     </tr> 
     <tr th:each="count : ${counts}"> 
      <td th:text="${count.id}"></td> 
      <td th:text="${count.name}"></td> 
     </tr> 
    </table> 
</div> 

閱讀Thymeleaf文檔的詳細信息 - Iteration Basics部分。

+0

對不起,但你做得很好!這是我所需要的。非常感謝! – Just4Fun

+0

很高興聽到,歡迎您;) – DimaSan

+1

不錯的工作,把從開始到結束的順序信息。正是我在尋找的東西。儘管我只需要最後一部分,但這是一個非常有用的格式。 – user1445967

相關問題