2012-03-08 52 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