我需要从可以在tomcat和jboss上部署的java应用程序访问jndi上下文。
我找不到一种方法来访问它,所以我写了这段代码:
try{
String webserver = getWebServer();
Logger logger=Logger.getLogger("myLog");
if(webserver.equalsIgnoreCase("Jboss")){
logger.severe("Webserver: " + webserver);
Hashtable<String, String> ht= new Hashtable();
ht.put(InitialContext.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
ht.put(InitialContext.PROVIDER_URL,"jnp://localhost:1099");
ht.put(InitialContext.URL_PKG_PREFIXES,"org.jboss.naming:org.jnp.interfaces");
InitialContext ic=new InitialContext(ht);
if(ic!=null){
logger.severe("success");/*I am getting success as output here*/
DataSource ds=(DataSource)ic.lookup(getDatasource());
/*this is where it's failing*/
if(ds!=null){
logger.severe("success1");
}
return ds.getConnection();
}
return null;
}
else{
logger.severe("Webserver: " + webserver);
// Obtain our environment naming context
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
// Look up our data source
DataSource ds = (DataSource) envCtx.lookup(getDatasource());
// Allocate and use a connection from the pool
Connection conn = ds.getConnection();
return conn;
}
}
有没有办法避免丑陋的“if条件”并为jboss / tomcat使用相同的代码行?
谢谢!