2017-06-15 23 views
-1

ich einen JDBC-Verbindungspool erstellt (jdbc/WILLIAMSON) in Glassfish-Server JNDI in Netbeans verwenden, möchte ich dies so in allen Servlets verwenden, anstatt zu schreiben, den folgenden Code in jedem ServletJDBC-Verbindungs ​​Variable Kontext Pooling möglicherweise nicht initialisiert wurden

Ich habe eine Klasse DBCONN erstellt und versucht, ein Objekt dieser Klasse in jedem Servlet aufzurufen, aber Fehler "Variablenkontext wurde möglicherweise nicht initialisiert". Sehen Sie meinen Code unten:

 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(); 
    } 

    } 

ich das datasource.getConnection() in Servlet HOME.java Aufruf

 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

Die Verwendung aller Großbuchstaben wird als Geschrei betrachtet, tun Sie das nicht. –

+0

plz helfen Sie mir bei der Suche nach der Antwort der oben genannten Frage? – Williamson

Antwort

0

Ändern Sie die Zeile zu private static InitialContext context = null;. Der Compiler warnt Sie, dass unter bestimmten Umständen context möglicherweise nicht erstellt wird.

+0

Ich habe geändert, aber Fehler innerhalb des statischen Blocks erhalten - kann dem endgültigen variablen Kontext keinen Wert zuweisen – Williamson

+0

@Williamson Entferne das Schlüsselwort 'final'. –

+0

ok, aber ist es thread-sicher, endgültiges Schlüsselwort zu entfernen? – 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

Sie sollten Ihre Antwort ändern, um alle Details hinzuzufügen, anstatt sie noch einmal zu beantworten. –

+0

statisch { context = neu InitialContext(); versuchen { datasource = (DataSource) context.lookup ("jdbc/WILLIAMSON"); } catch (NamingException ex) { Logger.getLogger (DBCONN.class.getName()). Log (Level.SEVERE, null, ex); } – user2902870

+0

Bearbeiten Sie Ihre Antwort und fügen Sie notwendige Details hinzu, kommentieren Sie nicht hier! –

Verwandte Themen