2013-05-31 84 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; 
}