运行环境:tomcate7.0 IDE:myeclipse2017 jdk:1.8 spring依赖jar ojdbc14.jar
1.在tomcat目录下conf/context.xml文件中 加入以下代码
<Resource name="jdbc/orcl"
auth="Container"
type="javax.sql.DataSource"
driverClassName="oracle.jdbc.driver.OracleDriver"
url="jdbc:oracle:thin:@localhost:1521:ORCL"
username="zhangsan"
password="zs123"
maxActive="100"
maxIdle="30"
maxWait="10000" />
2.在spring的配置文件applicationcontext.xml文件里面配置
<!-- JNDI -->
<bean id="dataSource"
class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName"
value="java:comp/env/jdbc/orcl">
</property>
3.写测试类打印出数据源的连接对象
main{
Context context = new InitialContext();
DataSource dSource =(DataSource) context.lookup("java:comp/env/jdbc/orcl");
Connection connection = dSource.getConnection();
System.out.println(connection);
connection.close();
}
打印连接对象然后测试一直报错:
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(NamingManager.java:645)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:325) at javax.naming.InitialContext.lookup(InitialContext.java:392) 后来看到论坛里的回复才知道原因在用JNDI连接数据库时用main函数测试时总报错,InitialContext 是要在应用服务器的上下文里才有的。你在普通的应用程序里怎么行!放到tomcat里面运行看看吧!
不能用main函数直接测试,只能放到tomcat或者servlet、jsp显示
jsp里面这样写:
<%
Context context = new InitialContext();
DataSource dSource =(DataSource) context.lookup("java:comp/env/jdbc/orcl");
Connection connection = dSource.getConnection();
System.out.println("连接对象在console显示:"+connection);
out.println("连接对象在jsp显示:"+connection);
connection.close();
%>
我这样写问题解决了
连接对象在console显示:jdbc:oracle:thin:@localhost:1521:ORCL, UserName=ZHANGSAN, Oracle JDBC driver
注意要加ojdbc14.jar到项目中,在这里浪费了很多时间,特此标记一下。