あなたは、接続サービスクラスを持つことができます:あなたは以下を追加する必要があり、あなたのweb.xmlに
public class ConnectionDB {
private Context initContext;
private static Context webContext;
private static DataSource dataSource = null;
private ConnectionDB() {
try {
initContext = new InitialContext();
webContext = (Context) initContext.lookup("java:/comp/env");
dataSource = (DataSource) webContext.lookup("name_ds");
} catch (NamingException e) {
e.printStackTrace();
}
}
public static DataSource getDS() {
if (dataSource == null) {
new ConnectionDB();
}
return dataSource;
}
}
(この例では、すでにデータソースのアプリケーションサーバーでセットアップを持っていると仮定し):
を
<resource-ref>
<res-ref-name>name_ds</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
私は@ManagedBeanとして持っていないことに注意してください。以下のように
次に、あなたは、あなたの他のサービス・クラスでの接続を開始するために、そのクラスを使用することができます。
public class Test{
private Connection conn;
private PreparedStatement prstmt;
private ResultSet rs;
public void testMethod() {
try {
conn = ConnectionDB.getDS().getConnection();
//create your sql, result sets and prepare statements
}
catch (SQLException e) {
e.printStackTrace();
}
}
}