Context ctx=new InitialContext();
ds=(DataSource)ctx.lookup("java:resources/env/entry/jdbc/bsw");
异常:
Exception in thread "main" javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(Unknown Source)
at javax.naming.InitialContext.getDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(Unknown Source)
at javax.naming.InitialContext.lookup(Unknown Source)
at com.Test.test(Test.java:17)
at com.Test.main(Test.java:27)
------解决方案--------------------
你在 Tomcat 中配置了 JNDI 吗?也就是在 %TOMCAT_HOME%/conf/server.xml 当前应用的 Context 下应该有 Resource 和 WatchedResource 两项的,而 lookup 中的字符串就是 Resource 中 name 的名字。若前缀是 java:comp/env/ 则可以缺省。
------解决方案--------------------
server.xml
<Context 项目配置>
<Resource name="test" auith="Container" type="javax.sql.DataSource"/>
下面是连接具体配置
</Context>
Context initContext=new InitialContext();
Context envContext=(Context)initContext.lookup("java:/comp/env");
DataSource ds=(DataSource)envContext.lookup("test");