2012-03-08 54 views
0

我使用此代码从数据库表中获取数据。重新加载多次后,JSF页面会冻结

public List<Dashboard> getDashboardList() throws SQLException { 

     if (ds == null) { 
      throw new SQLException("Can't get data source"); 
     } 

     //get database connection 
     Connection con = ds.getConnection(); 

     if (con == null) { 
      throw new SQLException("Can't get database connection"); 
     } 

     PreparedStatement ps = con.prepareStatement(
       "SELECT * from GLOBALSETTINGS"); 

     //get customer data from database 
     ResultSet result = ps.executeQuery(); 

     List<Dashboard> list = new ArrayList<Dashboard>(); 

     while (result.next()) { 
      Dashboard cust = new Dashboard(); 

      cust.setUser(result.getString("SessionTTL")); 
      cust.setPassword(result.getString("MAXACTIVEUSERS")); 


      //store all data into a List 
      list.add(cust); 
     } 

     return list; 
    } 

此代码是部署在glassfish服务器上的JSF页面的一部分。问题是,当我多次(大约8次)重新加载JSF页面时,网页冻结。我怀疑线程池是填充的,并且没有空间用于新的连接。我如何解决这个问题?当查询完成或有其他方法时关闭连接?

最良好的祝愿

+0

您能告诉我们如何配置该数据源吗?它首先汇集在一起​​吗? – 2012-03-08 20:31:30

+0

这段代码是否真的是你的jsf页面的一部分(所以你使用的是JSP)?或者它是支持bean的一部分?如果是后者,bean的范围是什么? – 2012-03-08 20:32:48

+0

我做了几个屏幕截图的池配置:http://imageshack.us/g/827/screenshotbg.png/ – 2012-03-08 20:48:18

回答

3

首先:是的,你应该关闭你的连接,当你通过显式调用close()方法来完成。关闭连接将释放数据库资源。

更新:你也应该关闭PreparedStatement(与close())。我还建议在你的方法中处理SQLExceptions,而不是抛出它,因为即使发生异常,你也需要确保你的语句和连接是关闭的。

事情是这样的:

Connection connection = dataSource.getConnection(); 
try { 
    PreparedStatement statement = connection.prepareStatement(); 
    try { 
     // Work with the statement 
    catch (SQLException e) { 
     // Handle exceptions 
} catch (SQLException e { 
    // Handle exceptions 
    } finally { 
     statement.close(); 
    } 
} finally { 
    connection.close(); 
} 

此外,你不应该查询一个bean字段的getter方法的数据库。在每次请求期间,可以多次调用Getters。更优雅的方法是在构造函数中准备DashboardList,或者在bean的@PostConstruct中准备DashboardList。

+0

如果我理解正确,我必须在公开列表前放置@PostConstruct getDashboardList()throws SQLException {? – 2012-03-08 21:21:28

+0

不,getDashboardList()是bean字段的getter。创建一种新方法,例如'@PostConstruc public void init()'你在哪里填充DashboardList。吸气剂然后只返回填充的列表。 – 2012-03-08 21:24:50

+0

现在我得到这个错误:ORA-00604:在递归SQL级别1时发生错误ORA-01000:超出最大打开游标ORA-01000:超过最大打开游标。我用这个语句关闭了连接--con.close(); – 2012-03-08 21:26:32