2017-06-15 44 views
-1

我使用NetBeans JNDI創造了GlassFish服務器的JDBC連接池(jdbc/WILLIAMSON)沒有初始化,我想在所有servlet使用該如此,而不是在每一個servlet的寫下面的代碼JDBC連接池變量上下文可能

 InitialContext context = new InitialContext(); 
     //The JDBC Data source that we just created 
     DataSource datasource = (DataSource) 
     context.lookup("jdbc/WILLIAMSON"); 
     Connection connection = null; 
      connection = ds.getConnection(); 

我創建了一個類DBCONN,並試圖在每個servlet中調用此類的對象,但出現錯誤「變量上下文可能未被初始化」。見我的代碼如下:

 public final class DBCONN {  
     private static final InitialContext context; 
     private static final DataSource datasource; 
     static{    
      try { 
       context = new InitialContext(); 
       datasource=(DataSource) context.lookup("jdbc/WILLIAMSON"); 
      } catch (NamingException ex) { 
       Logger.getLogger(DBCONN.class.getName()).log(Level.SEVERE, 
      null, ex); 
      } 
    } 
    private DBCONN() { 
     // I am confused how to use this method, pls guide me 
    }// ERROR HERE VARIABLE context MIGHT NOT HAVE BEEN INITIALIZED 

    public static Connection getConnection() throws SQLException { 
    return datasource.getConnection(); 
    } 

    } 

我打電話datasource.getConnection()在servlet的HOME.java

 DBCONN datasource = new DBCONN(); 
     Connection connection = null; 
     connection = datasource.getConnection();// I am accessing a static 
     method so warning coming accessing static method getConnection(), how 
     to avoid it??? 
+0

使用全部大寫被認爲是喊,不這樣做。 –

+0

plz幫助我找到上述問題的答案? – Williamson

回答

0

行更改爲private static InitialContext context = null;。編譯器警告你在某些情況下可能不會創建context

+0

我修改,但得到的靜態嵌段內誤差不能分配一個值到最終變量上下文 – Williamson

+0

@Williamson卸下'final'關鍵字。 –

+0

好吧,但它是線程安全的刪除最終的關鍵字? – Williamson

-2
static{ 
context = new InitialContext(); 
try { 
datasource=(DataSource) context.lookup("jdbc/WILLIAMSON"); 
} catch (NamingException ex) { 
Logger.getLogger(DBCONN.class.getName()).log(Level.SEVERE, null, ex);   }                   
+1

你應該修改你的答案補充的所有細節,而沒有回答一次。 –

+0

靜態{ 上下文=新的InitialContext(); 嘗試datasource =(DataSource)context.lookup(「jdbc/WILLIAMSON」); (LogNo.getLogger(DBCONN.class.getName()).log(Level.SEVERE,null,ex); } – user2902870

+0

編輯你的答案並添加必要的細節,不要在這裏評論! –