我正在尝试学习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 ..
感谢您的支持..
答案 0 :(得分: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;
}