NoInitialContextException

2019-06-13 04:00发布

问题:

I have a problem. I want to connect to database using JDBC, I have Tomcat server. For this I use connection pool.

According to Internet tutorials I've written: context.xml:

<?xml version="1.0" encoding="UTF-8"?>

<Context antiJARLocking="true" path="/Server" docBase="dbcp" debug="5"
         reloadable="true" crossContext="true">

    <Resource name="jdbc/TestDB" auth="Container"
          type="javax.sql.DataSource" removeAbandoned="true"
          removeAbandonedTimeout="30" maxActive="100"
          maxIdle="30" maxWait="10000" username="root"
          password="newpass"
          driverClassName="com.mysql.jdbc.Driver"
          url="jdbc:mysql://localhost:3306/delta_server"/>

</Context>

web.xml :

<resource-ref>
      <description>DB Connection Pooling</description>
      <res-ref-name>jdbc/TestDB</res-ref-name>
      <res-type>javax.sql.DataSource</res-type>
      <res-auth>Container</res-auth>
  </resource-ref>

and I try to connect...

Connection conn=null;
DataSource ds;
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:comp/env");
ds = (DataSource) envContext.lookup("jdbc/TestDB");
conn = ds.getConnection();

But I get a mistake: 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

What to do???