0

我正在尝试学习 JSF,但我对数据表有疑问。我从数据库中获取数据并将它们添加到我的列表中并尝试在我的页面中显示它们。它写入数据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..

谢谢你的支持..

4

1 回答 1

1

正如我评论的那样,每次调用 getter 时,您都会重新记录列表,因此列表正在增长,因为您没有在任何地方清除它。这是一个更好的方法:

// 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;
}
于 2013-05-31T17:36:57.397 回答