2013-05-31 85 views
0

我想學習JSF,我有一個數據表的問題。 我從數據庫中獲取數據並將它們添加到我的列表中,並嘗試在我的頁面中顯示它們。它寫數據3次。爲什麼?這裏是我的代碼...Jsf datatable寫我的數據3倍

這裏是bean的相關部分..

public ArrayList<videos> getVideoss() { 
    Connection con1 = null; 
    PreparedStatement pst1 = null; 
    ResultSet rs1 = null; 

    String url1 = "jdbc:postgresql://localhost:5432/db"; 
    String user1 = "postgres"; 
    String password11 = "123"; 

    try { 

     Class.forName("org.postgresql.Driver"); 
     con1 = DriverManager.getConnection(url1, user1, password11); 
     pst1 = con1 
       .prepareStatement("SELECT video_name FROM videos WHERE video_course = '" 
         + selectedCourse + "';"); 
     rs1 = pst1.executeQuery(); 

     while (rs1.next()) { 
     videoss.add(new videos(rs1.getString(1))); 

     } 
     System.out.println(videoss.size()); 
     ..... 

XHTML文件

<h:dataTable value="#{videoSearch.videoss}" var="videos"> 
    <h:column>     
    <f:facet name="header">Video Name</f:facet>     
    #{videos.videoName} 
    </h:column> 
    </h:dataTable> 

當我看着它去像6,12列表的大小, 18 ..但它應該是6 ..

感謝您的支持..

+1

你'getVideoss()'消氣部件創建數據表,但你每次調用時不清除它...你也應該移動數據列表創建到構造函數或'@ PostConstruct'方法。 –

+0

是的,它的作品! :) 非常感謝你 。 – mft

+0

作爲完整答案發布! –

回答

1

正如我評論,你recreting的名單E吸氣時間很長,所以名單越來越多,因爲你沒有清理任何地方。這裏是一個更好的方式來做到這一點:我懷疑

// Will be called only one time 
@PostConstruct 
public init() 
{ 
    Connection con1 = null; 
    PreparedStatement pst1 = null; 
    ResultSet rs1 = null; 

    String url1 = "jdbc:postgresql://localhost:5432/Thesis"; 
    String user1 = "postgres"; 
    String password11 = "123"; 

    videoss = new ArrayList(); 

    try 
    { 
     Class.forName("org.postgresql.Driver"); 
     con1 = DriverManager.getConnection(url1, user1, password11); 
     pst1 = con1.prepareStatement("SELECT video_name FROM videos WHERE video_course = '" + selectedCourse + "';"); 
     rs1 = pst1.executeQuery(); 

     while (rs1.next()) 
     { 
      videoss.add(new videos(rs1.getString(1))); 
     } 

     System.out.println(videoss.size()); 

     //..... 
    } 
    catch(Excepption e) 
    { 
     e.printStackTrace(); 
    } 
} 

public ArrayList<videos> getVideoss() 
{ 
    return videoss; 
}